Skip to content

Instantly share code, notes, and snippets.

@park-brian
Last active May 5, 2021 19:07
Show Gist options
  • Save park-brian/57e916e78a5b05cad860ca90b531083d to your computer and use it in GitHub Desktop.
Save park-brian/57e916e78a5b05cad860ca90b531083d to your computer and use it in GitHub Desktop.
Promise-based wrapper for space-constrained Node.js applications (aws lambda, gc functions, etc)
/**
* A Promise-based wrapper for the http/https.request function
* @param {string|URL} url - Strings are parsed as URL objects
* @param {Object} opts - A set of options for http.request - includes `body`
* @example let response = await request('http://jsonplaceholder.typicode.com/posts/1')
*/
function request(url, opts) {
return new Promise((resolve, reject) => {
if (!(url instanceof URL)) {
url = new URL(url);
}
const lib = url.protocol == 'https:' ? require('https') : require('http');
const req = lib.request(url, { ...opts }, res => {
res.setEncoding('utf8');
const isSuccess = String(res.statusCode).startsWith('2');
const isRedirect = String(res.statusCode).startsWith('3');
const callback = data => {
if (isRedirect && res.headers.location) {
request(res.headers.location, opts).then(resolve);
} else if (isSuccess) {
resolve(data);
} else {
reject(data);
}
}
let buffer = '';
res.on('data', data => buffer += data);
res.on('end', _ => callback(buffer));
res.on('error', error => reject(error));
});
req.on('timeout', _ => req.destroy());
req.on('error', error => reject(error));
if (opts && opts.body) {
req.write(opts.body);
}
req.end();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment