UNPKG

homebridge-smartsystem

Version:

SmartServer (Proxy Websockets to TCP sockets, Smappee MQTT, Duotecno IP Nodes, Homekit interface)

64 lines (49 loc) 1.83 kB
import * as http from "http"; import { err } from "./logger"; /////////////////// // http function // /////////////////// export async function get(host: string, port: number, path: string, headers = {}): Promise<string> { return request('GET', host, port, path, {}, headers); } export async function post(host: string, port: number, path: string, body: object, headers = {}): Promise<string> { return request('POST', host, port, path, body, headers); } async function request(method: string, host: string, port: number, path: string, body: object, headers = {}): Promise<string> { let timer; let httpReq: http.ClientRequest; return new Promise<any>((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); err("http", "http.get failed with " + JSON.stringify(e)); reject(e); }); if (method === "POST") { httpReq.write(JSON.stringify(body)); } httpReq.end(); } catch(error) { err("http", "http.request " + method + " to " + host + " with " + path + " failed with " + error.message); reject(error); } }); }