Created
February 27, 2017 04:40
-
-
Save davidchase/a134da910f8bdd405ba386a12d1d4da2 to your computer and use it in GitHub Desktop.
simple-http-request.js
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 toString = buff => buff.toString() | |
const jParse = str => JSON.parse(str) | |
const stringify = obj => JSON.stringify(obj) | |
const keys = obj => Object.keys(obj) | |
const dissoc = (str, obj) => | |
keys(obj).reduce((acc, k) => k !== str ? (acc[k] = obj[k], acc) : acc , {}) | |
const simpleReq = (url, opts = {}) => | |
new Promise((resolve, reject) => { | |
const options = dissoc('body', Object.assign({}, parse(url), opts)) | |
const body = opts.body || '' | |
const protocol = options.protocol === 'https:' ? https : http | |
const req = protocol.request(options, res => { | |
const { statusCode, statusMessage, headers } = res | |
return res.on('data', body => resolve({url, statusCode, statusMessage, headers, body})) | |
}) | |
req.on('error', reject) | |
req.on('timeout', () => (req.abort(), reject(new Error('Request timed out')))) | |
req.end(body) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment