Created
July 11, 2020 02:43
-
-
Save aqilc/5fb6a086c075e397ed2ea1e941ad6dc0 to your computer and use it in GitHub Desktop.
A simple fetch module.
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
// 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(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hot 💯 🔥