homebridge-smartsystem
Version:
SmartServer (Proxy TCP sockets to the cloud, Smappee MQTT, Duotecno IP Nodes, Homekit interface)
100 lines (91 loc) • 3.56 kB
text/typescript
import { debug, err, log } from "../duotecno/logger";
import * as http from "http";
//////////////////////////////////
// Home Assistant API //
// and other http based APIs //
//////////////////////////////////
export enum ContentType {form, plain, none, json};
export async function httpRequest(url: string, method = "GET", formdata = "",
contentType = ContentType.form, header: string | object = ""): Promise<Record<string, any>> {
if (url.indexOf("://") === -1) url = "http://" + url;
return new Promise((resolve, reject) => {
try {
// const data = querystring.stringify(formdata);
const options: {method: string, [key: string]: object | string} = { method };
if (formdata) {
if (contentType === ContentType.form) {
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(formdata)
}
} else if (contentType === ContentType.plain) {
options.headers = {
'Content-Type': 'text/plain',
'Accept': 'application/json'
};
} else if (contentType === ContentType.json) {
options.headers = {
'Content-Type': 'application/json',
'Accept': '*/*'
};
}
};
// header provide as string or object
if (header) {
if (!options.headers) options.headers = {};
if (typeof header === "string") {
if (header.substring(0,1) === "{") {
try {
options.headers = { ...<object>options.headers, ...JSON.parse(header)};
} catch(e) {
err("smartapp", "error parsing :" + header + " -> " + JSON.stringify(e));
}
} else {
const s = header.split(":");
options.headers[s[0]] = s[1];
}
} else {
// header is an object
options.headers = { ...<object>options.headers, ...header };
}
}
debug("smartapp", "Sending to " + url + " with options: " + JSON.stringify(options));
const req = http.request(url, options, res => {
let resp = "";
// res.setEncoding('utf8');
res.on('error', error => {
log("smartapp", "The request to " + url + ", error: " + (error ? error.message : "unknown"));
reject(error);
});
res.on('data', chunk => {
resp += chunk;
});
res.on('end', () => {
// try to make something out of it...
try {
const x = JSON.parse(resp);
if ((x.type === "Buffer") && x.data) x.data = x.data.toString();
debug("smartapp", "http " + method + " -> " + res.statusCode + ": " + url + " = " + JSON.stringify(x).substring(0, 200) + "...");
resolve(x)
} catch(e) {
err("smartapp", "http " + method + " -> " + res.statusCode + ": " + url + " = " + resp);
resolve({status: "NOK", result: resp});
};
});
});
if (formdata) {
req.write(formdata);
}
req.on("error", (e) => {
log("smartapp", "The request to " + url + ", error: " + (e ? e.message : "unknown"));
});
req.on("timeout", (e) => {
log("smartapp", "The request to " + url + ", timeout: " + (e ? e.message : "unknown"));
});
req.end();
} catch(e) {
log("smartapp", "** http error ** " + (e ? e.message : "unknown") + " **");
reject(e);
}
});
}