UNPKG

intereq

Version:

Apply interceptors to `fetch` and create a custom request function.

50 lines (49 loc) 1.96 kB
/** * An alias to `window.fetch` type definition. */ declare type Fetch = typeof window.fetch; /** * Options to do a request (`"url"` + `fetch`'s second argument). */ export declare type RequestOptions = RequestInit & { url: string; }; /** * Interceptors to handle request errors. */ declare type ErrorInterceptors = { /** * Handle request and response errors. * @param reason - Error reason, almost every time is an `Error` instance. */ onError?: (reason?: Error) => Promise<never>; /** * Handle request errors. Overwrites `onError` handling request errors. * @param reason - Error reason, almost every time is an `Error` instance. */ onRequestError?: (reason?: Error) => Promise<never>; /** * Handle response errors. Overwrites `onError` handling response errors. * @param reason - Error reason, almost every time is an `Error` instance. */ onResponseError?: (reason?: Error) => Promise<never>; }; /** * Apply interceptors to `fetch` and create a custom request function. * @param fetch - Yours environment Fetch function. * @param interceptors - Interceptors as a kind of protocol to handle requests. */ declare const createRequest: { (fetch: Fetch, interceptors?: ErrorInterceptors): (...params: [RequestOptions]) => Promise<Response>; <R = Response>(fetch: Fetch, interceptors?: ErrorInterceptors & { onResponse: (response: Response) => R | PromiseLike<R>; }): (...params: [RequestOptions]) => Promise<R>; <A extends any[]>(fetch: Fetch, interceptors?: ErrorInterceptors & { onRequest: (...params: A) => RequestOptions; }): (...params: A) => Promise<Response>; <A extends any[], R = Response>(fetch: Fetch, interceptors?: ErrorInterceptors & { onRequest: (...params: A) => RequestOptions; onResponse: (response: Response) => R | PromiseLike<R>; }): (...params: A) => Promise<R>; }; export default createRequest;