-
Notifications
You must be signed in to change notification settings - Fork 0
/
storyMicroservice.js
95 lines (84 loc) · 2.29 KB
/
storyMicroservice.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const sqlite3 = require('sqlite3').verbose();
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const storyProtoPath = 'story.proto';
const storyProtoDefinition = protoLoader.loadSync(storyProtoPath, {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
});
const storyProto = grpc.loadPackageDefinition(storyProtoDefinition).story;
const db = new sqlite3.Database('./database.db');
db.run(`
CREATE TABLE IF NOT EXISTS storys (
id INTEGER PRIMARY KEY,
title TEXT,
description TEXT
)
`);
const storyService = {
getStory: (call, callback) => {
const { story_id } = call.request;
db.get('SELECT * FROM storys WHERE id = ?', [story_id], (err, row) => {
if (err) {
callback(err);
} else if (row) {
const story = {
id: row.id,
title: row.title,
description: row.description,
};
callback(null, { story });
} else {
callback(new Error('story not found'));
}
});
},
searchStorys: (call, callback) => {
db.all('SELECT * FROM storys', (err, rows) => {
if (err) {
callback(err);
} else {
const storys = rows.map((row) => ({
id: row.id,
title: row.title,
description: row.description,
}));
callback(null, { storys });
}
});
},
CreateStory: (call, callback) => {
const { story_id, title, description } = call.request;
db.run(
'INSERT INTO storys (id, title, description) VALUES (?, ?, ?)',
[story_id, title, description],
function (err) {
if (err) {
callback(err);
} else {
const story = {
id: story_id,
title,
description,
};
callback(null, { story });
}
}
);
},
};
const server = new grpc.Server();
server.addService(storyProto.StoryService.service, storyService);
const port = 50056;
server.bindAsync(`0.0.0.0:${port}`, grpc.ServerCredentials.createInsecure(), (err, port) => {
if (err) {
console.error('Failed to bind server:', err);
return;
}
console.log(`Server is running on port ${port}`);
server.start();
});
console.log(`story microservice running on port ${port}`);