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

v1.1.0

Published

A http client wrapper for fetch api with middleware support.

Downloads

1,372

Readme

Fetch Http Client

GitHub license npm version Build Status Coverage Status

A http client wrapper for Fetch API with middleware support.

Introduction

Fetch API is a elegant way to access HTTP resources. I used it in my React/ReactNative project as the default network layer. But it still has some inconvenience to use. For example, every request should carry the access token in HTTP request headers, ervery request error should be logged to console etc.

If Fetch API support middleware, everything can be elegantly fixed. Both fetch-plus and http-client provided the middleware support, but if you need some asynchronous pre-request opreation, they could not suppport elegantly.

So this project is another choice to use Fetch API with middleware support, it's quite simple and powerful.

Installation

npm install fetch-http-client --save

Usage

Import

import FetchHttpClient, { json } from 'fetch-http-client';

Quick start

// Create a new client object.
const client = new FetchHttpClient('http://api.example.com/endpoint');

// Add access token
client.addMiddleware(request => {
  request.options.headers['X-Access-Token'] = 'secret';
});

// Add json support
client.addMiddleware(json());

// Add Logging
client.addMiddleware(request => response => {
  console.log(request, response);
});

// Fire request.
client.get('test').then(response => console.log(response.jsonData));

// Path variables support.
client.get('users/{id}', { uriParams: { id: 1 } }).then(response => console.log(response.jsonData));

Asynchronous pre-request middleware

if your access token is stored in a asynchronous storage, it should be fetch before every request, you can use such kind of middleware:

// Add access token asynchronously
client.addMiddleware(request => {
  return AsynchronousStorage.fetch('accessToken').then(token => {
    request.options.headers['X-Access-Token'] = token;
    return request;
  });
});

That means your middleware could return a Promise object and the real request opreate will be issued after the asynchronous method finished.

NEVER forget returning the request object after you handled the result!

API

FetchHttpClient

new FetchHttpClient(baseUrl:string);

fetch

fetch method can been used the same as Fetch API.

instance.fetch(uri:string[, options: object])

request

Convenience way to issue a request with specific verb.

instance.request(uri:string, method:string[, options: object])

get

Convenience way to issue a GET request.

instance.get(uri:string[, options: object])

post

Convenience way to issue a POST request.

instance.post(uri:string[, options: object])

put

Convenience way to issue a PUT request.

instance.put(uri:string[, options: object])

delete

Convenience way to issue a DELETE request.

instance.delete(uri:string[, options: object])

patch

Convenience way to issue a PATCH request.

instance.patch(uri:string[, options: object])

Build-in middlewares

query

This middleware could add the ability to append object value to query string:

// Add query middleware
client.addMiddleware(query());

// Request
client.get('test', {
  query: {
    foo: 'FOO',
    bar: 'BAR',
  },
});

It will request to http://api.example.com/endpoint/test?foo=FOO&bar=BAR.

form

Like query, this could be used to handle post form values.

// Add form middleware
client.addMiddleware(form());

// Request
client.post('test', {
  form: {
    foo: 'FOO',
    bar: 'BAR',
  },
});

header

A convenience middleware to add headers to request.

// Add header middleware
client.addMiddleware(header({
  'X-Request-By': 'FetchHttpClient',
}));

userAgent

A convenience middleware to set User-Agent to headers.

// Add header middleware
client.addMiddleware(userAgent({
  'Client': '1.1',
}));

json

Convert object to request and parse from response.

// Add json middleware
client.addMiddleware(json());

// Request
client.post('add', {
  json: {
    foo: 'FOO',
  },
}).then(response => {
  console.log(response.jsonData);
});

timeout

Set timeout options to fetch.

// Add timeout middleware
client.addMiddleware(timeout(1000));

credentials

Set credentials options to fetch. If you want to automatically send cookies for the current domain, use this middleware and config it as same-origin.

// Add credentials middleware
client.addMiddleware(credentials('same-origin'));

Feedback

If you have any questions, use Issues.

Sina Weibo: @starlight36

License

MIT Licence.