forked from Justinidlerz/GRPC-node-example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
66 lines (62 loc) · 1.75 KB
/
server.js
File metadata and controls
66 lines (62 loc) · 1.75 KB
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
const grpc = require('grpc');
const path = require('path');
const PROTO_PATH = path.join(__dirname, '/article.proto');
const article = grpc.load(PROTO_PATH).article;
let db = require('./db.json');
class Article {
getList (call, callback) {
return callback(null, {
articles: db
})
}
getById (call, callback) {
for (var i = 0; i < db.length; i++) {
if (db[i].id === call.request.id) {
return callback(null, db[i]);
}
}
return callback('Can not find article.');
}
insert (call, callback) {
let newArticle = Object.assign({}, call.request);
newArticle.id = (db.length + 1) + '';
db.push(newArticle);
return callback(null, newArticle);
}
update (call, callback) {
if (!call.request.id) {
return callback('Article id can not find.');
}
for( var i = 0; i < db.length; i++) {
if (db[i].id === call.request.id) {
const newArticle = Object.assign(db[i], call.request);
db.splice(i, 1, newArticle);
return callback(null, newArticle);
}
}
return callback('Can not find article.');
}
remove (call, callback) {
if (!call.request.id) {
return callback('Article id can not find.');
}
for( var i = 0; i < db.length; i++) {
if (db[i].id === call.request.id) {
db.splice(i, 1);
return callback(null);
}
}
return callback('Can not find article.');
}
}
const getServer = function (service, serviceCall, lintener){
const server = new grpc.Server();
server.addService(service, serviceCall);
server.bind(lintener, grpc.ServerCredentials.createInsecure());
return server;
}
function main() {
const articleServer = getServer(article.service, new Article, '0.0.0.0:50051');
articleServer.start();
}
main();