Skip to content

Instantly share code, notes, and snippets.

@letam
Created November 28, 2019 01:54
Show Gist options
  • Save letam/749a4223706b1dd9f4981baf4835bbd7 to your computer and use it in GitHub Desktop.
Save letam/749a4223706b1dd9f4981baf4835bbd7 to your computer and use it in GitHub Desktop.
Utility function to make http requests in nodejs.
const http = require("http");
const https = require("https");
function omitKey(object, key) {
const { [key]: _, ...objectWithoutSelectedKey } = object;
return objectWithoutSelectedKey;
}
const request = function(url, options = {}) {
const handler = url.startsWith("https") ? https : http;
let body;
if (!options.method) {
options.method = "GET";
} else if (options.hasOwnProperty("body")) {
body = options.body;
options = omitKey(options, "body");
}
return new Promise((resolve, reject) => {
const req = handler
.request(url, options, res => {
// Reference: https://nodejs.org/api/http.html#http_http_request_url_options_callback
let data = "";
res.on("data", chunk => (data += chunk));
res.on("end", () => resolve(data));
})
.on("error", err => {
console.log("Error: " + err.message);
reject(err);
});
if (options.method !== "GET" && body) {
req.write(body);
}
req.end();
});
};
request.get = (url, options) => request(url, { ...options, method: "GET" });
request.post = (url, body, options) =>
request(url, { ...options, method: "POST", body });
request.put = (url, body, options) => request(url, { ...options, method: "PUT", body });
request.patch = (url, body, options) =>
request(url, { ...options, method: "PATCH", body });
request.delete = (url, options) => request(url, { ...options, method: "DELETE" });
module.exports = request;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment