forked from koorchik/node-mole-rpc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoleServer.js
More file actions
90 lines (71 loc) · 2.48 KB
/
MoleServer.js
File metadata and controls
90 lines (71 loc) · 2.48 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const errorCodes = require('./errorCodes');
class MoleServer {
constructor({ transports }) {
if (!transports) throw new Error('TRANSPORT_REQUIRED');
this.transportsToRegister = transports;
this.methods = {};
}
expose(methods) {
this.methods = methods;
}
async registerTransport(transport) {
await transport.onData(this._processRequest.bind(this, transport));
}
async removeTransport(transport) {
await transport.shutdown(); // TODO
}
async _processRequest(transport, data) {
const requestData = JSON.parse(data);
let responseData;
if (Array.isArray(requestData)) {
// TODO Batch error handling?
responseData = await Promise.all(
requestData.map(request => this._callMethod(request, transport))
);
} else {
responseData = await this._callMethod(requestData, transport);
}
return JSON.stringify(responseData);
}
async _callMethod(request, transport) {
const isRequest = request.hasOwnProperty('method');
if (!isRequest) return ''; // send nothing in response
const { method: methodName, params = [], id } = request;
const methodNotFound =
!this.methods[methodName] ||
typeof this.methods[methodName] !== 'function' ||
methodName === 'constructor' ||
methodName.startsWith('_') ||
this.methods[methodName] === Object.prototype[methodName];
let response = {};
if (methodNotFound) {
response = {
jsonrpc: '2.0',
id,
error: {
code: errorCodes.METHOD_NOT_FOUND,
message: 'Method not found'
}
};
} else {
this.currentTransport = transport;
const result = await this.methods[methodName].apply(this.methods, params);
if (!id) {
return ''; // For notifications do not respond. "" means send nothing
}
response = {
jsonrpc: '2.0',
result: typeof result === 'undefined' ? null : result,
id
};
}
return response;
}
async run() {
for (const transport of this.transportsToRegister) {
this.registerTransport(transport);
}
this.transportsToRegister = [];
}
}
module.exports = MoleServer;