import 'isomorphic-fetch'; type HttpMethod = 'GET' | 'PUT' | 'POST' | 'PATCH' | 'DELETE'; export interface IResponse { ok: boolean; status: number; statusText?: string; type: string; url: string; data?: T; } export interface IHttpHeaders { [id: string]: string; } async function request( method: HttpMethod, requestUrl: string, data?: object, headers?: IHttpHeaders, ): Promise> { const payload = { method, body: data ? JSON.stringify(data) : undefined, headers: {}, }; if (data) { Object.assign(payload.headers, { Accept: 'application/json', 'Content-Type': 'application/json', }); } if (headers) { Object.assign(payload.headers, headers); } const response = await fetch(requestUrl, payload); const { ok, status, statusText, type, url } = response; const result = { ok, status, statusText, type, url, data: undefined }; if (ok) { // Attempt to parse the response as JSON. const contentType = (response.headers as any)._headers['content-type']; if (contentType[0].startsWith('application/json')) { result.data = await response.json(); } } return result; } function get(url: string, headers?: IHttpHeaders): Promise> { return request('GET', url, undefined, headers); } function put( url: string, data?: object, headers?: IHttpHeaders, ): Promise> { return request('PUT', url, data, headers); } function post( url: string, data?: object, headers?: IHttpHeaders, ): Promise> { return request('POST', url, data, headers); } function patch( url: string, data?: object, headers?: IHttpHeaders, ): Promise> { return request('PATCH', url, data, headers); } function del(url: string, headers?: IHttpHeaders): Promise> { return request('DELETE', url, undefined, headers); } function headers(httpHeaders: IHttpHeaders) { return { get: (url: string): Promise> => get(url, httpHeaders), put: (url: string, data?: object): Promise> => put(url, data, httpHeaders), post: (url: string, data?: object): Promise> => post(url, data, httpHeaders), patch: (url: string, data?: object): Promise> => patch(url, data, httpHeaders), delete: (url: string): Promise> => del(url, httpHeaders), headers: (append: IHttpHeaders) => headers({ ...httpHeaders, ...append }), }; } export { get, put, post, patch, del as delete, headers }; export default { get, put, post, patch, delete: del, headers };