return-fetch
Version:
A very light and simple library to extend fetch by implementing request, response interceptors.
76 lines (75 loc) • 2.72 kB
text/typescript
/**
* A simple and powerful high order function to extend fetch.
*
* @packageDocumentation
*/
/**
* Arguments of fetch function.
*
* @throws {Error} if a first argument of fetch is `Request` object. only string and URL are supported.
* @see {fetch, RequestInfo, Request}
*
* @public
*/
export type FetchArgs = [string | URL, RequestInit | undefined];
/**
* Type of `returnFetch` function.
* It is useful for whom want to write customized returnFetch function.
*
* @public
*/
export type ReturnFetch = typeof returnFetch;
/**
* Options of `returnFetch` function.
*
* @public
*/
export type ReturnFetchDefaultOptions = {
/**
* `fetch` function to be used in `returnFetch` function.
* If not provided, `fetch` function in global scope will be used.
* Any fetch implementation can be used, such as `node-fetch`, `cross-fetch`, `isomorphic-fetch`, etc.
*
* a `fetch` function created by `returnFetch` also can be used here.
*
* @public
*/
fetch?: ReturnType<ReturnFetch>;
/**
* Base URL of fetch. It will be used when the first argument of fetch is relative URL.
*
* @public
*/
baseUrl?: string | URL;
/**
* Default headers of fetch. It will be used when the second argument of fetch does not have `headers` property.
* If it is provided and `headers` also provided when calling a `fetch`, headers will be merged.
* Priority of headers is `requestInit.headers` > `defaultOptions.headers`. Duplicated headers will be overwritten.
*
* @public
*/
headers?: HeadersInit;
interceptors?: {
/**
* Request interceptor. It will be called before request.
*
* @param requestArgs Arguments of fetch function.
* @param fetch the `fetch` you provided at {@link ReturnFetchDefaultOptions['fetch']}
*
* @public
*/
request?: (requestArgs: FetchArgs, fetch: NonNullable<ReturnFetchDefaultOptions["fetch"]>) => Promise<FetchArgs>;
/**
* Response interceptor. It will be called after response.
*
* @param response Response object received from fetch function.
* @param requestArgs Arguments of fetch function.
* @param fetch the `fetch` you provided at {@link ReturnFetchDefaultOptions['fetch']}
*
* @public
*/
response?: (response: Response, requestArgs: FetchArgs, fetch: NonNullable<ReturnFetchDefaultOptions["fetch"]>) => Promise<Response>;
};
};
declare const returnFetch: (defaultOptions?: ReturnFetchDefaultOptions) => (input: URL | RequestInfo, init?: RequestInit | undefined) => Promise<Response>;
export default returnFetch;