UNPKG

proactive-http-fetch

Version:

Proactive http fetch package

100 lines (80 loc) 3.44 kB
import { autoinject } from 'aurelia-framework'; import { FetchError } from 'cross-fetch/polyfill'; import { EventAggregator } from 'aurelia-event-aggregator'; import { HttpClient, json, RequestInit } from 'aurelia-fetch-client'; import { AntiforgeryService } from './antiforgery-service'; import { BrowserLocation } from './browser-location'; export type paramType = string | object | FormData | void; @autoinject() export class HttpFetch { constructor( private httpClient: HttpClient, private antiforgeryService: AntiforgeryService, private browserLocation: BrowserLocation, private eventAggregator: EventAggregator) { this.httpClient.configure(config => { config .rejectErrorResponses() .withDefaults({ credentials: 'same-origin', // use cookies headers: { 'X-Requested-With': 'Fetch' } }) .withInterceptor({ request(request) { request.headers.append(antiforgeryService.headerName, antiforgeryService.headerValue); return request; } }) .withInterceptor({ response(response) { antiforgeryService.storeAntiforgery(response); return response; } }); }); } public get(url: string, param?: paramType): Promise<any> { if (typeof param === 'undefined') return this.send(`${url}`, 'GET'); if (typeof param === 'string') return this.send(`${url}?${param}`, 'GET'); if (typeof param === 'object') return this.send(`${url}?${encodeURI(JSON.stringify(param))}`, 'GET'); } public post(url: string, param?: paramType): Promise<any> { return this.send(url, 'POST', param); } public put(url: string, param?: paramType): Promise<any> { return this.send(url, 'PUT', param); } private send(url: string, method: string, param?: paramType): Promise<any> { return this.httpClient .fetch(url, this.createRequest(method, param)) .then(response => this.handleResponse(response)) .catch(error => this.handleError(error)); } private createRequest(method: string, param?: paramType): RequestInit { if (typeof param === 'undefined') return { method }; if (typeof param === 'string') return { method, body: param}; if (typeof param === 'object') return { method, body: JSON.stringify(param) }; return { method, body: (param as FormData)}; } private handleResponse(response: Response): Promise<any> { if (!!response.body) return response.json(); return Promise.resolve(); } private handleError(response: Response | FetchError): Promise<any> { this.browserLocation.redirect(response); let message = ''; if (response instanceof Response) message = response.statusText; else message = 'Network error.'; this.eventAggregator.publish('error', message); return Promise.reject(message); } }