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

json-fetch

v9.0.10

Published

A wrapper around ES6 fetch to simplify interacting with JSON APIs.

Downloads

397

Readme

JSON Fetch

codecov badge

A wrapper around ES6 fetch to simplify interacting with JSON APIs.

  • automatically JSON stringify request body
  • set JSON request headers
  • resolve with json for any response with the Content-Type: application/json header
  • include request credentials by default
  • configurable retry option for requests

build status MIT license

Usage

yarn add json-fetch
# or...
npm install json-fetch
import jsonFetch from 'json-fetch';

jsonFetch('http://www.test.com/products/1234', {
  body: {name: 'apple'}, // content to be JSON stringified
  credentials: 'omit', // "include" by default
  expectedStatuses: [201], // rejects "FetchUnexpectedStatusError" on unexpected status (optional)
  // supports all normal json-fetch options:
  method: 'POST',
})
  .then((response) => {
    // handle response with expected status:
    console.log(response.body); // json response here
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
  })
  .catch((err) => {
    // handle response with unexpected status:
    console.log(err.name);
    console.log(err.message);
    console.log(err.response.status);
    console.log(err.response.statusText);
    console.log(err.response.body);
    console.log(err.response.text);
    console.log(err.response.headers);
  });

TypeScript

This library comes with built-in TypeScript type declarations.

Due to complexities in dealing with isomorphic-fetch - which uses whatwg-fetch in browsers and node-fetch in node.js, which are subtly different - these type declarations only work if you include the DOM built-in TypeScript lib in your tsconfig.json. For example:

{
  "lib": ["DOM", "ES2020"]
}

This happens implicitly if you don't set a lib.

This may be fixed in the future.

Retry Behavior

By default, jsonFetch doesn't retry requests. However, you may opt in to jsonFetch's very flexible retry behavior, provided by the excellent promise-retry library. Here's a quick example:

import jsonFetch, {retriers} from 'json-fetch'

jsonFetch('http://www.test.com/products/1234', {
  method: 'POST',
  body: {name: 'apple'},
  shouldRetry: retriers.isNetworkError // after every request, retry if a network error is thrown
  retry: {
    // Retry 5 times, in addition to the original request
    retries: 5,
  }
}).then(response => {
  // handle responses
});

Any option that promise-retry accepts will be passed through from options.retry. See the promise-retry documentation for all options.

Custom Retry Logic

We've provided two default "retrier" functions that decide to retry 503/504 status code responses and network errors (jsonFetch.retriers.is5xx and jsonFetch.retriers.isNetworkError respectively). You can easily provide your own custom retrier function to options.shouldRetry.

The contract for a retrier function is:

shouldRetry([Error || FetchResponse]) returns bool

You can use any attribute of the FetchResponse or Error to determine whether to retry or not. Your function must handle both errors (such as network errors) and FetchResponse objects without blowing up. We recommend stateless, side-effect free functions. You do not need to worry about the maximum number of retries -- promise-retry will stop retrying after the maximum you specify. See the tests and src/retriers.js file for examples.

On Request callbacks

Two callback functions can be passed as options to do something onRequestStart and onRequestEnd. This may be especially helpful to log request and response data on each request. If you have retries enabled, these will trigger before and after each actual, individual request.

onRequestStart

If given, onRequestStart is called with:

{
  // ... all the original json-fetch options, plus:
  url: string;
  retryCount: number;
}

onRequestEnd

If given, onRequestEnd is called with:

{
  // ... all the original json-fetch options, plus:
  url: string;
  retryCount: number;
  status?: Response['status'];
  error?: Error;
}

For example, to log before and after each request:

const requestUrl = 'http://www.test.com/products/1234';
await jsonFetch(requestUrl, {
  onRequestStart: ({url, timeout, retryCount}) =>
    console.log(`Requesting ${url} with timeout ${timeout}, attempt ${retryCount}`),
  onRequestEnd: ({url, retryCount, status}) =>
    console.log(`Requested ${url}, attempt ${retryCount}, got status ${status}`),
});

Contributing

Please follow our Code of Conduct when contributing to this project.

yarn install
yarn test

Deploying a new version

This module is automatically deployed when a version tag bump is detected by Travis. Remember to update the changelog!

yarn version

License

MIT

Module scaffold generated by generator-goodeggs-npm.