Last active
December 16, 2020 15:28
-
-
Save d0whc3r/840666d65b79eb3910fee840ce39f11b to your computer and use it in GitHub Desktop.
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'); | |
/** | |
* 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