composable-fetch
v8.0.0
Published
- Composable and extensible - Just javascript and promises - Brings solutions for most common cases such as status code checking, body encoding/decoding, retries & retries strategies, ... - Provides functional API - Dependency free
Readme
composable-fetch
- Composable and extensible
- Just javascript and promises
- Brings solutions for most common cases such as status code checking, body encoding/decoding, retries & retries strategies, ...
- Provides functional API
- Dependency free
Installation
npm install composable-fetchExample
import * as composableFetch from 'composable-fetch'
const log = console.log.bind(console)
const fetchJSON = composableFetch.pipeP(
composableFetch.withBaseUrl('https://example.com/api'),
composableFetch.withHeader('Content-Type', 'application/json'),
composableFetch.withHeader('Accept', 'application/json'),
composableFetch.withEncodedBody(JSON.stringify),
composableFetch.retryable(composableFetch.fetch1(window.fetch)),
composableFetch.withRetry(),
composableFetch.withSafe204(),
composableFetch.decodeJSONResponse,
composableFetch.checkStatus,
)
fetchJSON({ url: '/foo' }).then(log).catch(log)
fetchJSON({ url: '/bar', method: 'POST', body: [1, 2, 3] })
.then(log)
.catch(log)For better overview of how composability may help take a look at examples/composable.ts.
Development
npm install
npm test # run tests (vitest)
npm run typecheck # type check (tsc)
npm run lint # lint & format check (biome)
npm run build # build dist (tsdown)
npm run example # list examples
npm run example abortOverview
The main concept of composable-fetch is piping (left-to-right composition) - passing data through pipe of unary functions. Pipe typically has three blocks, subpipes (see API for more details about applicable functions):
pipe = enhance request -> fetch (with retries) -> enhance responsefetch
For better composability, composable-fetch requires unary fetch. However original fetch function or its polyfills is of binary arity. Don't worry, composable-fetch comes with fetch1 wrapper that transforms unary interface to its binary counterpart.
Retries
max is the number of retries, so max: 3 makes at most 4 requests (default max is 5). max: 0 disables retries.
withRetry({ max: 3, delay: delays.constant() })
// retries after 1 sec, then again after 1 sec, then again after 1 sec
withRetry({ max: 3, delay: delays.linear() })
// retries after 1 sec, then after 2 secs, then after 3 secs
withRetry({ max: 3, delay: delays.exponential() })
// retries after 1 sec, then after 2 secs, then after 4 secs
withRetry({ max: 3, delay: delays.quadratic() })
// retries after 1 sec, then after 4 secs, then after 9 secs
withRetry({ max: 6, delay: delays.limited(3, delays.linear()) })
// retries after 1 sec, then 2 secs, 3 secs, then 1 sec, 2 secs, 3 secsWhen the response contains a Retry-After header, its value is used instead of delay. If it is higher than maxTimeout, withRetry gives up.
By default every request is retried. Use filter to retry only some of them, e.g. only idempotent ones, so that a POST is not sent twice:
const idempotent = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE'])
withRetry({
filter: (req) => idempotent.has((req?.method ?? 'GET').toUpperCase()),
})When using withRetry, make sure that you wrapped fetch with retryable.
Error handling & logging
To pretty print failed request (any reason):
const fetchJSON = tryCatchP(
pipeP(/* ... */),
logError(), // to console.error by default
)In case you are interested in details of all requests made by your application, you can add simple tap function which performs desired side effect:
const tap = (f) => (v) => {
f(v)
return v
}
const fetchJSON = pipeP(
// ...
withHeader('Accept', 'application/json'),
withEncodedBody(JSON.stringify),
tap(console.log.bind(console, 'request:')),
fetch1(window.fetch),
// ...
)The fetch API has one major "limitation" - body of the response can be read just once. For example you deal with an API that returns HTML encoded reponse even though you asked for JSON encoded one - fetch fails on DecodeResponseError. You cannot just catch this error and decode that HTML encoded response, because you already read it. In browser it typically does not matter, you have network tab with all the details, however in non-browser environment it's not that easy, therefore composable-fetch comes with withClone function that gives you second chance to read the response:
const fetchJSON = tryCatchP(
pipeP(
// ...
withRetry(),
withClone,
decodeJSONResponse, // this will fail for any non application/json response
// ...
),
logError(),
)API
pipeP
Performs left-to-right function composition. Each function in composition must be unary. If function returns promise, than pipeP waits to its resolution before it calls next function in chain.
tryCatchP
tryCatchP takes two functions, an async trier and an async catcher. The returned function evaluates the trier; if it does not throw, it simply returns the result. If it does throw, the catcher function is evaluated and result is returned.
Enhance request phase
withBaseUrl: (baseUrl: string) => (req: Request) => Request
withEncodedBody: <A, B>(encoder: Encoder<A, B>) => (req: Request) => Request
withJSONEncodedBody: (req: Request) => Request
withHeader: (header: string, value: string) => (req: Request) => Request
withCredentials: (value: 'omit' | 'same-origin' | 'include') => (req: Request) => RequestRequest enhancers never mutate the passed request, so it's safe to reuse it. They return a copy made by copyRequest, which can be used in custom enhancers as well:
copyRequest: (req: Request, patch?: Partial<Request>) => Request // { ...req, headers: copyHeaders(req.headers), ...patch }
copyHeaders: (headers?: HeadersInit) => HeadersInit | undefined
const withMethod = (method) => (req) => copyRequest(req, { method })withHeader sets the header and replaces any existing value with the same (case-insensitive) name. req.headers may be a plain object, an array of [name, value] tuples or a Headers instance.
Fetch phase
fetch1: (fetch: BinaryFetch) => UnaryFetch
retryable: (fetch: UnaryFetch) => (req: Request) => RetryableFetch
withRetry: (options?: RetryOptions) => (fetch: RetryableFetch) => Promise<Response>
withTimeout: (timeout: number) => (fetch: RetryableFetch) => RetryableFetch // deprecated, use `signal: AbortSignal.timeout(ms)`
interface RetryOptions {
max?: number // number of retries, default 5
delay?: Delay // default delays.linear()
maxTimeout?: number // max accepted Retry-After in ms
filter?: (req?: Request) => boolean // default () => true
}retryable retries on statuses 408, 413, 429, 500, 502, 503, 504 and on network errors such as ECONNRESET, ECONNREFUSED, ENOTFOUND (including errors of Node's built-in fetch, where the code is in error.cause.code).
Enhance response phase
Decoders store the decoded body in res.data and return the same res.
checkStatus: (res: Response) => Response
decodeArrayBufferResponse: (res: Response) => Promise<Response>
decodeBlobResponse: (res: Response) => Promise<Response>
decodeFormDataResponse: (res: Response) => Promise<Response>
decodeJSONResponse: (res: Response) => Promise<Response>
decodeResponse: (res: Response) => Response | Promise<Response>
decodeTextResponse: (res: Response) => Promise<Response>
withSafe204: (text?: string, json?: any) => (res: Response) => Response
withClone: (res: Response) => ResponsePredefined pipes
json: (fetch: BinaryFetch, options?: RetryOptions) => (req: Request) => Promise<Response>
text: (fetch: BinaryFetch, options?: RetryOptions) => (req: Request) => Promise<Response>A response with invalid status code always fails with InvalidStatusCodeError, also when its body can't be decoded (e.g. HTML 404 page returned to json).
Abort
For better understanding how to abort fetch request, go to examples/abort.ts example.
abortable: () => { signal: AbortSignal, abort: () => void }
ignoreAbortError: <T>(handler: (error: Error) => T) => (error: Error) => T