added option to control timeout of http requests

This commit is contained in:
Daniel Sommer 2022-03-24 13:00:19 +01:00
parent 5e6314eee9
commit 039496a7e0
3 changed files with 16 additions and 8 deletions

View file

@ -3,6 +3,9 @@
"listen": "0.0.0.0",
"port": 3001
},
"requests": {
"timeout": 5000
},
"cache": {
"active": true,
"lifetime": 0

View file

@ -31,7 +31,6 @@ async function fill() {
logger.debug('filling cache...');
clear();
try {
if (modep === undefined) {
modep = require('./modep.js');
}
@ -43,6 +42,7 @@ async function fill() {
logger.debug('cache filled after ' + timeDiff(timestamp) + 'ms');
} catch (err) {
logger.error('encountered an error while filling the cache after ' + timeDiff(timestamp) + 'ms');
logger.error(err);
}
}

View file

@ -28,7 +28,7 @@ function httpPOST(host, port, path, args) {
}
function httpRequest(host, port, path, method, args) {
return new Promise(function (resolve, reject) {
return new Promise((resolve, reject) => {
if (!path.startsWith("/")) {
path = "/" + path;
}
@ -36,7 +36,8 @@ function httpRequest(host, port, path, method, args) {
hostname: host,
port: port,
path: path,
method: method
method: method,
timeout: global.config?.requests?.timeout || 5000
};
let requestName = 'http \'' + method + '\' request > \'' + host + ':' + port + path;
if (args !== undefined) {
@ -48,15 +49,15 @@ function httpRequest(host, port, path, method, args) {
}
requestName += '\'';
logger.debug('sending ' + requestName + '...');
const request = http.request(options, function (response) {
const request = http.request(options, (response) => {
if (!response) {
return reject('no response from host for ' + requestName);
}
let responseData = "";
response.on('data', function (data) {
response.on('data', (data) => {
responseData += data;
});
response.on('end', function () {
response.on('end', () => {
logger.debug(requestName + ' returned status code \'' + response.statusCode + '\' and data \'' + responseData + '\'');
let fn = resolve;
if (response.statusCode != 200) {
@ -73,7 +74,11 @@ function httpRequest(host, port, path, method, args) {
});
});
request.on('error', function (err) {
request.on('timeout', () => {
request.destroy();
return reject(requestName + ' timed out after ' + options.timeout + 'ms');
});
request.on('error', (err) => {
return reject(requestName + ' returned an error >>> ' + err.message);
});
if (args !== undefined) {
@ -104,7 +109,7 @@ function hexToRGB(hex) {
}
function sortById(array) {
return array.sort(function (a, b) {
return array.sort((a, b) => {
return a.id - b.id;
});
}