Last active
October 25, 2019 02:39
-
-
Save alex-taxiera/4f95ff8c77df339ccd6832c3d8b56840 to your computer and use it in GitHub Desktop.
Native HTTP Request Module
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
// 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