Skip to content

Instantly share code, notes, and snippets.

@alex-taxiera
Last active October 25, 2019 02:39
Show Gist options
  • Save alex-taxiera/4f95ff8c77df339ccd6832c3d8b56840 to your computer and use it in GitHub Desktop.
Save alex-taxiera/4f95ff8c77df339ccd6832c3d8b56840 to your computer and use it in GitHub Desktop.
Native HTTP Request Module
// request('https://www.google.com').then(console.log)
const https = require('https')
const http = require('http')
const { URL } = require('url')
const requesters = {
'http:': http,
'https:': https
}
const request = (url, options = {}) => {
const {
method = 'GET'
} = options
if (!http.METHODS.includes(method.toUpperCase())) {
return Promise.reject(Error(`INVALID METHOD: ${method.toUpperCase()}`))
}
url = new URL(url)
const protocol = requesters[url.protocol]
if (!protocol) {
return Promise.reject(Error(`INVALID PROTOCOL: ${url.protocol}`))
}
return new Promise((resolve, reject) => {
const {
body,
...reqOptions
} = options
const req = protocol.request(url, { ...reqOptions, method }, (res) => {
res.resume()
res.on('end', () => {
if (res.complete) {
resolve(res)
} else {
reject(Error('REQUEST NOT COMPLETED'))
}
})
})
req.on('error', reject)
if (body) {
req.write(body)
}
req.end()
})
}
module.exports = request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment