-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrpc.js
80 lines (64 loc) · 1.59 KB
/
rpc.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
var http = require('http');
function RPCClient(config) {
this.config = config;
this.authHeader = 'Basic ' + new Buffer(this.config.username + ':' + this.config.password).toString('base64');
};
RPCClient.prototype.request = function(method, params, callback) {
var content = {
version: 1.1
, method: method
, id: 1
, params: params || []
};
content = JSON.stringify(content);
content = new Buffer(content);
var headers = {
Authorization: this.authHeader
, 'Content-type': 'application/json'
, 'Content-length': content.length
};
var request = http.request({
host: this.config.host
, port: this.config.port
, method: 'POST'
, path: '/'
, headers: headers
}, function(response) {
var chunks = [];
var status = response.statusCode;
response.on('data', function(chunk) {
chunks.push(chunk);
});
response.on('end', function() {
var data = null;
if (status !== 200) {
var error = status;
if (chunks.length > 0) {
error = Buffer.concat(chunks)
error = error.toString('utf8');
}
return (callback ? callback(error) : false);
}
// Make sure we got some data
if (chunks.length > 0) {
data = Buffer.concat(chunks)
data = data.toString('utf8');
data = JSON.parse(data);
}
// Make sure it's not an error
if (data) {
if (data.error) {
if (callback) callback(data.error);
} else {
if (callback) callback(null, data.result);
}
}
});
});
request.on('error', function(err) {
console.log(err);
});
request.write(content);
request.end();
};
exports.client = RPCClient;