npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

composable-fetch

v7.0.1

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 - First class supp

Downloads

327

Readme

composable-fetch CircleCI

  • 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 support for both TypeScript and Flow

Installation

npm install composable-fetch

Example

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.

Overview

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

fetch

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

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.

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) => Request
withTimeout: (timeout: number) => (fetch: RetryableFetch) => RetryableFetch

Fetch phase

fetch1: (fetch: BinaryFetch) => UnaryFetch
retryable: (fetch: UnaryFetch) => (req: Request) => RetryableFetch
withRetry: (options?: RetryOptions) => (fetch: RetryableFetch) => Promise<Response>

Enhance response phase

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

Predefined pipes

json: (fetch: BinaryFetch, options?: RetryOptions) => Promise<DecodedResponse>
text: (fetch: BinaryFetch, options?: RetryOptions) => Promise<DecodedResponse>

Abort

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