Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Poor man's request library
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
You can’t perform that action at this time.