All Projects → soal → fennch

soal / fennch

Licence: MIT license
Modern fetch-based axios-like HTTP client for the browser and node.js

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to fennch

Gretchen
Making fetch happen in TypeScript.
Stars: ✭ 301 (+2408.33%)
Mutual labels:  fetch, http-client
Ky
🌳 Tiny & elegant JavaScript HTTP client based on the browser Fetch API
Stars: ✭ 7,047 (+58625%)
Mutual labels:  fetch, http-client
Redux Requests
Declarative AJAX requests and automatic network state management for single-page applications
Stars: ✭ 330 (+2650%)
Mutual labels:  fetch, http-client
fetchx
Beautiful way to fetch data in React
Stars: ✭ 71 (+491.67%)
Mutual labels:  fetch, http-client
Fetcher Ts
Type-safe wrapper around Fetch API
Stars: ✭ 87 (+625%)
Mutual labels:  fetch, http-client
http4s-dom
http4s, in a browser near you
Stars: ✭ 13 (+8.33%)
Mutual labels:  fetch, http-client
Node Fetch
A light-weight module that brings the Fetch API to Node.js
Stars: ✭ 7,176 (+59700%)
Mutual labels:  fetch, http-client
Fetch
Asynchronous HTTP client with promises.
Stars: ✭ 29 (+141.67%)
Mutual labels:  fetch, http-client
Cross Fetch
Universal WHATWG Fetch API for Node, Browsers and React Native.
Stars: ✭ 1,063 (+8758.33%)
Mutual labels:  fetch, http-client
Create Request
Apply interceptors to `fetch` and create a custom request function.
Stars: ✭ 34 (+183.33%)
Mutual labels:  fetch, http-client
fetch-wrap
extend WHATWG fetch wrapping it with middlewares
Stars: ✭ 21 (+75%)
Mutual labels:  fetch, http-client
Wretch
A tiny wrapper built around fetch with an intuitive syntax. 🍬
Stars: ✭ 2,285 (+18941.67%)
Mutual labels:  fetch, http-client
fitch.js
A lightweight Promise based HTTP client, using Fetch API.
Stars: ✭ 35 (+191.67%)
Mutual labels:  fetch, http-client
electron-request
Zero-dependency, Lightweight HTTP request client for Electron or Node.js
Stars: ✭ 45 (+275%)
Mutual labels:  fetch, http-client
bestfetch
fetch ⭐️caching ⭐️deduplication
Stars: ✭ 44 (+266.67%)
Mutual labels:  fetch, requests
Ky Universal
Use Ky in both Node.js and browsers
Stars: ✭ 421 (+3408.33%)
Mutual labels:  fetch, http-client
Grequests
A Go "clone" of the great and famous Requests library
Stars: ✭ 1,843 (+15258.33%)
Mutual labels:  http-client, requests
Libhv
🔥 比libevent、libuv更易用的国产网络库。A c/c++ network library for developing TCP/UDP/SSL/HTTP/WebSocket client/server.
Stars: ✭ 3,355 (+27858.33%)
Mutual labels:  http-client, requests
Xhr.js
🌎 xhr.js is a library(< 2Kb) to make AJAX/HTTP requests with XMLHttpRequest.
Stars: ✭ 12 (+0%)
Mutual labels:  fetch, requests
Php Fetch
A simple, type-safe, zero dependency port of the javascript fetch WebApi for PHP
Stars: ✭ 95 (+691.67%)
Mutual labels:  fetch, http-client

Fennch

Modern fetch-based HTTP client for the browser.

npm version

Fennch is:

fetch + request abortion + timeout support + request and response interceptions

Quickstart

Basic usage

import Fennch from "fennch";
const api = Fennch({
    baseUri: "http://awesome.app/api"
})
async function apiCall() {
    const result = await api.get("/awesome-data", {
        params: {
            awesome: "really",
            params: "cool"
        }
    });
    /* ###### Under the hood ######
        const result = await fetch("http://awesome.app/api/awesome-data?awesome=really&params=cool", {
            method: "GET"
        })
        return {
            ...response,
            body: await response.json() // if Content-Type is 'application/json'
        }
      #############################
    */
    /*
     `result` is a FResponse object which is Proxy that wraps native Response object.
     `result.headers` and `result.body` is already parsed and can accessed right away.
    */
    console.log(result.body) => /* => Awesome response! */
}

Request abortion

const api = Fennch({
  baseUri: "http://awesome.app/api"
});

const MySuperComponent = {
  currentRequest: null,

  handleUserAbort(req) {
    this.currentRequest.abort();
  },

  async apiCall() {
    this.currentRequest = api.get("/awesome-data", {
      params: {
        awesome: "really",
        params: "cool"
      }
    });
    let result;
    try {
      result = await currentRequest;
    } catch (err) {
      result = err;
    }
    return result;
  }
};

// I want make a request
MySuperComponent.apiCall()
  .then(res => res)
  .catch(err => {
    console.log(err); // => 'Request aborted'
  });

// Oh, wait, I changed my mind!
MySuperComponent.handleUserAbort();

Timeout

// Global timeout
const api = Fennch({
  baseUri: "http://awesome.app/api",
  timeout: 10000
});

async function apiCall() {
  try {
    await api.get("/awesome-data", {
        params: {
            awesome: "really",
            params: "cool"
        }
    });
  } catch (err) {
    // If request pednding more than 10 sec
    console.log(err.toString()) // -> "Timeout exceeded"
  }
}

// Timeout per-request, overrides global value
async function apiCallWithTimeout() {
  try {
    await api.get("/awesome-data", {
        timeout: 20000,
        params: {
            awesome: "really",
            params: "cool"
        }
    });
  } catch (err) {
    // If request pednding more than 20 sec
    console.log(err.toString()) // -> "Timeout exceeded"
  }
}

Interceptors

You can register any number of interceptors using register() method. It returns function that can be used to unregister this interceptor.

const unregister = fennch.interceptor.register({
  request(request) {}, // Must return FRequest object, for example `request` that passed as an argument
  requestError(error) {},
  response(response) {}, // Must return FResponse object, for example `request` that passed as an argument
  responseError(error) {}
})

unregister() // unregister interceptor

Simple example:

const api = Fennch({
  baseUri: "http://awesome.app/api"
});

const unregister = api.interceptor.register({
  request(request) {
    /* Making some tweaks in request */
    /*...*/
    return request // Interceptor *must* return request 
  },
  requestError(request) {
    /* Making some tweaks in request */
    /*...*/
    return Promise.resolve(request)
  },
  response(response) {
    /* Making some tweaks in response */
    /*...*/
    return response // Interceptor *must* return response 
  },
  responseError(err) {
    /* If request is aborted adding `cancel` property to error */
    if (err.toString() === 'AbortError') {
      err.cancel = true
      return Promise.reject(err)
    }
    if (!err.response && err.message === 'Network Error') {
      err = networkErrorResolver(err)
      return Promise.resolve(err)
    }
    return err
  }
})

Example for refreshing authorization token using interceptor:

const accessToken = "some_access_token"
const refreshToken = "some_refresh_token"
const api = Fennch({
  baseUri: "http://awesome.app/api",
  headers: {
    "Content-Type": "application/json",
    Accept: 'application/json',
    Authorization: `Bearer ${accessToken}`
  },
});

api.interceptors.register({
  async response(response) {
    if (response.status === 401) {
      try {
        const refreshed = await api.post('/refresh_token', {
          headers: {
            Authorization: `Bearer ${refreshToken}`
          }
        })
        const newAccessToken = refreshed.body.token
        const request = response.request
        request.headers.Authorization = `Bearer ${newAccessToken}`
        return api.req(request)
      } catch (error) {
        return Promise.reject(error)
      }
    }
  }
})
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].