-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
132 lines (115 loc) · 3.16 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
const { EventEmitter } = require('events');
function rawr({ transport, timeout = 0, handlers = {} }) {
let callId = 0;
const pendingCalls = {};
const methodHandlers = {};
const notificationEvents = new EventEmitter();
notificationEvents.on = notificationEvents.on.bind(notificationEvents);
transport.on('rpc', function(msg) {
if(msg.id) {
if(msg.params && methodHandlers[msg.method]) { //handle the request
methodHandlers[msg.method](msg);
return;
}
else { //handle the result
const promise = pendingCalls[msg.id];
if(promise) {
if(promise.timeoutId) {
clearTimeout(promise.timeoutId);
}
delete pendingCalls[msg.id];
if (msg.error) {
promise.reject(msg.error);
}
else {
promise.resolve(msg.result);
}
}
return;
}
}
// handle notification
msg.params.unshift(msg.method);
notificationEvents.emit.apply(notificationEvents, msg.params);
});
function addHandler(methodName, handler) {
methodHandlers[methodName] = function(msg) {
Promise.resolve()
.then(function() {
return handler.apply(this, msg.params);
})
.then(function(result) {
transport.send({
id: msg.id,
result: result
});
})
.catch(function(error) {
const serializedError = {message: error.message};
if(error.code) {
serializedError.code = error.code;
}
transport.send({
id: msg.id,
error: serializedError
});
});
}
}
for (const m in handlers) {
addHandler(m, handlers[m]);
}
const methods = new Proxy({}, {
get: function(target, name) {
return function (...args) {
const id = ++callId;
const msg = {
jsonrpc : '2.0',
method: name,
params: args,
id
};
let timeoutId;
if(timeout) {
timeoutId = setTimeout(function() {
if(pendingCalls[id]) {
const err = new Error('RPC timeout');
err.code = 504;
pendingCalls[id].reject(err);
delete pendingCalls[id];
}
}, timeout);
}
const response = new Promise(function(resolve, reject) {
pendingCalls[id] = { resolve: resolve, reject: reject, timeoutId: timeoutId };
});
transport.send(msg);
return response;
}
}
});
const notifiers = new Proxy({}, {
get: function(target, name) {
return function (...args) {
const msg = {
jsonrpc : '2.0',
method: name,
params: args
};
transport.send(msg);
return;
}
}
});
const notifications = new Proxy({}, {
get: function(target, name) {
return function (callback) {
notificationEvents.on(name.substring(2), function(...args) {
return callback.apply(callback, args);
});
}
}
});
return { methods, addHandler, notifications, notifiers };
}
module.exports = rawr;