-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonrpc.ts
62 lines (52 loc) · 1.61 KB
/
jsonrpc.ts
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
///<reference path='node/node.d.ts' />
import http = module("http");
export class JSONRPCClient {
port: number;
host: string;
constructor(port, host) {
this.port = port;
this.host = host;
}
call(method: string, params: any[], callback: (p1: any, p2: any) => any, path: string) {
// First we encode the request into JSON
var requestJSON = JSON.stringify({
'id': '' + (new Date()).getTime(),
'method': method,
'params': params
});
// Then we build some basic headers.
var headers = {
'host': this.host,
'Content-Length': requestJSON.length
};
if (path === null) {
path = '/';
}
var options = {
host: this.host,
port: this.port,
path: path,
headers: headers,
method: 'POST'
}
var buffer = '';
var req = http.request(options, function(res) {
res.on('data', function(chunk) {
buffer = buffer + chunk;
});
res.on('end', function() {
var decoded = JSON.parse(buffer);
if(decoded.hasOwnProperty('result')) {
callback(null, decoded.result);
} else {
callback(decoded.error, null);
}
});
res.on('error', function(err) {
callback(err, null);
});
});
req.write(requestJSON);
req.end();
}
}