Security News
tea.xyz Spam Plagues npm and RubyGems Package Registries
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
composable-fetch
Advanced tools
Readme
npm install composable-fetch
const composableFetch = require('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.js
example.
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 response
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.
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 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 secs
When using withRetry
, make sure that you wrapped fetch
with retryable
.
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
)
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
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.
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) => Request
withTimeout: (timeout: number) => (fetch: RetryableFetch) => RetryableFetch
fetch1: (fetch: BinaryFetch) => UnaryFetch
retryable: (fetch: UnaryFetch) => (req: Request) => RetryableFetch
withRetry: (options?: RetryOptions) => (fetch: RetryableFetch) => Promise<Response>
checkStatus: (res: Response) => Response
decodeArrayBufferResponse: (res: Response) => DecodedResponse
decodeBlobResponse: (res: Response) => DecodedResponse
decodeFormDataResponse: (res: Response) => DecodedResponse
decodeJSONResponse: (res: Response) => DecodedResponse
decodeResponse: (res: Response) => DecodedResponse
decodeTextResponse: (res: Response) => DecodedResponse
withSafe204: (text?: string, json?: any) => (res: Response) => Response
withClone: (res: Response) => Response
json: (fetch: BinaryFetch, options?: RetryOptions) => Promise<DecodedResponse>
text: (fetch: BinaryFetch, options?: RetryOptions) => Promise<DecodedResponse>
For better understanding how to abort fetch request, go to examples/abort.js
example.
abortable: () => { signal: AbortSignal, abort: () => void }
ignoreAbortError: <T>(handler: (error: Error) => T) => (error: Error) => T
FAQs
- 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 - First class supp
The npm package composable-fetch receives a total of 84 weekly downloads. As such, composable-fetch popularity was classified as not popular.
We found that composable-fetch demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.
Security News
UnitedHealth Group disclosed that the ransomware attack on Change Healthcare compromised protected health information for millions in the U.S., with estimated costs to the company expected to reach $1 billion.