const logger = require('./logger.js'); const http = require('http'); const { HTTP_GET, HTTP_POST } = require('./constants.js'); function timeDiff(startTime) { if (startTime instanceof Date) { return (new Date().getTime() - startTime.getTime()); } return new Date().getTime - startTime; } function clone(object) { var clone = {}; for (key in object) { clone[key] = object[key]; } return clone; } function httpGET(host, port, path, args) { return httpRequest(host, port, path, HTTP_GET, args); } function httpPOST(host, port, path, args) { return httpRequest(host, port, path, HTTP_POST, args); } function httpRequest(host, port, path, method, args) { return new Promise(function (resolve, reject) { if (!path.startsWith("/")) { path = "/" + path; } logger.debug('sending http \'' + method + '\' request to \'' + host + ':' + port + path + '\'...'); const request = http.request({ hostname: host, port: port, path: path, method: method }, function (response) { if (!response) { return reject('error: no response from host for http \'' + method + '\' request \'' + host + ':' + port + path + '\''); } var responseData = ""; response.on('data', function (data) { responseData += data; }); response.on('end', function () { logger.debug('http \'' + method + '\' request \'' + host + ':' + port + path + '\' returned status code \'' + response.statusCode + '\' and data \'' + responseData + '\''); var fn = resolve; if (response.statusCode != 200) { fn = reject; } if (!responseData) { return fn(); } try { return fn(JSON.parse(responseData)); } catch (err) { return fn(responseData); } }); }); request.on('error', function (err) { return reject('http \'' + method + '\' request \'' + host + ':' + port + path + '\' returned an error >>> ' + err); }); request.end(); }); } function toHex(value) { var hex = Number(value).toString(16); return hex; } function sortById(array) { return array.sort(function (a, b) { return a.id - b.id; }); } module.exports = { timeDiff, clone, httpGET, httpPOST, toHex, sortById }