UNPKG

@fosenu/httpclient

Version:

A HTTP-client written in typescript, using native node.js library

160 lines 5.7 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const http = require("http"); const https = require("https"); var Protocol; (function (Protocol) { Protocol["HTTP"] = "http"; Protocol["HTTPS"] = "https"; })(Protocol = exports.Protocol || (exports.Protocol = {})); var HTTP_METHOD; (function (HTTP_METHOD) { HTTP_METHOD["GET"] = "GET"; HTTP_METHOD["POST"] = "POST"; HTTP_METHOD["PUT"] = "PUT"; HTTP_METHOD["DELETE"] = "DELETE"; })(HTTP_METHOD || (HTTP_METHOD = {})); var ResponseType; (function (ResponseType) { ResponseType["JSON"] = "application/json"; ResponseType["XML"] = "application/xml"; ResponseType["XML_TEXT"] = "text/xml"; ResponseType["HTML"] = "text/html"; ResponseType["SCRIPT"] = "script"; })(ResponseType || (ResponseType = {})); const defaultOptions = { protocol: Protocol.HTTP, encoding: 'utf8', error: error => console.error(error), baseUrl: '', headers: {} }; class Client { static isErrorStatus(response) { return response.statusCode >= 400 && response.statusCode < 600; } static prepareData(data) { if (data) { if (typeof data === 'object') return JSON.stringify(data); return data.toString(); } return null; } constructor(url, options = defaultOptions) { this.parseOptions(options); this._options.baseUrl = url; } parseOptions(options) { this._options = Object.assign({}, defaultOptions, options); } parseResponseData(type, data) { switch (type) { case ResponseType.JSON: return JSON.parse(data); case ResponseType.XML: case ResponseType.XML_TEXT: case ResponseType.HTML: case ResponseType.SCRIPT: return data; default: throw new Error(`Unsupported content-type for http response received: ${type}`); } } createRequestFn(protocol) { if (protocol === Protocol.HTTP) return http.request; else if (protocol === Protocol.HTTPS) return https.request; else throw new Error(`Unsupported protocol: ${protocol}`); } responseHandler(response) { let data = ''; let type; if (response.headers && response.headers['content-type']) type = response.headers['content-type'].split(';')[0]; response.on('data', chunkData => data += chunkData); return new Promise((resolve, reject) => { response.on('end', () => { try { const parsedData = this.parseResponseData(type, data); if (Client.isErrorStatus(response)) { this.options.error(new Error(parsedData)); return reject(parsedData); } return resolve(parsedData); } catch (ex) { this.options.error(ex); return reject(ex); } }); }); } request(type, path, data) { const requestFn = this.createRequestFn(this._options.protocol); const { baseUrl, port, headers, protocol } = this._options; const preparedData = Client.prepareData(data); if (preparedData) { headers['content-length'] = Buffer.byteLength(preparedData); } const requestOptions = { hostname: baseUrl, port, path, method: type, headers, protocol: `${protocol}:` }; return new Promise((resolve, reject) => { const request = requestFn(requestOptions, (res) => __awaiter(this, void 0, void 0, function* () { try { const parsedResponse = yield this.responseHandler(res); return resolve(parsedResponse); } catch (ex) { return reject(ex); } })); request.on('error', error => { this._options.error(error); return reject(error); }); request.end(preparedData); }); } get(path) { return __awaiter(this, void 0, void 0, function* () { return this.request(HTTP_METHOD.GET, path, null); }); } post(path, data = null) { return __awaiter(this, void 0, void 0, function* () { return this.request(HTTP_METHOD.POST, path, data); }); } put(path, data = null) { return __awaiter(this, void 0, void 0, function* () { return this.request(HTTP_METHOD.PUT, path, data); }); } delete(path, data = null) { return __awaiter(this, void 0, void 0, function* () { return this.request(HTTP_METHOD.DELETE, path, data); }); } get options() { return this._options; } } exports.Client = Client; //# sourceMappingURL=Client.js.map