homebridge-smartsystem
Version:
SmartServer (Proxy Websockets to TCP sockets, Smappee MQTT, Duotecno IP Nodes, Homekit interface)
73 lines • 3.15 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.post = exports.get = void 0;
const http = require("http");
const logger_1 = require("./logger");
///////////////////
// http function //
///////////////////
function get(host, port, path, headers = {}) {
return __awaiter(this, void 0, void 0, function* () {
return request('GET', host, port, path, {}, headers);
});
}
exports.get = get;
function post(host, port, path, body, headers = {}) {
return __awaiter(this, void 0, void 0, function* () {
return request('POST', host, port, path, body, headers);
});
}
exports.post = post;
function request(method, host, port, path, body, headers = {}) {
return __awaiter(this, void 0, void 0, function* () {
let timer;
let httpReq;
return new Promise((resolve, reject) => {
try {
timer = setTimeout(() => {
if (httpReq) {
httpReq.destroy();
}
reject("Request to " + host + path + " timed out");
}, 4000);
httpReq = http.request({ host, port, path, headers, method }, (response) => {
let str = '';
// another chunk of data has been received, so append it to `str`
response.on('data', (chunk) => {
str += chunk;
});
// the whole response has been received,
// stop the timer and resolve the promise with ithe collected result
response.on('end', () => {
if (timer)
clearTimeout(timer);
resolve(str);
});
}).on('error', (e) => {
if (timer)
clearTimeout(timer);
(0, logger_1.err)("http", "http.get failed with " + JSON.stringify(e));
reject(e);
});
if (method === "POST") {
httpReq.write(JSON.stringify(body));
}
httpReq.end();
}
catch (error) {
(0, logger_1.err)("http", "http.request " + method + " to " + host + " with " + path + " failed with " + error.message);
reject(error);
}
});
});
}
//# sourceMappingURL=api.js.map