Skip to content

Instantly share code, notes, and snippets.

@davidchase
Created February 27, 2017 04:40
Show Gist options
  • Save davidchase/a134da910f8bdd405ba386a12d1d4da2 to your computer and use it in GitHub Desktop.
Save davidchase/a134da910f8bdd405ba386a12d1d4da2 to your computer and use it in GitHub Desktop.
simple-http-request.js
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