Last active
November 6, 2018 03:36
-
-
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
This file contains hidden or 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 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