export enum Method { GET = 'GET', POST = 'POST', PUT = 'PUT', DELETE = 'DELETE', } export interface TResponse { status: number; error: boolean; data: T; response: Response; } export class Requests { private baseUrl: string; private token: () => string; private headers: Record = {}; private logger?: (response: Response) => void; private url(rest: string): string { return this.baseUrl + rest; } constructor( baseUrl: string, token: string | (() => string) = '', headers: Record = {}, logger?: (response: Response) => void ) { this.baseUrl = baseUrl; this.token = typeof token === 'string' ? () => token : token; this.headers = headers; this.logger = logger; } public get(url: string): Promise> { return this.do(Method.GET, url); } public post(url: string, payload: T): Promise> { return this.do(Method.POST, url, payload); } public put(url: string, payload: T): Promise> { return this.do(Method.PUT, url, payload); } public delete(url: string): Promise> { return this.do(Method.DELETE, url); } private methodSupportsBody(method: Method): boolean { return method === Method.POST || method === Method.PUT; } private async do(method: Method, url: string, payload: Object = {}): Promise> { const args: RequestInit = { method, headers: { 'Content-Type': 'application/json', ...this.headers, }, }; const token = this.token(); if (token !== '' && args.headers !== undefined) { args.headers['Authorization'] = token; } if (this.methodSupportsBody(method)) { args.body = JSON.stringify(payload); } const response = await fetch(this.url(url), args); if (this.logger) { this.logger(response); } const data: T = await (async () => { if (response.status === 204) { return {} as T; } try { return await response.json(); } catch (e) { return {} as T; } })(); return { status: response.status, error: !response.ok, data, response, }; } }