Skip to content

Instantly share code, notes, and snippets.

@d0whc3r
Last active December 16, 2020 15:28
Show Gist options
  • Save d0whc3r/840666d65b79eb3910fee840ce39f11b to your computer and use it in GitHub Desktop.
Save d0whc3r/840666d65b79eb3910fee840ce39f11b to your computer and use it in GitHub Desktop.
const https = require('https');
/**
* Make a https request
* @param {string} url
* @param {import('https').RequestOptions} options
* @param {Record<string, any>} [postData]
* @returns {Promise<{ data: Record<string, any>, statusCode: number, statusMessage: string }>}
*/
function request(url, options, postData) {
return new Promise((resolve, reject) => {
const req = https.request(url, options, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
const data = JSON.parse(body);
const result = { data, statusCode: res.statusCode, statusMessage: res.statusMessage };
if (res.statusCode < 200 || res.statusCode >= 300) {
reject(result);
} else {
resolve(result);
}
});
});
req.on('error', (e) => {
reject(e);
});
if (postData) {
req.write(postData);
}
req.end();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment