forked from grpc-ecosystem/grpc-cloud-run-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
39 lines (34 loc) · 1020 Bytes
/
server.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
// The package @grpc/grpc-js can also be used instead of grpc here
const grpc = require('grpc');
const protoLoader = require('@grpc/proto-loader');
const packageDefinition = protoLoader.loadSync(
__dirname + '/calculator.proto',
{keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
const calculatorProto = grpc.loadPackageDefinition(packageDefinition);
const PORT = process.env.PORT;
function calculate(call, callback) {
const request = call.request;
let result;
if (request.operation === 'ADD') {
result = request.first_operand + request.second_operand;
} else {
result = request.first_operand - request.second_operand;
}
callback(null, {result});
}
function main() {
const server = new grpc.Server();
server.addService(calculatorProto.Calculator.service, {calculate});
server.bindAsync(`0.0.0.0:${PORT}`, grpc.ServerCredentials.createInsecure(), (error, port) => {
if (error) {
throw error;
}
server.start();
});
}
main();