-
Notifications
You must be signed in to change notification settings - Fork 1
/
jsonrpc.js
183 lines (167 loc) · 5.56 KB
/
jsonrpc.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
/**
* Provides RPC functionality over WebSockets using the JSON-RPC protocol.
*
* @see http://www.jsonrpc.org/
* @example
* const socket = new WebSocket('wss://www.example.com/rpc');
* const rpc = new JSONRPC(socket);
* rpc.call('greet', { name: 'Alice' }).then(function(response) {
* console.log("Success!", response);
* }).catch(function(error) {
* console.log("Failed!", error);
* });
*/
class JSONRPC {
/**
* @param {WebSocket} webSocket - WebSocket instance to use for RPC.
* @param {object} [methods={}] - Local methods that the server can invoke.
* @throws {TypeError} - If argument is not a WebSocket.
*/
constructor(webSocket, methods = {}) {
if (!(webSocket instanceof WebSocket)) {
throw new TypeError('Argument is not of type WebSocket.');
}
/** System extension methods that the server can invoke. */
this.extensions = {};
/** Local methods that the server can invoke. */
this.methods = methods;
this._callbackId = 0;
this._callbacks = new Map();
this._socket = webSocket;
this._socket.onmessage = (message) => {
let data;
try {
data = JSON.parse(message.data);
} catch (e) {
this._error(e, message);
return;
}
if (data instanceof Array) {
data.forEach(x => this._processMessage(x));
} else {
this._processMessage(data);
}
};
}
/**
* Gets the callback function that gets called when an error occurs.
* @type {function}
*/
get onerror() {
return this._onerror;
}
/**
* Sets the callback function that gets called when an error occurs.
* @type {function(error: Error)}
* @throws {TypeError} - If callback is not a function.
*/
set onerror(callback) {
if (typeof callback !== 'function') {
throw new TypeError('Callback is not a function.');
}
this._onerror = callback;
}
/**
* Gets the callback function for error responses.
* @type {function}
*/
get onResponseError() {
return this._onResponseError;
}
/**
* Sets the callback function for error responses.
* @type {function}
* @throws {TypeError} - If callback is not a function.
*/
set onResponseError(callback) {
if (typeof callback !== 'function') {
throw new TypeError('Callback is not a function.');
}
this._onResponseError = callback;
}
/**
* Call a remote function.
* @param {string} method - Method name to call.
* @param {object} params - Method parameters to pass.
* @returns {Promise}
*/
call(method, params) {
const message = {
jsonrpc: '2.0',
method: method,
params: params,
id: this._callbackId
};
this._callbackId++;
const promise = new Promise((resolve, reject) => {
this._callbacks.set(message.id, { resolve, reject });
this._socket.send(JSON.stringify(message));
});
return promise;
}
/**
* Call a remote function as a notification without a callback.
* @param {string} method - Method name to call.
* @param {object} params - Method parameters to pass.
*/
notify(method, params) {
const message = {
jsonrpc: '2.0',
method: method,
params: params
};
this._socket.send(JSON.stringify(message));
}
/**
* @private
*/
_error(message, data) {
const error = new Error(message);
error.data = data;
if (this.onerror !== undefined) {
this.onerror(error);
}
}
/**
* @private
*/
_processMessage(data) {
if (data.hasOwnProperty('result')) {
if (this._callbacks.has(data.id)) {
this._callbacks.get(data.id).resolve(data.result);
this._callbacks.delete(data.id);
} else {
this._error(`Unknown response id: ${data.id}.`, data);
}
} else if (data.hasOwnProperty('method')) {
if (data.method.startsWith('rpc.')) {
const method = data.method.slice(4);
if (this.extensions.hasOwnProperty(method)) {
const response = this.extensions[method](data.params);
if (data.id !== undefined) {
this._socket.send(JSON.stringify(response));
}
} else {
this._error(`Server called an unknown extension method: ${method}.`, data);
}
} else if (this.methods.hasOwnProperty(data.method)) {
const response = this.methods[data.method](data.params);
if (data.id !== undefined) {
this._socket.send(JSON.stringify(response));
}
} else {
this._error(`Server called method on client that does not exist: ${data.method}.`, data);
}
} else if (data.hasOwnProperty('error')) {
if (this.onResponseError !== undefined) {
this.onResponseError(data);
}
if (data.id !== undefined && this._callbacks.has(data.id)) {
this._callbacks.get(data.id).reject(data);
this._callbacks.delete(data.id);
}
} else {
this._error('Invalid message received.', data);
}
}
}