-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (64 loc) · 1.66 KB
/
index.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
/*
eslint
no-multi-spaces: ["error", {exceptions: {"VariableDeclarator": true}}]
padded-blocks: ["error", {"classes": "always"}]
max-len: ["error", 80]
*/
'use strict'
const { ServerCredentials, Server, load } = require('grpc')
const isObject = require('is.object')
const getPropValue = require('get-property-value')
class GrpcServer {
constructor (config = {}) {
const address = config.address || '0.0.0.0:50051'
const credentials = isObject(config.credentials)
? setAuthentication(config.credentials)
: ServerCredentials.createInsecure()
this._server = new Server()
this._server.bind(address, credentials)
}
addServices (services = []) {
if (!services.length) {
this._server.forceShutdown()
throw new Error('you must add some services')
}
try {
for (let svc in services) {
const service = `${services[svc].package}.${services[svc].name}.service`
const proto = getPropValue(load(services[svc].proto), service)
this._server.addService(proto, services[svc].methods)
}
} catch (ex) {
this._server.forceShutdown()
throw new Error(`check your service config and proto file: ${ex.message}`)
}
return this
}
start (cb) {
this._server.start()
cb()
}
stop (cb) {
this._server.tryShutdown(shutdow)
function shutdow () {
setTimeout(cb, 50)
}
}
}
module.exports = function factory (config) {
return new GrpcServer(config)
}
//
// help functions
//
function setAuthentication (certs) {
return ServerCredentials.createSsl(
null,
[
{
'cert_chain': certs.server,
'private_key': certs.key
}
]
)
}