Created
January 5, 2018 06:32
-
-
Save amolpednekar/0c64b35fb11cba13e95be07204023f40 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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 }, | |
timeout: 6000000 | |
}; | |
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'); | |
var req = http.request(options).setTimeout(options.timeout, () => { | |
console.log("Socket Timed Out after", options.timeout/1000, "seconds"); | |
}); | |
let data = ""; | |
req.on('socket', function (socket) { | |
socket.setTimeout(options.timeout); | |
socket.on('timeout', function () { | |
console.log("Socket Timed Out!"); | |
req.abort(); | |
}); | |
}); | |
req.on('error', (e) => { | |
console.log("Request Timed Out!"); | |
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment