export interface Response { status: number, text: string, json: () => Promise, } export interface Options { body: FormData|string, headers?: any, onUploadProgress?: (ev: ProgressEvent) => any, } const request = async ( method: string, url: string, options: Options ): Promise => { return new Promise((resolve, reject) => { const xhr = new window.XMLHttpRequest() xhr.open(method, url, true) xhr.withCredentials = true for (const k in options.headers || {}) { xhr.setRequestHeader(k, options.headers[k]) } xhr.addEventListener('load', function (ev: ProgressEvent ) { resolve({ status: this.status, text: this.responseText, json: async () => JSON.parse(this.responseText), }) }) xhr.addEventListener('error', function (ev: ProgressEvent) { reject(new Error('xhr error')) }) if (xhr.upload && options.onUploadProgress) { xhr.upload.addEventListener('progress', function (ev: ProgressEvent) { // typescript complains without this extra check if (options.onUploadProgress) { options.onUploadProgress(ev) } }) } xhr.send(options.body) }) } export default { request, get: (url: string, options: any): Promise => { return request('get', url, options) }, post: (url: string, options: any): Promise => { return request('post', url, options) }, }