Created
March 15, 2016 10:17
-
-
Save ducksoupdev/d311eec2d1b97ca7c36c to your computer and use it in GitHub Desktop.
Custom XHR wrapper with JSON parser
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
| import {Promise} from "es6-promise"; | |
| export class Header { | |
| header: string; | |
| data: string; | |
| constructor(header: string, data: string) { | |
| this.header = header; | |
| this.data = data; | |
| } | |
| } | |
| export class Data { | |
| headers: string; | |
| body: string; | |
| text: string; | |
| json: any; | |
| type: string; | |
| statusCode: number; | |
| statusText: string; | |
| public static FromXHR(jsXHR: XMLHttpRequest): Data { | |
| var data = new Data(); | |
| data.headers = jsXHR.getAllResponseHeaders(); | |
| data.body = jsXHR.responseBody; | |
| data.text = jsXHR.responseText; | |
| if (/Content-Type: application\/json/i.test(data.headers)) { | |
| data.json = JSON.parse(data.text); | |
| } | |
| data.type = jsXHR.responseType; | |
| data.statusCode = jsXHR.status; | |
| data.statusText = jsXHR.statusText; | |
| return data; | |
| } | |
| } | |
| export class XHR { | |
| private sendCommand(method: string, url: string, headers: Array<Header>, data: string = ""): Promise<Data> { | |
| return new Promise<Data>((resolve, reject) => { | |
| var jsXHR = new XMLHttpRequest(); | |
| jsXHR.open(method, url); | |
| if (headers != null) { | |
| headers.forEach((header) => { | |
| jsXHR.setRequestHeader(header.header, header.data); | |
| }); | |
| } | |
| jsXHR.onload = (ev) => { | |
| if (jsXHR.status < 200 || jsXHR.status >= 300) { | |
| reject(Data.FromXHR(jsXHR)); | |
| } | |
| resolve(Data.FromXHR(jsXHR)); | |
| } | |
| jsXHR.onerror = (ev) => { | |
| reject('Error ' + method.toUpperCase() + 'ing data to url "' + url + '", check that it exists and is accessible'); | |
| }; | |
| if (method == 'POST') { | |
| jsXHR.send(data); | |
| } else { | |
| jsXHR.send(); | |
| } | |
| }); | |
| } | |
| public get(url: string, headers: Array<Header> = null): Promise<Data> { | |
| return this.sendCommand('GET', url, headers); | |
| } | |
| public post(url: string, data: string = "", headers: Array<Header> = null): Promise<Data> { | |
| return this.sendCommand('POST', url, headers, data); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment