Created
March 25, 2019 00:43
-
-
Save andreigec/d9c0f1d0f83b83def39bd5ba691c572b to your computer and use it in GitHub Desktop.
A simple https request wrapper. Useful for aws lambda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const https = require("https"); | |
const btoaPF = str => Buffer.from(str).toString("base64"); | |
const getdata = (host, path, headers, binary = false, body) => | |
new Promise(res2 => { | |
const op = { | |
host, | |
port: 443, | |
path, | |
method: body ? "POST" : "GET", | |
headers: { | |
...headers, | |
"Content-Length": body && body.length | |
} | |
}; | |
const req = https.request(op, res => { | |
const chunks = []; | |
if (binary) { | |
res.setEncoding("binary"); | |
} else { | |
res.setEncoding("utf8"); | |
} | |
res.on("data", chunk => { | |
if (binary) { | |
chunks.push(Buffer.from(chunk, "binary")); | |
} else { | |
chunks.push(chunk); | |
} | |
}); | |
res.on("end", () => { | |
if (binary) { | |
const buff = Buffer.concat(chunks); | |
res2(btoaPF(buff)); | |
return; | |
} | |
const joined = chunks.join(""); | |
try { | |
const ret = JSON.parse(joined); | |
res2(ret); | |
return; | |
} catch (e) { | |
// | |
} | |
res2(joined); | |
}); | |
}); | |
req.on("error", res2); | |
if (body) { | |
req.write(body); | |
} | |
req.end(); | |
}); | |
//eg get | |
const items = await getdata( | |
"gec.dev", | |
"/hello-get" | |
); | |
//get post | |
const itemsRaw = await getdata( | |
"gec.dev", | |
"/hello-post", | |
{ a: 1 }, //headers | |
false, | |
JSON.stringify(body) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment