-
Notifications
You must be signed in to change notification settings - Fork 18
/
simple-jsonrpc-js.js
518 lines (456 loc) · 17.2 KB
/
simple-jsonrpc-js.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
(function (root) {
'use strict';
/*
name: simple-jsonrpc-js
version: 1.0.0
*/
var _Promise = Promise;
if (typeof _Promise === 'undefined') {
_Promise = root.Promise;
}
if (_Promise === undefined) {
throw 'Promise is not supported! Use latest version node/browser or promise-polyfill';
}
var isUndefined = function (value) {
return value === undefined;
};
var isArray = Array.isArray;
var isObject = function (value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
};
var isFunction = function (target) {
return typeof target === 'function'
};
var isString = function (value) {
return typeof value === 'string';
};
var isEmpty = function (value) {
if (isObject(value)) {
for (var idx in value) {
if (value.hasOwnProperty(idx)) {
return false;
}
}
return true;
}
if (isArray(value)) {
return !value.length;
}
return !value;
};
var forEach = function (target, callback) {
if (isArray(target)) {
return target.map(callback);
}
else {
for (var _key in target) {
if (target.hasOwnProperty(_key)) {
callback(target[_key]);
}
}
}
};
var clone = function (value) {
return JSON.parse(JSON.stringify(value));
};
var ERRORS = {
"PARSE_ERROR": {
"code": -32700,
"message": "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."
},
"INVALID_REQUEST": {
"code": -32600,
"message": "Invalid Request. The JSON sent is not a valid Request object."
},
"METHOD_NOT_FOUND": {
"code": -32601,
"message": "Method not found. The method does not exist / is not available."
},
"INVALID_PARAMS": {
"code": -32602,
"message": "Invalid params. Invalid method parameter(s)."
},
"INTERNAL_ERROR": {
"code": -32603,
"message": "Internal error. Internal JSON-RPC error."
}
};
function ServerError(code, message, data) {
this.message = message || "";
this.code = code || -32000;
if (Boolean(data)) {
this.data = data;
}
}
ServerError.prototype = new Error();
var simple_jsonrpc = function () {
var self = this,
waitingframe = {},
id = 0,
dispatcher = {};
self.undefinedResult = true;
function setError(jsonrpcError, exception) {
var error = clone(jsonrpcError);
if (!!exception) {
if (isObject(exception) && exception.hasOwnProperty("message")) {
error.data = exception.message;
}
else if (isString(exception)) {
error.data = exception;
}
if (exception instanceof ServerError) {
error = {
message: exception.message,
code: exception.code
};
if (exception.hasOwnProperty('data')) {
error.data = exception.data;
}
}
}
return error;
}
function isPromise(thing) {
return !!thing && 'function' === typeof thing.then;
}
function isError(message) {
return !!message.error;
}
function isRequest(message) {
return !!message.method;
}
function isResponse(message) {
return message.hasOwnProperty('result') && message.hasOwnProperty('id');
}
function beforeResolve(message) {
var promises = [];
if (isArray(message)) {
forEach(message, function (msg) {
promises.push(resolver(msg));
});
}
else if (isObject(message)) {
promises.push(resolver(message));
}
return _Promise.all(promises)
.then(function (result) {
var toStream = [];
forEach(result, function (r) {
if (!isUndefined(r)) {
toStream.push(r);
}
});
if (toStream.length === 1) {
self.toStream(JSON.stringify(toStream[0]));
}
else if (toStream.length > 1) {
self.toStream(JSON.stringify(toStream));
}
return result;
});
}
function resolver(message) {
try {
if (isError(message)) {
return rejectRequest(message);
}
else if (isResponse(message)) {
return resolveRequest(message);
}
else if (isRequest(message)) {
return handleRemoteRequest(message);
}
else {
return _Promise.resolve({
"id": null,
"jsonrpc": "2.0",
"error": setError(ERRORS.INVALID_REQUEST)
});
}
}
catch (e) {
console.error('Resolver error:' + e.message, e);
return _Promise.reject(e);
}
}
function rejectRequest(error) {
if (waitingframe.hasOwnProperty(error.id)) {
waitingframe[error.id].reject(error.error);
}
else {
console.log('Unknown request', error);
}
}
function resolveRequest(result) {
if (waitingframe.hasOwnProperty(result.id)) {
waitingframe[result.id].resolve(result.result);
delete waitingframe[result.id];
}
else {
console.log('unknown request', result);
}
}
function handleRemoteRequest(request) {
if (dispatcher.hasOwnProperty(request.method)) {
try {
var result;
if (request.hasOwnProperty('params')) {
if (dispatcher[request.method].params == "pass") {
result = dispatcher[request.method].fn.call(dispatcher, request.params);
}
else if (isArray(request.params)) {
result = dispatcher[request.method].fn.apply(dispatcher, request.params);
}
else if (isObject(request.params)) {
if (dispatcher[request.method].params instanceof Array) {
var argsValues = [];
dispatcher[request.method].params.forEach(function (arg) {
if (request.params.hasOwnProperty(arg)) {
argsValues.push(request.params[arg]);
delete request.params[arg];
}
else {
argsValues.push(undefined);
}
});
if (Object.keys(request.params).length > 0) {
return _Promise.resolve({
"jsonrpc": "2.0",
"id": request.id,
"error": setError(ERRORS.INVALID_PARAMS, {
message: "Params: " + Object.keys(request.params).toString() + " not used"
})
});
}
else {
result = dispatcher[request.method].fn.apply(dispatcher, argsValues);
}
}
else {
return _Promise.resolve({
"jsonrpc": "2.0",
"id": request.id,
"error": setError(ERRORS.INVALID_PARAMS, "Undeclared arguments of the method " + request.method)
});
}
}
}
else {
result = dispatcher[request.method].fn();
}
if (request.hasOwnProperty('id')) {
if (isPromise(result)) {
return result.then(function (res) {
if (isUndefined(res)) {
res = self.undefinedResult;
}
return {
"jsonrpc": "2.0",
"id": request.id,
"result": res
};
})
.catch(function (e) {
return {
"jsonrpc": "2.0",
"id": request.id,
"error": setError(ERRORS.INTERNAL_ERROR, e)
};
});
}
else {
if (isUndefined(result)) {
result = self.undefinedResult;
}
return _Promise.resolve({
"jsonrpc": "2.0",
"id": request.id,
"result": result
});
}
}
else {
return _Promise.resolve(); //nothing, it notification
}
}
catch (e) {
return _Promise.resolve({
"jsonrpc": "2.0",
"id": request.id,
"error": setError(ERRORS.INTERNAL_ERROR, e)
});
}
}
else {
return _Promise.resolve({
"jsonrpc": "2.0",
"id": request.id,
"error": setError(ERRORS.METHOD_NOT_FOUND, {
message: request.method
})
});
}
}
function notification(method, params) {
var message = {
"jsonrpc": "2.0",
"method": method,
"params": params
};
if (isObject(params) && !isEmpty(params)) {
message.params = params;
}
return message;
}
function call(method, params) {
id += 1;
var message = {
"jsonrpc": "2.0",
"method": method,
"id": id
};
if (isObject(params) && !isEmpty(params)) {
message.params = params;
}
return {
promise: new _Promise(function (resolve, reject) {
waitingframe[id.toString()] = {
resolve: resolve,
reject: reject
};
}),
message: message
};
}
self.toStream = function (a) {
console.log('Need define the toStream method before use');
console.log(arguments);
};
self.dispatch = function (functionName, paramsNameFn, fn) {
if (isString(functionName) && paramsNameFn == "pass" && isFunction(fn)) {
dispatcher[functionName] = {
fn: fn,
params: paramsNameFn
};
}
else if (isString(functionName) && isArray(paramsNameFn) && isFunction(fn)) {
dispatcher[functionName] = {
fn: fn,
params: paramsNameFn
};
}
else if (isString(functionName) && isFunction(paramsNameFn) && isUndefined(fn)) {
dispatcher[functionName] = {
fn: paramsNameFn,
params: null
};
}
else {
throw new Error('Missing required argument: functionName - string, paramsNameFn - string or function');
}
};
self.on = self.dispatch;
self.off = function (functionName) {
delete dispatcher[functionName];
};
self.call = function (method, params) {
var _call = call(method, params);
self.toStream(JSON.stringify(_call.message));
return _call.promise;
};
self.notification = function (method, params) {
self.toStream(JSON.stringify(notification(method, params)));
};
self.batch = function (requests) {
var promises = [];
var message = [];
forEach(requests, function (req) {
if (req.hasOwnProperty('call')) {
var _call = call(req.call.method, req.call.params);
message.push(_call.message);
//TODO(jershell): batch reject if one promise reject, so catch reject and resolve error as result;
promises.push(_call.promise.then(function (res) {
return res;
}, function (err) {
return err;
}));
}
else if (req.hasOwnProperty('notification')) {
message.push(notification(req.notification.method, req.notification.params));
}
});
self.toStream(JSON.stringify(message));
return _Promise.all(promises);
};
self.messageHandler = function (rawMessage) {
try {
var message = JSON.parse(rawMessage);
return beforeResolve(message);
}
catch (e) {
console.log("Error in messageHandler(): ", e);
self.toStream(JSON.stringify({
"id": null,
"jsonrpc": "2.0",
"error": ERRORS.PARSE_ERROR
}));
return _Promise.reject(e);
}
};
self.customException = function (code, message, data) {
return new ServerError(code, message, data);
};
};
/**
* Static method for simple_jsonrpc for creating a simple_jsonrpc() instance pre-configured
* for use in a browser, with JSON-RPC over HTTP using standard XHR.
*
* Example:
*
* var rpc = simple_jsonrpc.connect_xhr("http://rpc.example.com:8888");
* rpc.call("get_account", ["johndoe"]).then(function(res) {
* console.log("johndoe full name:", res.full_name)
* })
*
*/
simple_jsonrpc.connect_xhr = function(rpc_url, rpc_config) {
if ( typeof rpc_url === "undefined" || rpc_url === null ) rpc_url = "/";
if ( typeof rpc_config === "undefined" || rpc_config === null ) rpc_config = {};
if ( !('content-type' in rpc_config) ) rpc_config['content-type'] = 'application/json; charset=utf-8';
if ( !('method' in rpc_config) ) rpc_config.method = 'POST';
if ( !('onerror' in rpc_config) ) rpc_config.onerror = console.error;
var jrpc = new simple_jsonrpc();
jrpc.toStream = function(_msg){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState != 4) return;
try {
JSON.parse(this.responseText);
jrpc.messageHandler(this.responseText);
}
catch (e){
rpc_config.onerror(e);
}
};
xhr.open(rpc_config.method, rpc_url, true);
xhr.setRequestHeader('Content-type', rpc_config['content-type']);
xhr.send(_msg);
};
return jrpc;
};
if (typeof define == 'function' && define.amd) {
define('simple_jsonrpc', [], function () {
return simple_jsonrpc;
});
}
else if (typeof module !== "undefined" && typeof module.exports !== "undefined") {
module.exports = simple_jsonrpc;
}
else if (typeof root !== "undefined") {
root.simple_jsonrpc = simple_jsonrpc;
}
else {
return simple_jsonrpc;
}
})(this);