Skip to content

Instantly share code, notes, and snippets.

@aqilc
Created July 11, 2020 02:43
Show Gist options
  • Save aqilc/5fb6a086c075e397ed2ea1e941ad6dc0 to your computer and use it in GitHub Desktop.
Save aqilc/5fb6a086c075e397ed2ea1e941ad6dc0 to your computer and use it in GitHub Desktop.
A simple fetch module.
// HTTPS API
import https from "https";
/**
* Executes an HTTP request
* @param {string | URL} url The url
* @returns {Promise<any>} The response
*/
export default (url, { method, headers, data } = {}) => new Promise((res, rej) => {
// Starts a new HTTPS request
let req = https.request(url, { method, headers, data }, r/*es*/ => {
// Stores data
let data = "";
// Stores data chunks
r.on("data", chunk => data += chunk);
// Sends response on end of request
r.on("end", () => {
// If the format was JSON, parse(with test) and return
if (/^application\/json/.test(r.headers["content-type"]))
try { return res(JSON.parse(data)); }
catch(err) { console.log(`JSON Parse on content of type ${r.headers["content-type"]} failed.\nError: ${err}\nData: ${data}`); }
// Sends raw data as response
res(data);
});
}).on("error", rej);
// If there is data to be sent, send it
if(data) req.write(data);
// Sends the request
req.end();
});
@117
Copy link

117 commented Jul 11, 2020

hot 💯 🔥

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment