import "isomorphic-fetch"; import * as _ from "lodash"; enum FetchMethod { GET = "GET", POST = "POST", PUT = "PUT", PATCH = "PATCH", DELETE = "DELETE", } const ALL_METHODS: Fetch.Method[] = Object.values(FetchMethod); export interface FetchRequest { url: string; method: FetchMethod; headers: Headers; body: string; } enum FetchEvent { SUCCESS = "SUCCESS", ERROR = "ERROR", } export type FetchEventHandler = (request: FetchRequest, response: Response) => void; type HeaderGenerator = (request: FetchRequest) => string; type GlobalHeader = string | HeaderGenerator; // A subset of RequestInit that we allow setting as global options that // get used with each request. interface GlobalRequestOptions { cache?: RequestCache; credentials?: RequestCredentials; mode?: RequestMode; redirect?: RequestRedirect; referrerPolicy?: ReferrerPolicy; } export class FetchRequestError extends Error { readonly status: number; readonly body: any; constructor(message: string, status: number, body: any) { super(message); // See: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget Object.setPrototypeOf(this, new.target.prototype); this.name = FetchRequestError.name; this.status = status; this.body = body; } } export class Fetch { // These static fields are used to allow FetchMethod and FetchEvent to be // accessible through Fetch.Method and Fetch.Event rather than exporting them. static Method = FetchMethod; static Event = FetchEvent; private static _eventHandlers: { [event in FetchEvent]?: FetchEventHandler[] } = {}; private static _globalHeaders: { [method in Fetch.Method]: { [header: string]: GlobalHeader }; } = { [FetchMethod.GET]: {}, [FetchMethod.POST]: {}, [FetchMethod.PUT]: {}, [FetchMethod.PATCH]: {}, [FetchMethod.DELETE]: {}, }; private static _globalRequestOptions: GlobalRequestOptions = {}; private static _fireEvent(event: FetchEvent, request: FetchRequest, response: Response) { if (!this._eventHandlers[event]) { return; } // We use setTimeout to push each operation into the background. this._eventHandlers[event].forEach((handler) => setTimeout(() => handler(request, response.clone()), 1), ); } private static _getGlobalHeadersForRequest(request: FetchRequest): { [header: string]: string } { const headers = {}; const globalHeadersForMethod = this._globalHeaders[request.method]; Object.keys(globalHeadersForMethod).forEach((key) => { const value = globalHeadersForMethod[key]; const headerValue = _.isFunction(value) ? (value as HeaderGenerator)(request) : value; // Don't include headers that are empty, null, or undefined. if (headerValue) { headers[key] = headerValue; } }); return headers; } // Resets Fetch's internal state and any custom configurations. static reset() { this._eventHandlers = {}; ALL_METHODS.forEach((method) => (this._globalHeaders[method] = {})); this._globalRequestOptions = {}; } /* Registers an event handler for the specified event. Multiple event handlers can be added to the same event and they all will trigger. */ static on(event: FetchEvent, handler: FetchEventHandler) { if (!this._eventHandlers[event]) { this._eventHandlers[event] = []; } this._eventHandlers[event].push(handler); } /* Sets a header to be included with all requests of the specified methods. A global header can be a string, in which case it's constant, or a function that takes the request as input and returns a value to use for the header. If the function returns a falsey value the header isn't included. */ static setGlobalHeader(header: string, headerValue: GlobalHeader, methods = ALL_METHODS) { methods.forEach((method) => { this._globalHeaders[method][header] = headerValue; }); } /* Sets global options to be used with all requests. */ static setGlobalOptions(options: GlobalRequestOptions) { this._globalRequestOptions = options; } static async get(url, queryParams = {}, headers = {}) { let queryString = ""; if (!_.isEmpty(queryParams)) { const paramStrings = Object.keys(queryParams).map((key) => `${key}=${queryParams[key]}`); queryString = `?${paramStrings.join("&")}`; } const urlWithoutTrailingSlashes = url.replace(/\/+$/, ""); return await Fetch.makeRequest(`${urlWithoutTrailingSlashes}${queryString}`, { method: FetchMethod.GET, headers, body: undefined, }); } // TODO: Add support for non-object bodies static async post(url, body = {}, headers = {}) { return await Fetch.makeRequest(url, { method: FetchMethod.POST, headers: { "Content-Type": "application/json", ...headers, }, body: JSON.stringify(body), }); } static async put(url, body = {}, headers = {}) { return await Fetch.makeRequest(url, { method: FetchMethod.PUT, headers: { "Content-Type": "application/json", ...headers, }, body: JSON.stringify(body), }); } static async patch(url, body = {}, headers = {}) { return await Fetch.makeRequest(url, { method: FetchMethod.PATCH, headers: { "Content-Type": "application/json", ...headers, }, body: JSON.stringify(body), }); } // body is ignored for DELETE static async delete(url, body = {}, headers = {}) { if (!body || Object.keys(body).length === 0) { return await Fetch.makeRequest(url, { method: FetchMethod.DELETE, headers, body: undefined, }); } return await Fetch.makeRequest(url, { method: FetchMethod.DELETE, headers: { "Content-Type": "application/json", ...headers, }, body: JSON.stringify(body), }); } // Fetch's underlying method static async makeRequest(url, options = { method: FetchMethod.GET, headers: {}, body: "" }) { const { method, headers, body } = options; // Initialize eventRequest with the explicitly specified headers so we can use it in _getGlobalHeadersForRequest. const eventRequest = { url, headers: new Headers(headers), method, body }; const headersWithGlobals = new Headers({ ...this._getGlobalHeadersForRequest(eventRequest), ...options.headers, }); // Update the headers on eventRequest to be the actual headers we'll use for the request (including global headers). eventRequest.headers = headersWithGlobals; let response: Response; try { response = await fetch(url, { method, headers: headersWithGlobals, credentials: "same-origin", // Firefox and Safari throw an error if a body is provided for a GET request body: method === FetchMethod.GET ? undefined : body, // Apply global request options for the request. ...this._globalRequestOptions, }); } catch (err) { throw new Error(`Fetch internal error: ${err.message}`); } // Attempt to read the response as JSON. If this fails, read it as text. Cloning is necessary // because responses can only be read once const responseBody = await response .clone() .json() .catch(() => response.clone().text()); if (!response.ok) { this._fireEvent(FetchEvent.ERROR, eventRequest, response); throw new FetchRequestError( `Request error: ${method} ${url} returned a ${response.status}`, response.status, responseBody, ); } this._fireEvent(FetchEvent.SUCCESS, eventRequest, response); return responseBody; } } // eslint-disable-next-line @typescript-eslint/no-namespace export namespace Fetch { // The static fields on the Fetch class allow using the enums, but // doesn't allow using the type. Exporting the types on the Fetch namespace does the trick. export type Method = FetchMethod; export type Event = FetchEvent; }