{"id":16589525,"url":"https://github.com/honzabrecka/composable-fetch","last_synced_at":"2025-03-16T21:30:32.335Z","repository":{"id":23691152,"uuid":"99581386","full_name":"honzabrecka/composable-fetch","owner":"honzabrecka","description":"A library that brings composition to http requests \u0026 solves most common tasks","archived":false,"fork":false,"pushed_at":"2023-01-06T02:03:48.000Z","size":2052,"stargazers_count":24,"open_issues_count":15,"forks_count":1,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-10-15T09:32:17.169Z","etag":null,"topics":["composable","fetch","functional","http","javascript","request","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/honzabrecka.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-08-07T13:33:50.000Z","updated_at":"2023-09-01T11:19:52.000Z","dependencies_parsed_at":"2023-01-14T07:45:21.586Z","dependency_job_id":null,"html_url":"https://github.com/honzabrecka/composable-fetch","commit_stats":null,"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/honzabrecka%2Fcomposable-fetch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/honzabrecka%2Fcomposable-fetch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/honzabrecka%2Fcomposable-fetch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/honzabrecka%2Fcomposable-fetch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/honzabrecka","download_url":"https://codeload.github.com/honzabrecka/composable-fetch/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243830915,"owners_count":20354850,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["composable","fetch","functional","http","javascript","request","typescript"],"created_at":"2024-10-11T23:09:07.665Z","updated_at":"2025-03-16T21:30:31.959Z","avatar_url":"https://github.com/honzabrecka.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# composable-fetch [![CircleCI](https://circleci.com/gh/honzabrecka/composable-fetch/tree/master.svg?style=svg\u0026circle-token=eefe6811545741764260a25f382c13da0d6e31a7)](https://circleci.com/gh/honzabrecka/composable-fetch/tree/master)\n\n - Composable and extensible\n - Just javascript and promises\n - Brings solutions for most common cases such as status code checking, body encoding/decoding, retries \u0026 retries strategies, ...\n - Provides functional API\n - Dependency free\n - First class support for both TypeScript and Flow\n\n## Installation\n\n```\nnpm install composable-fetch\n```\n\n## Example\n\n```js\nconst composableFetch = require('composable-fetch')\n\nconst log = console.log.bind(console)\n\nconst fetchJSON = composableFetch.pipeP(\n  composableFetch.withBaseUrl('https://example.com/api'),\n  composableFetch.withHeader('Content-Type', 'application/json'),\n  composableFetch.withHeader('Accept', 'application/json'),\n  composableFetch.withEncodedBody(JSON.stringify),\n  composableFetch.retryable(composableFetch.fetch1(window.fetch)),\n  composableFetch.withRetry(),\n  composableFetch.withSafe204(),\n  composableFetch.decodeJSONResponse,\n  composableFetch.checkStatus\n)\n\nfetchJSON({ url: '/foo' }).then(log).catch(log)\nfetchJSON({ url: '/bar', method: 'POST', body: [1, 2, 3] }).then(log).catch(log)\n```\n\nFor better overview of how composability may help take a look at `examples/composable.js` example.\n\n## Overview\n\nThe main concept of composable-fetch is [piping (left-to-right composition)](#pipep) - passing data through pipe of unary functions. Pipe typically has three blocks, subpipes ([see API](#api) for more details about applicable functions):\n\n```\npipe = enhance request -\u003e fetch (with retries) -\u003e enhance response\n```\n\n## fetch\n\nFor 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.\n\n## Retries\n\n```js\nwithRetry({ max: 3, delay: delays.constant() })\n// retries after 1 sec, then again after 1 sec, then again after 1 sec\n\nwithRetry({ max: 3, delay: delays.linear() })\n// retries after 1 sec, then after 2 secs, then after 3 secs\n\nwithRetry({ max: 3, delay: delays.exponential() })\n// retries after 1 sec, then after 4 secs, then after 9 secs\n\nwithRetry({ max: 6, delay: delays.limited(3, delays.linear()) })\n// retries after 1 sec, then 2 secs, 3 secs, then 1 sec, 2 secs, 3 secs\n```\n\nWhen using `withRetry`, make sure that you wrapped `fetch` with `retryable`.\n\n## Error handling \u0026 logging\n\nTo pretty print failed request (any reason):\n\n```js\nconst fetchJSON: tryCatchP(\n  pipeP(/* ... */),\n  logError(), // to console.error by default\n)\n```\n\nIn case you are interested in details of all requests made by your application, you can add simple `tap` function which performs desired side effect:\n\n```js\nconst tap = (f) =\u003e (v) =\u003e {\n  f(v)\n  return v\n}\n\nconst fetchJSON = pipeP(\n  // ...\n  withHeader('Accept', 'application/json'),\n  withEncodedBody(JSON.stringify),\n  tap(console.log.bind(console, 'request:')),\n  fetch1(window.fetch),\n  // ...\n)\n```\n\nThe `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:\n\n```js\nconst fetchJSON = tryCatchP(\n  pipeP(\n    // ...\n    withRetry(),\n    withClone,\n    decodeJSONResponse, // this will fail for any non application/json response\n    // ...\n  ),\n  logError\n)\n```\n\n## API\n\n### pipeP\n\nPerforms 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.\n\n### tryCatchP\n\n`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.\n\n### Enhance request phase\n\n```js\nwithBaseUrl: (baseUrl: string) =\u003e (req: Request) =\u003e Request\nwithEncodedBody: \u003cA, B\u003e(encoder: Encoder\u003cA, B\u003e) =\u003e (req: Request) =\u003e Request\nwithJSONEncodedBody: (req: Request) =\u003e Request\nwithHeader: (header: string, value: string) =\u003e (req: Request) =\u003e Request\nwithCredentials: (value: 'omit' | 'same-origin' | 'include') =\u003e (req: Request) =\u003e Request\nwithTimeout: (timeout: number) =\u003e (fetch: RetryableFetch) =\u003e RetryableFetch\n```\n\n### Fetch phase\n\n```js\nfetch1: (fetch: BinaryFetch) =\u003e UnaryFetch\nretryable: (fetch: UnaryFetch) =\u003e (req: Request) =\u003e RetryableFetch\nwithRetry: (options?: RetryOptions) =\u003e (fetch: RetryableFetch) =\u003e Promise\u003cResponse\u003e\n```\n\n### Enhance response phase\n\n```js\ncheckStatus: (res: Response) =\u003e Response\ndecodeArrayBufferResponse: (res: Response) =\u003e DecodedResponse\ndecodeBlobResponse: (res: Response) =\u003e DecodedResponse\ndecodeFormDataResponse: (res: Response) =\u003e DecodedResponse\ndecodeJSONResponse: (res: Response) =\u003e DecodedResponse\ndecodeResponse: (res: Response) =\u003e DecodedResponse\ndecodeTextResponse: (res: Response) =\u003e DecodedResponse\nwithSafe204: (text?: string, json?: any) =\u003e (res: Response) =\u003e Response\nwithClone: (res: Response) =\u003e Response\n```\n\n### Predefined pipes\n\n```js\njson: (fetch: BinaryFetch, options?: RetryOptions) =\u003e Promise\u003cDecodedResponse\u003e\ntext: (fetch: BinaryFetch, options?: RetryOptions) =\u003e Promise\u003cDecodedResponse\u003e\n```\n\n### Abort\n\nFor better understanding how to abort fetch request, go to `examples/abort.js` example.\n\n```js\nabortable: () =\u003e { signal: AbortSignal, abort: () =\u003e void }\nignoreAbortError: \u003cT\u003e(handler: (error: Error) =\u003e T) =\u003e (error: Error) =\u003e T\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhonzabrecka%2Fcomposable-fetch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhonzabrecka%2Fcomposable-fetch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhonzabrecka%2Fcomposable-fetch/lists"}