Code Monkey home page Code Monkey logo

c-fetch's Introduction

Travis (.com) Coverage Status npm npm bundle size David

SYNOPSIS โœจ

cpFetch is a simple wrapper around fetch with cancelable promise (c-promise2). This lib can be used for both backend and frontend development, platform specific fetch API is provided by cross-fetch package.

Why โ“

It's good to have the ability to cancel fetch requests automatically when the related promise is canceling. Using powerful of a promise with cancelation feature lets you automatically manage fetch request cycle, handling timeouts, abort the related request when you use concurrent requests.

Features / Advantages

  • browser & node.js support
  • timeouts
  • cancellation (rejecting promise chain & aborting the related network request)
  • returns CPromise instead of native
  • automatically aborting other requests, passed to the CPromise.all, if one fails.
  • automatically aborting other requests, passed to the CPromise.race, if one of them resolves or fails.

Installation ๐Ÿ”จ

$ npm install cp-fetch
$ yarn add cp-fetch
// cross-platform version
const cpFetch= require('cpFetch'); 

// version that uses the global fetch API, instead of cross-fetch ponyfill 
// (for modern browsers only or in case you're using third-party polyfill)
import cpFetch from "cp-fetch/lib/native";

CDN bundle

Ready for use prebuilt UMD bundles for browser with all dependencies inside.

These module bundles are only suitable to load as a script directly from the html page. If you're using some module bunlder like webpack or rollup, please import cjs module to avoid potential duplications in your project dependencies tree.

Global module export is cpFetch.

Usage examples

Live Example

Live browser example

Abortable fetch with timeout

A simple example:

const cpFetch= require('cp-fetch');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';

const chain = cpFetch(url, {timeout: 10000})
    .then(response => response.json())
    .then(data => console.log(`Done: `, data), err => console.log(`Error: `, err))

setTimeout(()=> chain.cancel(), 1000); // abort the request after 1000ms 

// you able to call cancel() at any time to cancel the entire chain at any stage
// Take into account the related network request will also be aborted

The same using generators as async function:

const cpFetch= require('cp-fetch');
const CPromise= require('c-promise2');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';

const chain= CPromise.from(function*(){
    try{
        const response= yield cpFetch(url, {timeout: 5000});
        console.log(`Done: `, yield response.json())
    }catch(err){
        console.log(`Error: `, err)
    }   
});

 setTimeout(()=> chain.cancel(), 1000); // abort the request after 1000ms 

Abortable concurrent requests

const cpFetch= require('cp-fetch');
const CPromise = require('c-promise2');

const chain= CPromise.race([
    cpFetch("https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=3s"),
    cpFetch("https://run.mocky.io/v3/30a97b24-ed0e-46e8-9f78-8f954aead2f8?mocky-delay=5s")
]).timeout(10000).then((response)=> {
    console.log(`Result :`, response.data);
}, function (err) {
    console.warn(`We got an error: ${err}`);
});

// the slower request will be aborted

// setTimeout(()=> chain.cancel(), 1000); // abort the request after 1000ms 

API Reference

The package exports a wrapped version of the fetch function.

cFetch(url, {timeout, ...nativeFetchOptions}): CPromise

Options:

timeout- the timeout before the promise and related request will be rejected/aborted.

...nativeFetchOptions- other native options of the fetch function.

Learn more about CPromise features

Related projects

  • cp-axios - a simple axios wrapper that provides an advanced cancellation api
  • c-promise2 - promise with cancellation and progress capturing support
  • use-async-effect2 - cancel async code in functional React components
  • cp-koa - Koa with cancelable middlewares

License

The MIT License Copyright (c) 2020 Dmitriy Mozgovoy [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

c-fetch's People

Contributors

digitalbrainjs avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.