Home

Awesome

<div align="center"> <h1>Fatcher</h1>

Send fetch request gracefully in browsers and nodeJS

codecov install size <a href="https://unpkg.com/fatcher"><img alt="Size" src="https://img.badgesize.io/https://unpkg.com/fatcher"></a> <a href="https://npmjs.com/package/fatcher"><img src="https://img.shields.io/npm/v/fatcher.svg" alt="npm package"></a> <a href="https://nodejs.org/en/about/releases/"><img src="https://img.shields.io/node/v/fatcher.svg" alt="node compatibility"></a> <a href="https://github.com/fanhaoyuan/fatcher/actions/workflows/ci.yml"><img src="https://github.com/fanhaoyuan/fatcher/actions/workflows/ci.yml/badge.svg?branch=master" alt="build status"></a>

</div>

Introduction

Fatcher is a lightweight HTTP request library based on fetch. It allows us to use native fetch for web requests in a browser and NodeJS environment.

It is wrapped using the native fetch, we require that browsers or NodeJS support fetch when we use it.

Fatcher aims to embrace the fetch of the standard library and at the same time provide some functions that cannot be provided in fetch, as well as make the function better expand and reuse.

Features

Compatibility

Browsers

NodeJS

Getting Started

Install

NPM

>$ npm install fatcher

CDN

<script src="https://cdn.jsdelivr.net/npm/fatcher/dist/fatcher.min.js"></script>

Usage

Basic

Fatcher is fully compatible with fetch api.

const fetchOptions = {
  /* options */
};

fetch('https://foo.bar', fetchOptions);

// is similar to
import { fatcher } from 'fatcher';
fatcher('https://foo.bar', fetchOptions);

Middleware

Everything is middleware, middleware is a function which is like in koa

export type FatcherMiddleware = (
  request: FatcherRequest,
  next: (request?: Partial<FatcherRequest>) => Promise<FatcherResponse> | FatcherResponse,
) => Promise<FatcherResponse> | FatcherResponse;

We can pass the request context to next middleware and get the response form next middleware.

We should call the next function and return the response to prev middleware.

import { defineMiddleware } from 'fatcher';

const logs = defineMiddleware(async (request, next) => {
  const startTime = Date.now();

  const response = await next({
    url: 'https://foo.bar1',
  });

  const now = Date.now();
  console.log(`spent ${now - startTime}ms`);

  return response;
});

fatcher('https://foo.bar', { middlewares: [logs] }); //  sent to 'https://foo.bar1' instead of 'https://foo.bar'

Exception Handling

In the fetch api, all requests are considered successful. However, we generally consider a request with a response code of 200-299 to be successful.

import { exception, fatcher, isFatcherError } from 'fatcher';

fatcher('https://foo.bar', { middlewares: [exception()] }).catch(error => {
  if (isFatcherError(error)) {
    // handle fatcher error
    return;
  }

  // handle other error
});

Packages

License

MIT