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 🙏

© 2025 – Pkg Stats / Ryan Hefner

funtch

v2.5.4

Published

FUNctional feTCH isomorphic

Readme

funtch - Functional Fetch

CI Status Doc Status codecov npm version Quality Gate Status

Fetch based on isomorphic-fetch with functional and customizable behavior.

Getting started

Add dependency to your project

npm i -S funtch

Usage

Full documentation is available here.

Full usage example in example folder

ES6

import funtch from 'funtch';

funtch.get('https://api.github.com').then((data) => doSomething(data));

CommonJS

const funtch = require('funtch').default;

funtch.get('https://api.github.com').then((data) => doSomething(data));

API

You can send HTTP requests from common verbs by invoking the following methods from funtch:

| Methode name | Params | Description | | ------------ | ---------------------------------------- | --------------------------------------------------------------------- | | get | url: String query: Object/Map | Perform a GET with optional query params | | post | url: String body: Any | Perform a POST with given body and Content-type guessed from param | | put | url: String body: Any | Perform a PUT with given body and Content-type guessed from param | | patch | url: String body: Any | Perform a PATCH with given body and Content-type guessed from param | | delete | url: String | Perform a DELETE |

If default pattern doesn't match your needs, you can build a step by step request by invoking funtch.url(url: String) and applying following methods:

| Method name | Params | Description | | ------------------ | ------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | | query | query: Object/Map | Append query params when requesting | | header | key: String value: String | Add HTTP header | | auth | value: String | Add Authorization Header with given value | | contentJson | | Add Content-type: application/json header | | contentText | | Add Content-type: text/plain header | | guessContentType | body: Any | Guess content type by checking if body is a JSON. If true, content is set to JSON, otherwise to text | | acceptJson | | Add Accept: application/json header | | acceptText | | Add Accept: text/plain header | | contentHandler | callback: func(response) | See content handler | | errorHandler | callback: func(response, contentHandler) | See error handler | | abortHandler | callback: func(error) | Callback method when request is aborted | | fullResponse | | Return complete response with {status, headers, data}, instead of just raw data by default | | body | body: Any guess: Boolean default true | Set body content of request, and guessing content on the fly | | get | | Set method to GET and send request | | post | body: Any | Set method to POST, add body if provided with content guess and send request | | put | body: Any | Set method to PUT, add body if provided with content guess and send request | | patch | body: Any | Set method to PATCH, add body if provided with content guess and send request | | delete | | Set method to DELETE and send request | | method | method: String | Set HTTP method to given value | | send | | Send request as it | | abort | | Abort request |

All these methods, except abort, are chainable and once send is called, the result is a Promise.

const fetchPromise = funtch
  .url('https://api.github.com')
  .auth('Basic SECRET')
  .contentJson()
  .acceptJson()
  .post({ star: true });

fetchPromise
  .then((data) => console.log(data))
  .catch((err) => console.error(data));

Cancelable request can be done this way.

const fetchRequest = funtch
  .url('https://api.vibioh.fr/delay/10') // 10 seconds delay
  .abortHandler((e) => console.warn(`Request was aborted: ${e.name}`));

fetchRequest.get();
fetchRequest.abort();

You can create a pre-configured builder, in order to avoid repeating yourself, by passing an object to the withDefault method with keys as the config function name.

const funtcher = funtch.withDefault({
  baseURL: 'https://api.github.com',
  auth: 'github SecretToken',
  fullResponse: true,
  contentJson: true,
});

funtcher.get('/user/keys').then((response) => doSomething(response.data));
funtcher
  .post('/user/keys', 'my-ssh-key')
  .then((response) => doSomething(response.data));

Error Handling

By default, funtch will rejects promise with a full response describing error if HTTP status is greater or equal than 400. This object contains HTTP status, response headers and data (in plain text or JSON, according to content handler).

{
  status: 404,
  headers: {
    'content-length': '19',
    'content-type': 'text/plain; charset=utf-8',
    date: 'Sat, 06 May 2017 11:58:38 GMT',
    'x-content-type-options': 'nosniff',
    connection: 'close'
  },
  data: '404 page not found',
}

Customization

Custom content handler

By default, fetch exposes only two methods for reading content : text() and json(). Instead of juggling with these methods, funtch return content by examining Content-Type header and call one of the two methods.

You can easily override default content handler by calling content() on the build. The content handler method accepts a reponse and return a Promise. Method is also passed to error handler method, in order to read content while identifying error.

Below an example that parse XML response.

import funtch { MEDIA_TYPE_JSON, CONTENT_TYPE_HEADER } from 'funtch';

const contentTypeJsonRegex = new RegExp(MEDIA_TYPE_JSON, 'i');
const contentTypeXmlRegex = /application\/xml/i;

function xmlContent(response) {
  if (contentTypeJsonRegex.test(response.headers.get(CONTENT_TYPE_HEADER))) {
    return response.json();
  }

  return new Promise(resolve => {
    response.text().then(data => {
      if (contentTypeXmlRegex.test(response.headers.get(CONTENT_TYPE_HEADER))) {
        resolve(new DOMParser().parseFromString(data, 'text/xml'));
      }
      resolve(data);
    });
  });
}

funtch
  .url('https://api.github.com')
  .content(xmlContent)
  .get();

Custom error handler

By default, fetch returns a valid Promise without considering http status. Funtch error handler is called first, in this way, you can identify an error response and reject the Promise. By default, if HTTP status is greather or equal than 400, it's considered as error.

You can easyly override default error handler by calling errorHandler() on the builder. The error handler method accepts a response and a content handler, and return a Promise. You can reimplement it completely or adding behavior of the default one.

Below an example that add a toString() behavior.

import funtch, { errorHandler } from 'funtch';

function errorWithToString(response) {
  return new Promise((resolve, reject) =>
    errorHandler(response)
      .then(resolve)
      .catch((err) =>
        reject({
          ...err,
          toString: () => {
            if (typeof err.content === 'string') {
              return err.content;
            }
            return JSON.stringify(err.content);
          },
        }),
      ),
  );
}

funtch
  .url('https://api.github.com')
  .errorHandler(errorWithToString)
  .get()
  .catch((err) => console.log(String(err)));