-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathjsonrpc.js
99 lines (83 loc) · 2.78 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
/**
* Simple JSON-RPC
*/
var JSONRPCClient, URL_REGEXP;
// Take url in parts: scheme, host, root zone, port, and path of request
URL_REGEXP = /(http|https):\/\/([\w\-_]+(?:\.([\w\-_]+))+)(?::([\d]+))*([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
/**
* JSON-RPC client
* @param {String} scheme Scheme of request (http|https)
* @param {String} host JSON-RPC server
* @param {Number} port Port
* @param {String} path Path of request
*/
JSONRPCClient = function (scheme, host, port, path) {
this.scheme = scheme;
this.host = host;
this.port = port;
this.path = path;
/**
* Call method of JSON-RPC API
* @param {String} method Method
* @param {Array} params Params of request
* @param {Function} [onSuccessCallback] Callback for success result
* @param {Function} [onErrorCallback] Callback for error
*/
this.call = function(method, params, onSuccessCallback, onErrorCallback) {
var requestJSON, requestOptions, request;
requestJSON = JSON.stringify({
'id': '' + (new Date()).getTime(),
'method': method,
'params': params
});
requestOptions = {
host: this.host,
port: this.port,
path: this.path,
method: 'POST',
headers: {
'Content-Length': Buffer.byteLength(requestJSON, encoding='utf8')
}
}
// Send request
request = require(this.scheme).request(requestOptions, onComplete);
request.on('error', function (error) {
onErrorCallback && onErrorCallback(error);
});
request.write(requestJSON);
request.end();
function onComplete (res) {
var buffer = '';
res.setEncoding('utf8');
res.on('data', function(chunk) {
buffer = buffer + chunk;
});
res.on('end', function () {
var decoded = JSON.parse(buffer);
if(decoded.result) {
onSuccessCallback && onSuccessCallback(decoded.result);
} else {
onErrorCallback && onErrorCallback(decoded.error);
}
});
res.on('error', function (error) {
onErrorCallback && onErrorCallback(error);
});
}
};
}
module.exports = {
/**
* Create JSON-RPC client
* @param {String} url Server url
* @return {JSONRPCClient} client
*/
client: function (url) {
var urlParts = url.match(URL_REGEXP),
scheme = urlParts[1] || 'http',
host = urlParts[2],
port = urlParts[4] || (scheme === 'https' ? 443 : 80),
path = urlParts[5];
return new JSONRPCClient(scheme, host, port, path);
}
};