UNPKG

typescriptkit

Version:

Basic functionality for TypeScript projects

54 lines (46 loc) 2.18 kB
/* istanbul ignore next */ import { ObjectExtensions } from '../Extensions/ObjectExtensions'; import { StringExtensions } from '../Extensions/StringExtensions'; import { IHttpRequestExecutor } from './IHttpRequestExecutor'; /* istanbul ignore next */ /** * Implementation of the xmlHttpclient converting eventhandlers to callbacks (For internal use) */ export class HttpRequestExecutor implements IHttpRequestExecutor { /** * execte the Http GET call * @param url The url to point the request to * @param httpheaders (optional) The httpHeaders array to append to the request * @param success (optional) The callback after a succesfull request * @param error (optional) The callback after a failed request */ public executeHttpGet = (url: string, httpHeaders?: Array<any>, success?: (responseText: string) => void, error?: (responseText: string, statusCode: number) => void): void => { if (StringExtensions.isNullOrWhitespace(url)) throw new URIError('Please provide a valid URL to call to!'); // Todo: validate url const httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = () => { if (httpRequest.readyState !== 4) return; if (httpRequest.status === 200) { success(httpRequest.responseText); } else { error(httpRequest.responseText, httpRequest.status); } }; httpRequest.open(`GET`, url as any, true); // true for asynchronous if (!ObjectExtensions.isNullOrUndefined(httpHeaders) && httpHeaders.length > 0) this.applyRequestHeaders(httpRequest, httpHeaders); httpRequest.send(null); } private applyRequestHeaders(xmlHttp: XMLHttpRequest, httpHeaders: Array<any>): void { if (ObjectExtensions.isNullOrUndefined(httpHeaders)) return; for (let headerKey in httpHeaders) { if (!httpHeaders.hasOwnProperty(headerKey)) continue; const headerValue = httpHeaders[headerKey]; xmlHttp.setRequestHeader(headerKey, headerValue); } } } export default HttpRequestExecutor;