Created
February 8, 2017 13:29
-
-
Save wh4everest/f35a668aecb6d63c5aabb3e86d198f83 to your computer and use it in GitHub Desktop.
Poor man's request library
This file contains 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
import * as http from 'http'; | |
import * as https from 'https'; | |
import { parse as parseURL } from 'url'; | |
/** | |
* Poor man's `request` library. | |
* | |
* Performs an HTTP(S) request, returns a promise that will | |
* return the body of the response. | |
*/ | |
export function request(url: string, opts?: http.RequestOptions): Promise<{ body: string, req: http.ClientRequest, res: http.IncomingMessage }> { | |
let urlObj = parseURL(url); | |
let isHTTP = urlObj.protocol === 'http:'; | |
let request = isHTTP ? http.request : https.request; | |
let hostAndPort = urlObj.host.split(':'); | |
let host = hostAndPort[0]; | |
let port = hostAndPort[1] ? parseInt(hostAndPort[1], 10) : (isHTTP ? 80 : 443); | |
let reqOpts = Object.assign({}, opts, { | |
auth: urlObj.auth, | |
host, | |
port, | |
path: urlObj.path, | |
agent: false | |
}); | |
let promise = new Promise((resolve, reject) => { | |
let req = request(reqOpts, (res) => { | |
let body: string[] = []; | |
res.on('data', (chunk) => { | |
if (typeof chunk === 'string') { | |
body.push(chunk); | |
} else { | |
body.push(chunk.toString()); | |
} | |
}); | |
res.on('end', () => { | |
resolve({ | |
body: body.join(''), | |
request: req, | |
response: res | |
}); | |
}); | |
res.on('error', (e) => { | |
reject(e); | |
}); | |
}); | |
req.end(); | |
}); | |
return promise; | |
} | |
request('https://openshift.redhat.com/broker/rest/api', { headers: { 'accept': '*/*' } }).then((res) => { | |
console.log(res.body); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment