{"id":16823427,"url":"https://github.com/digitalbrainjs/cp-axios","last_synced_at":"2025-04-11T04:13:56.821Z","repository":{"id":56824050,"uuid":"298858296","full_name":"DigitalBrainJS/cp-axios","owner":"DigitalBrainJS","description":"Simple axios wrapper that provides an advanced cancellation api","archived":false,"fork":false,"pushed_at":"2021-11-25T20:21:42.000Z","size":1375,"stargazers_count":10,"open_issues_count":2,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-25T02:23:15.879Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DigitalBrainJS.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-09-26T16:46:58.000Z","updated_at":"2024-05-13T13:06:55.000Z","dependencies_parsed_at":"2022-09-01T13:02:36.067Z","dependency_job_id":null,"html_url":"https://github.com/DigitalBrainJS/cp-axios","commit_stats":null,"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DigitalBrainJS%2Fcp-axios","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DigitalBrainJS%2Fcp-axios/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DigitalBrainJS%2Fcp-axios/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DigitalBrainJS%2Fcp-axios/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DigitalBrainJS","download_url":"https://codeload.github.com/DigitalBrainJS/cp-axios/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247892112,"owners_count":21013645,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-13T11:07:58.639Z","updated_at":"2025-04-11T04:13:56.806Z","avatar_url":"https://github.com/DigitalBrainJS.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![Build Status](https://travis-ci.com/DigitalBrainJS/cp-axios.svg?branch=master)](https://travis-ci.com/DigitalBrainJS/cp-axios)\n[![Coverage Status](https://coveralls.io/repos/github/DigitalBrainJS/cp-axios/badge.svg?branch=master)](https://coveralls.io/github/DigitalBrainJS/cp-axios?branch=master)\n![npm](https://img.shields.io/npm/dm/cp-axios)\n![npm bundle size](https://img.shields.io/bundlephobia/minzip/cp-axios)\n![David](https://img.shields.io/david/DigitalBrainJS/cp-axios)\n\n## Table of contents :page_with_curl:\n- [SYNOPSIS](#synopsis-sparkles)\n- [Installation](#installation-hammer)\n- [CDN bundle](#cdn-bundle)\n- [Usage examples](#usage-examples)\n    - [Request aborting using CPromise cancellation  API](#request-aborting-using-cpromise-cancellation-api)\n    - [Request aborting using AbortController signal](#request-aborting-using-abortcontroller-signal)\n    - [Request aborting using Axios cancelToken](#request-aborting-using-axios-canceltoken)\n    - [Using generators as async functions](#using-generators-as-async-functions)\n    - [Abortable concurrent requests](#abortable-concurrent-requests)\n    - [React usage](#react-usage)\n- [API Reference](#api-reference)    \n- [Related projects](#related-projects)    \n- [License](#license)    \n\n\n## SYNOPSIS :sparkles:\n\n**cpAxios** is a simple [axios](https://www.npmjs.com/package/axios) wrapper that provides an advanced cancellation api.\n\nThis library supports three types of the cancellation  API that could be used *simultaneously*:\n- Axios [cancelableToken](https://github.com/axios/axios#cancellation)\n- [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) signal\n- [CPromise](https://www.npmjs.com/package/c-promise2) promise cancellation  API \n\nIn addition, since cpAxios return a custom promise instead of the native, you get some powers of [CPromise](https://www.npmjs.com/package/c-promise2):\n- concurrency limiting fot creating request queues\n- progress capturing\n- promise timeouts\n\n## Installation :hammer:\n\nStarting from version `0.1.12` the package imports peer dependencies instead of built-in.\nSo, you should install `c-promise2` and `axios` packages manually using the following command:\n\n```bash\n$ npm install cp-axios\n```\n\n```bash\n$ yarn add cp-axios\n```\n\n### CDN bundle\nBrowser UMD bundle (with all dependencies inside):\n- [production UMD bundle](https://unpkg.com/cp-axios) (or [minified](https://unpkg.com/cp-axios/dist/cp-axios.umd.min.js) ~45KB)\n\nmodule global export- `cpAxios`\n\n## Usage examples\n\n#### Live Example\n\n[Live browser example](https://codesandbox.io/s/strange-almeida-1lcjj)\n\n#### Request aborting using CPromise cancellation API:\n````javascript\n const cpAxios= require('cp-axios');\n const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';\n\n const chain = cpAxios(url)\n      .timeout(5000)\n      .then(response =\u003e {\n          console.log(`Done: ${JSON.stringify(response.data)}`)\n      }, err =\u003e {\n          console.warn(`Request failed: ${err}`)\n      });\n\n setTimeout(() =\u003e chain.cancel(), 500);\n````\n\n#### Request aborting using AbortController signal:\n````javascript\n const cpAxios= require('cp-axios');\n const CPromise= require('c-promise2');\n const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';\n\n // you could use any other AbortController implementation, but CPromise already provides it\n const abortController = new CPromise.AbortController();\n const {signal} = abortController;\n \n cpAxios(url, {signal})\n      .timeout(5000)\n      .then(response =\u003e {\n          console.log(`Done: ${JSON.stringify(response.data)}`)\n      }, err =\u003e {\n          console.warn(`Request failed: ${err}`)\n      });\n\n setTimeout(() =\u003e abortController.abort(), 500);\n````\n\n#### Request aborting using Axios cancelToken:\n````javascript\n const cpAxios= require('cp-axios');\n const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';\n const source = cpAxios.CancelToken.source();\n \n cpAxios(url, {cancelToken: source.token})\n      .timeout(5000)\n      .then(response =\u003e {\n          console.log(`Done: ${JSON.stringify(response.data)}`)\n      }, err =\u003e {\n          console.warn(`Request failed: ${err}`)\n      });\n\n setTimeout(() =\u003e source.cancel(), 500);\n````\n\n#### Using generators as async functions:\n\n````javascript\nconst cpAxios= require('cp-axios');\nconst CPromise= require('c-promise2');\nconst url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';\n\nconst chain= CPromise.run(function*(){\n    try{\n        const response= yield cpAxios(url).timeout(5000);\n        console.log(`Done: `, response.data)\n    }catch(err){\n        console.log(`Error: `, err)\n    }   \n});\n\n setTimeout(()=\u003e chain.cancel(), 1000); // abort the request after 1000ms \n````\n\n#### Abortable concurrent requests\n\n````javascript\nconst cpAxios= require('cp-axios');\nconst CPromise = require('c-promise2');\n\n// same as cpAxios.all([...])\nconst chain= CPromise.all([\n    cpAxios(\"https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=3s\"),\n    cpAxios(\"https://run.mocky.io/v3/30a97b24-ed0e-46e8-9f78-8f954aead2f8?mocky-delay=5s\")\n]).timeout(10000).then(responses=\u003e {\n    console.log(`Results :`, responses[0].data, responses[1].data);\n}, function (err) {\n    console.warn(`We got an error: ${err}`);\n});\n\n// other request will be aborted if one fails\n\n setTimeout(()=\u003e chain.cancel(), 1000); // abort the requests after 1000ms \n````\n\nMaking a request queue using mapper function with concurrency limit and progress capturing \n[Live Demo](https://codesandbox.io/s/cpromise-all-concurrent-generatorforked-k0fjk?file=/src/index.js):\n````javascript\nimport { CPromise } from \"c-promise2\";\nimport cpAxios from \"cp-axios\";\n\nconst promise = CPromise.all(\n  [\n    \"https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=2s\u0026x=1\",\n    \"https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=2s\u0026x=2\",\n    \"https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=2s\u0026x=3\",\n    \"https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=2s\u0026x=4\",\n    \"https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=2s\u0026x=5\",\n    \"https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=2s\u0026x=6\",\n    \"https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=2s\u0026x=7\"\n  ],\n  {\n    mapper: (url) =\u003e {\n      console.log(`Request [${url}]`);\n      return cpAxios(url);\n    },\n    concurrency: 2\n  }\n)\n  .innerWeight(7)\n  .progress((p) =\u003e console.log(`Progress: ${(p * 100).toFixed(1)}`))\n  .then(\n    (v) =\u003e console.log(`Done: `, v),\n    (e) =\u003e console.warn(`Failed: ${e}`)\n  );\n\n// yeah, we able to cancel the entire task and abort pending network requests\n//setTimeout(() =\u003e promise.cancel(), 4500);\n````\n## React usage\n\n`cpAxios` can be easily used with React using the [`useAsyncEffect`](https://www.npmjs.com/package/use-async-effect2) hook, which allows cancelable asynchronous functions to be executed as effects ([Live Demo](https://codesandbox.io/s/use-async-effect-axios-minimal-pdngg?file=/src/TestComponent.js)):\n\n```jsx\nimport React from \"react\";\nimport { useAsyncEffect } from \"use-async-effect2\";\nimport cpAxios from \"cp-axios\";\n\n/*\n Note: the related network request will also be aborted\n Check out your network console\n */\n\nfunction TestComponent({ url, timeout }) {\n  const [cancel, done, result, err] = useAsyncEffect(\n    function* () {\n      return (yield cpAxios(url).timeout(timeout)).data;\n    },\n    { states: true, deps: [url] }\n  );\n\n  return (\n    \u003cdiv\u003e\n      {done ? (err ? err.toString() : JSON.stringify(result)) : \"loading...\"}\n      \u003cbutton onClick={cancel} disabled={done}\u003e\n        Cancel async effect (abort request)\n      \u003c/button\u003e\n    \u003c/div\u003e\n  );\n}\n\nexport default TestComponent;\n```\n\nThe request will be automatically aborted when the effect is canceled / restarted.\n\n## API Reference\n\nThe package exports a wrapped version of the axios instance. \nSee the axios [documentation](https://www.npmjs.com/package/axios#axios) to get more information.\n\n`cpAxios(url, {signal, ...nativeAxiosOptions}): CPromise`\n\nOptions:\n\n- `signal`- the AbortController signal\n\n- `...nativeAxiosOptions`- other options supported by [axios](https://www.npmjs.com/package/axios) package\n\nLearn more about [CPromise](https://www.npmjs.com/package/c-promise2) features \n\n## Related projects\n\n- [cp-fetch](https://www.npmjs.com/package/cp-fetch) - fetch with timeouts and promise cancellation \n- [c-promise2](https://www.npmjs.com/package/c-promise2) - promise with cancellation and progress capturing support \n\n## License\n\nThe MIT License Copyright (c) 2020 Dmitriy Mozgovoy robotshara@gmail.com\n\nPermission 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:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\nINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\nPURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdigitalbrainjs%2Fcp-axios","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdigitalbrainjs%2Fcp-axios","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdigitalbrainjs%2Fcp-axios/lists"}