@autocodingsystems/gateway-client
Version:
Library and commandline utility to control the acs gateway - device drivers for the most common industrial production line devices
87 lines (73 loc) • 2.32 kB
JavaScript
var http = require('http');
const { URL } = require('url');
function readjson() {
var savedres, savedrej;
var next = new Promise((res, rej) => {
savedres = res;
savedrej = rej;
});
var handler = function (response) {
var body = '';
response.setEncoding('utf8');
response.on('data', (chunk) => {
body += chunk;
});
response.on('end', () => {
try {
var bodyobj = JSON.parse(body || "{}");
if (typeof bodyobj === 'string') {
bodyobj = {Message: bodyobj};
}
if (response.statusCode === 200) {
savedres(bodyobj);
} else {
savedrej(Object.assign({StatusCode: response.statusCode}, bodyobj));
}
} catch (e) {
console.log(body);
savedrej(e);
}
});
response.on('error', savedrej);
}
return {handler, next}
}
function getJson(host, options) {
return new Promise( async (res, rej) => {
const {handler, next} = readjson();
const url = new URL(host);
const requestopts = Object.assign(
{},
{
protocol: url.protocol,
hostname: url.hostname,
method: 'GET',
port: url.port,
auth: (url.username || url.password) ? `${url.username}:${url.password}` : null,
headers: {}
},
options
);
if (typeof options.data === 'object') {
requestopts.headers['Content-Type'] = 'application/json';
}
var req = http.request(requestopts);
req.once('response', handler);
req.once('error', rej);
if (options.data) {
if (typeof options.data === 'object') {
req.write(JSON.stringify(options.data));
} else {
req.write(options.data);
}
}
req.end();
try {
var body = await next;
res(body);
} catch (e) {
rej(e);
}
});
}
module.exports = getJson;