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-client

v0.0.1

Published

A convenient fetch client with middleware support.

Downloads

3

Readme

fetch-client

A convenient fetch client with middleware support.

MIT License

build:? coverage:? Package Quality

Features

You can do all the same thing that you do with fetch, plus:

  • Custom middlewares to intercept requests, responses, and caught errors.
  • Useful middlewares available as separate npm packages.
  • Create custom config instances.
  • Convenient aliases for the supported methods.
  • Runs in Node and all browsers(with polyfill).

Installation

$ npm install --save fetch-client

Usage

Note: Make sure you have a fetch compatible environment or added a appropriate polyfill.

Performing a GET request

import FetchClient from 'fetch-client';

let fetchClient = new FetchClient();
fetchClient.get('http://httpbin.org/get?param1=param1')
  .then((response) => response.json())
  .then((json) => console.log(json))
  .catch((error) => console.error(error));

Performing a POST request


import FetchClient from 'fetch-client';

let fetchClient = new FetchClient();
fetchClient.post('http://httpbin.org/post?param1=param1', {
  param2: 'param2',
  param3: 'param3'
}).then((response) => response.json())
  .then((json) => console.log(json))
  .catch((error) => console.error(error));

API

Create custom config instance

You can create a new instance of FetchClient with a custom config.

let fetchClient = new FetchClient({
  headers: {
    'X-Custom-Header': 'foobar'
  }
});

fetchClient.get(url)
  .then((response) => {
    // handle response
  })
  .catch((error) => {
    // handle error
  });

Request method aliases

For convenience aliases have been provided for all supported request methods.

  • fetchClient.fetch(url[, options])
  • fetchClient.fetch(request[, options])
  • fetchClient.get(url[, options])
  • fetchClient.get(request[, options])
  • fetchClient.head(url[, options])
  • fetchClient.head(request[, options])
  • fetchClient.delete(url[, options])
  • fetchClient.delete(request[, options])
  • fetchClient.put(url[, data[, options]])
  • fetchClient.put(request[, data[, options]])
  • fetchClient.post(url[, data[, options]])
  • fetchClient.post(request[, data[, options]])
  • fetchClient.patch(url[, data[, options]])
  • fetchClient.patch(request[, data[, options]])

NOTE: When using the alias methods url, method, and data properties don't need to be specified in options.

Middleware

You can add middleware objects to any instance, to intercept requests and responses.

The middleware object must have defined at least one of these methods:

  • request(req) takes the Request that will be passed to global.fetch() after interceptors run. It should return the same Request, or create a new one. Errors thrown in request interceptors will be handled by requestError interceptors.
  • requestError(error) acts as a Promise rejection handler during Request creation and request interceptor execution. It will receive the rejection reason, and can either re-throw, or recover by returning a valid Request.
  • response(res) will be run after `fetch()`` completes, and will receive the resulting Response. As with request, it can either pass the Response along, return a modified response, or throw.
  • responseError(error) is similar to requestError, and acts as a Promise rejection handler for response rejections.
let jsonMiddleware = {
  response(res) {
    return res.json().catch((e) => {
      return e;
    });
  }
};

// fetchClient.addMiddlewares(ArrayOrMiddlewares)
fetchClient.addMiddlewares(jsonMiddleware);

// clear
fetchClient.clearMiddlewares();

Interceptors' running sequence

import FetchClient from 'fetch-client';

let fetchClient = new FetchClient();
let middleware1 = {
  request(req) {
    req.headers.set('x-req-fake1', true);
    return req;
  },

  requestError(error) {
    return global.Promise.reject(error);
  },

  response(res) {
    res.headers.set('x-res-fake1', true);
    return res;
  },

  responseError(error) {
    return global.Promise.reject(error);
  }
};
let middleware2 = {
  request(req) {
    req.headers.set('x-req-fake2', true);
    return req;
  },

  requestError(error) {
    return global.Promise.reject(error);
  },

  response(res) {
    res.headers.set('x-res-fake2', true);
    return res;
  },

  responseError(error) {
    return global.Promise.reject(error);
  }
};

fetchClient.addMiddlewares([middleware1, middleware2]);
fetchClient.fetch('http://example.com/page');


// the interceptors will be executed with the following sequence, equal with:
let req = new Request('http://example.com/page');
let promise = Promise.resolve(req);

promise
  // handle request
  .then(middleware1.request)
  .then(null, middleware1.requestError)
  .then(middleware2.request)
  .then(null, middleware2.requestError)
  // call the fetch method
  .then(global.fetch)
  // handle response
  .then(middleware1.response)
  .then(null, middleware1.responseError)
  .then(middleware2.response)
  .then(null, middleware2.responseError);

Additional middlewares

On the way...

Contributing

Pull requests and stars are highly welcome.

For bugs and feature requests, please create an issue.