Skip to content

Instantly share code, notes, and snippets.

@image72
Last active Nov 6, 2018
Embed
What would you like to do?
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