-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathclient.js
More file actions
79 lines (63 loc) · 2.21 KB
/
client.js
File metadata and controls
79 lines (63 loc) · 2.21 KB
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
"use strict";
const http = require("http");
const https = require("https");
let client = (connection) => {
let options = {
host: connection.host,
port: connection.port,
method: "POST",
key: connection.key,
cert: connection.cert,
agent: connection.agent,
pfx: connection.pfx,
passphrase: connection.passphrase,
ca: connection.ca,
ciphers: connection.ciphers,
rejectUnauthorized: connection.rejectUnauthorized,
secureProtocol: connection.secureProtocol,
servername: connection.servername,
headers: {'Content-Type': 'application/json', host: connection.host}
};
if(connection.user && connection.pass){
options.auth = connection.user + ":" + connection.pass;
}
return {
call: (method, params, cb) => {
let payload = {method: method, params: [], id: 1, jsonrpc: '2.0'};
if(params){
payload.params = params;
}
let body = JSON.stringify(payload);
options.headers['Content-Length'] = Buffer.byteLength(body, 'utf8');
if(connection.protocol === "https"){
var req = https.request(options);
} else {
var req = http.request(options);
}
let data = "";
req.on('error', (e) => {
cb(e);
});
req.write(JSON.stringify(payload));
req.on("response", (res) => {
res.on('data', (chunk) => {
data += chunk;
})
res.on('end', () => {
let response;
if(res.statusCode === 200){
response = JSON.parse(data);
return cb(null, response.result);
} else if (res.headers['content-type'] === "application/json"){
response = JSON.parse(data);
return cb(response.error);
} else {
return cb(data);
}
})
})
req.end();
}
}
}
module.exports = client;