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

cp-axios

v0.3.1

Published

axios wrapper that provides an advanced cancellation api

Downloads

160

Readme

Build Status Coverage Status npm npm bundle size David

Table of contents :page_with_curl:

SYNOPSIS :sparkles:

cpAxios is a simple axios wrapper that provides an advanced cancellation api.

This library supports three types of the cancellation API that could be used simultaneously:

In addition, since cpAxios return a custom promise instead of the native, you get some powers of CPromise:

  • concurrency limiting fot creating request queues
  • progress capturing
  • promise timeouts

Installation :hammer:

Starting from version 0.1.12 the package imports peer dependencies instead of built-in. So, you should install c-promise2 and axios packages manually using the following command:

$ npm install cp-axios
$ yarn add cp-axios

CDN bundle

Browser UMD bundle (with all dependencies inside):

module global export- cpAxios

Usage examples

Live Example

Live browser example

Request aborting using CPromise cancellation API:

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

 const chain = cpAxios(url)
      .timeout(5000)
      .then(response => {
          console.log(`Done: ${JSON.stringify(response.data)}`)
      }, err => {
          console.warn(`Request failed: ${err}`)
      });

 setTimeout(() => chain.cancel(), 500);

Request aborting using AbortController signal:

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

 // you could use any other AbortController implementation, but CPromise already provides it
 const abortController = new CPromise.AbortController();
 const {signal} = abortController;
 
 cpAxios(url, {signal})
      .timeout(5000)
      .then(response => {
          console.log(`Done: ${JSON.stringify(response.data)}`)
      }, err => {
          console.warn(`Request failed: ${err}`)
      });

 setTimeout(() => abortController.abort(), 500);

Request aborting using Axios cancelToken:

 const cpAxios= require('cp-axios');
 const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
 const source = cpAxios.CancelToken.source();
 
 cpAxios(url, {cancelToken: source.token})
      .timeout(5000)
      .then(response => {
          console.log(`Done: ${JSON.stringify(response.data)}`)
      }, err => {
          console.warn(`Request failed: ${err}`)
      });

 setTimeout(() => source.cancel(), 500);

Using generators as async functions:

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

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

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

Abortable concurrent requests

const cpAxios= require('cp-axios');
const CPromise = require('c-promise2');

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

// other request will be aborted if one fails

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

Making a request queue using mapper function with concurrency limit and progress capturing Live Demo:

import { CPromise } from "c-promise2";
import cpAxios from "cp-axios";

const promise = CPromise.all(
  [
    "https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=2s&x=1",
    "https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=2s&x=2",
    "https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=2s&x=3",
    "https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=2s&x=4",
    "https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=2s&x=5",
    "https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=2s&x=6",
    "https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=2s&x=7"
  ],
  {
    mapper: (url) => {
      console.log(`Request [${url}]`);
      return cpAxios(url);
    },
    concurrency: 2
  }
)
  .innerWeight(7)
  .progress((p) => console.log(`Progress: ${(p * 100).toFixed(1)}`))
  .then(
    (v) => console.log(`Done: `, v),
    (e) => console.warn(`Failed: ${e}`)
  );

// yeah, we able to cancel the entire task and abort pending network requests
//setTimeout(() => promise.cancel(), 4500);

React usage

cpAxios can be easily used with React using the useAsyncEffect hook, which allows cancelable asynchronous functions to be executed as effects (Live Demo):

import React from "react";
import { useAsyncEffect } from "use-async-effect2";
import cpAxios from "cp-axios";

/*
 Note: the related network request will also be aborted
 Check out your network console
 */

function TestComponent({ url, timeout }) {
  const [cancel, done, result, err] = useAsyncEffect(
    function* () {
      return (yield cpAxios(url).timeout(timeout)).data;
    },
    { states: true, deps: [url] }
  );

  return (
    <div>
      {done ? (err ? err.toString() : JSON.stringify(result)) : "loading..."}
      <button onClick={cancel} disabled={done}>
        Cancel async effect (abort request)
      </button>
    </div>
  );
}

export default TestComponent;

The request will be automatically aborted when the effect is canceled / restarted.

API Reference

The package exports a wrapped version of the axios instance. See the axios documentation to get more information.

cpAxios(url, {signal, ...nativeAxiosOptions}): CPromise

Options:

  • signal- the AbortController signal

  • ...nativeAxiosOptions- other options supported by axios package

Learn more about CPromise features

Related projects

  • cp-fetch - fetch with timeouts and promise cancellation
  • c-promise2 - promise with cancellation and progress capturing support

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.