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

fetch-friends

v1.0.3

Published

Common utils for the Fetch API

Downloads

48

Readme

fetch-friends

Common utils for the Fetch API.

fetch is ubiquitous to the web. fetch-friends is a minimal, auto-curried utility library to decorate fetch with behaviors you might otherwise switch to another HTTP library for, confusing other developers in the process.

No need to replace fetch with a library just because you need timeout:

import fetch from 'node-fetch';
import { timeout } from 'fetch-friends';

// fetch aborts when API takes longer than 5 seconds to respond
export default timeout(5000, fetch);

fetch is never mentioned in the source code, so fetch-friends can decorate any function with a matching type signature.

Use decorate(fetch, decorators) to elegantly compose higher order functions over fetch:

import fetch from 'node-fetch';
import { limit } from 'semaphorejs';
import retry from 'min-retry';
import decorate, {
  bearerAuthHeader,
  headers,
  timeout
} from 'fetch-friends';

// fetch with token, timeout, retry, and concurrency limiting
export default decorate(fetch, [
  // fetch => (url, opts?) => Promise<Response>
  headers(bearerAuthHeader('sometoken123')),
  timeout(5000),
  retry(3),
  limit(10)
]);

Create advanced yet expressive flavors of fetch:

import fetch from 'node-fetch';
import { andThen, pipe } from 'ramda';
import retry from 'min-retry';
import decorate, {
  bearerAuthToken,
  headers,
  json,
  method,
  rejectIfNotOkay,
  timeout
} from 'fetch-friends';

export {
  GET: pipe(
    decorate(fetch, [
      method('GET'),
      headers(bearerAuthToken(TOKEN)),
      timeout(5000),
      retry(3),
    ]),
    andThen(rejectIfNotOkay),
    andThen(json)
  ),
  DELETE: pipe(
    decorate(fetch, [
      method('DELETE'),
      headers(bearerAuthToken(TOKEN))
    ]),
    andThen(rejectIfNotOkay)
  ),
  POST: pipe(
    decorate(fetch, [
      body,
      headers(bearerAuthToken(TOKEN))
    ]),
    andThen(rejectIfNotOkay)
  )
};

Fetch Decorators

Fetch decorators are higher order functions that add behavior on top of your fetch(url, opts?) implementation without changing the interface. All decorators are auto-curried except for the final (url, opts?) invocation.

Decorators that accept a function are lazily evaluated. This comes in handy for side effects like setting timeouts and getting an API token when fetch is called.

To apply multiple fetch decorators to fetch, use the default export decorate.

Like native fetch, the second argument opts is optional. Options passed in earlier always take precedence when a duplicate is found.

decorate(fetch, decorators)

decorate applies multiple fetch decorators in left-to-right, top-to-bottom fashion:

import fetch from 'node-fetch';
import decorate, { basicAuthHeader, headers, timeout } from 'fetch-friends';

export default decorate(fetch, [
  headers(basicAuthHeaders('joshua', 'm@rt1n')),
  timeout(5000)
]);

body(fetch)(json, url, opts?)

body accepts a JSON payload:

body(fetch)({ hello: 'world' }, '123.com', {});
// fetch('123.com', { body: JSON.stringify({ hello: 'world' })})

When combining with other decorators via decorate, place body at the top of the stack.

method(string, fetch)(url, opts?)

method accepts a standard method string:

method('GET', fetch)('123.com', {});
method('GET')(fetch)('123.com', {});
// fetch('123.com', { method: 'GET' })

headers(objectOrFn, fetch)(url, opts?)

headers accepts an object, function, or async function:

headers({ 'Authorization': 'Bearer 123.secret.456' }, fetch)('123.com', {});
headers({ 'Authorization': 'Bearer 123.secret.456' })(fetch)('123.com', {});
headers(async () => ({ `Authorization: Bearer ${await getToken()}` }), fetch)('123.com', {});
// fetch('123.com', { headers: { 'Authorization': 'Bearer 123.secret.456' } })

option(key, valueOrFn, fetch)(url, opts?)

option accepts a key and a value/function/async function:

option('signal', () => abort(5000), fetch)('123.com', {});
option('signal', () => abort(5000))(fetch)('123.com', {});
option('signal')(() => abort(5000), fetch)('123.com', {});
option('signal')(() => abort(5000))(fetch)('123.com', {});
// fetch('123.com', { signal: AbortSignal })

options(objectOrFn, fetch)(url, opts?)

options accepts an object, function, or async function:

options({ method: 'GET' }, fetch)('123.com', {});
options({ method: 'GET' })(fetch)('123.com', {});
// fetch('123.com', { method: 'GET' })
options(() => ({ signal: abort(5000) }), fetch)('123.com', {});
// fetch('123.com', { signal: AbortSignal })

timeout(millis, fetch)(url, opts?)

timeout accepts a millisecond duration at which to abort a fetch call:

timeout(5000, fetch)('123.com', {});
timeout(5000)(fetch)('123.com', {});
// fetch('123.com', { signal: AbortSignal })

Fetch Helpers

Just some teeny helper functions.

abort(millis)

abort sets a timeout and returns an AbortSignal:

abort(5000);
// AbortSignal

basicAuthHeader(username, password)

basicAuthHeader('joshua', 'm@rt1n');
basicAuthHeader('joshua')('m@rt1n');
// { 'Authorization': 'Basic am9zaHVhOm1AcnQxbg==' }

bearerAuthHeader(token)

bearerAuthHeader('abcdefg');
// { 'Authorization': 'Bearer abcdefg' }

json(response)

fetch('/users').then(json);
// Promise<[{ id: 1 }, { id: 2 }, { id: 3 }]>

rejectIfNotOkay(response)

rejectIfNotOkay throws an error if response.ok is false:

fetch('/forbidden/users').then(rejectIfNotOkay);
// Promise<Error('Forbidden')>

Related libraries

Ramda

You may find yourself needing just a few utilities for fetch-friends. For convenience, this package includes the most common for composing over fetch:

min-retry

Retries fetch on:

  • 429 and 500...599 status codes
  • FetchError
  • AbortError

semaphorejs

Decorates fetch with semaphore behavior

CommonJS

const { decorate, json, rejectIfNotOkay, headers } = require('fetch-friends');