This repository has been archived by the owner on Dec 15, 2023. It is now read-only.
forked from speedymonster/node-grpc-interceptors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-proxy.js
73 lines (70 loc) · 2.67 KB
/
server-proxy.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
const utils = require('./utils');
const grpc = require('@grpc/grpc-js');
const handler = {
get(target, propKey) {
if (propKey !== 'addService') {
return target[propKey];
}
return (service, implementation) => {
const newImplementation = {};
const lookup = utils.lookupServiceMetadata(service, implementation);
for (const k in service) {
const name = k;
const fn = implementation[k];
newImplementation[name] = (call, callback) => {
const ctx = {
call,
service: lookup(name),
};
const newCallback = callback => {
return (...args) => {
ctx.status = {
code: grpc.status.OK,
};
const err = args[0];
if (err) {
ctx.status = {
code: grpc.status.UNKNOWN,
details: err,
};
}
callback(...args);
};
};
const interceptors = target.intercept();
const first = interceptors.next();
const errorCb = grpcServiceError => callback(grpcServiceError, null);
if (!first.value) { // if we don't have any interceptors
return new Promise(resolve => {
return resolve(fn(call, newCallback(callback)));
});
}
first.value(ctx, function next() {
return new Promise(resolve => {
const i = interceptors.next();
if (i.done) {
return resolve(fn(call, newCallback(callback)));
}
return resolve(i.value(ctx, next, errorCb));
});
}, errorCb);
};
}
return target.addService(service, newImplementation);
};
},
};
module.exports = (server) => {
server.interceptors = [];
server.use = fn => {
server.interceptors.push(fn);
};
server.intercept = function* intercept() {
let i = 0;
while (i < server.interceptors.length) {
yield server.interceptors[i];
i++;
}
};
return new Proxy(server, handler);
};