Skip to content

Instantly share code, notes, and snippets.

@image72
Last active November 6, 2018 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save image72/0c564a1302642da80f197b6d812e4234 to your computer and use it in GitHub Desktop.
Save image72/0c564a1302642da80f197b6d812e4234 to your computer and use it in GitHub Desktop.
nodejs http request with promise.fork from https://dev.to/simov/composable-http-client-for-nodejs-83f
const composePromise = (...funcs) => initialValue =>
funcs.reduce((sum, fn) => Promise.resolve(sum).then(fn), initialValue);
// const {res, body} = await request({...options});
module.exports = composePromise(
options => {
options.headers = options.headers || {};
options.headers['user-agent'] = 'request-compose';
options.protocol = options.protocol || 'https:';
return options;
},
options =>
new Promise((resolve, reject) => {
let protocol = options.protocol.slice(0, -1);
require(protocol)
.request(options)
.on('response', resolve)
.on('error', reject)
.end();
}),
res =>
new Promise((resolve, reject) => {
var body = '';
res
.on('data', chunk => body += chunk)
.on('end', () => resolve({res, body}))
.on('error', reject);
}),
({res, body}) => ({res, body: JSON.parse(body)})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment