cuffeo/src/inc/fetch.mjs
2018-09-08 19:39:27 +02:00

32 lines
993 B
JavaScript

import http from "http";
import https from "https";
import url from "url";
import querystring from "querystring";
export default (a, options = {}, link = url.parse(a)) => new Promise((resolve, reject) => {
options = {...{
hostname: link.hostname,
path: link.path,
method: "GET"
}, ...options};
let body = "";
if(options.method === "POST") {
body = querystring.stringify(options.body);
delete options.body;
options.headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": Buffer.byteLength(body)
}
}
const post = (link.protocol === "https:"?https:http).request(options, (res, data = "") => res
.setEncoding("utf8")
.on("data", chunk => data += chunk)
.on("end", () => resolve({
text: () => data,
json: () => { try { return JSON.parse(data); } catch(err) { return "no json D:"; } },
buffer: () => new Buffer.from(data)
}))
).on("error", err => reject(err));
post.end(body);
});