Skip to content

Commit c14b4aa

Browse files
Initial commit
0 parents  commit c14b4aa

14 files changed

+8260
-0
lines changed

Diff for: .eslintrc.js

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
module.exports = {
2+
"env": {
3+
"browser": true,
4+
"commonjs": true,
5+
"es2021": true,
6+
"node": true
7+
},
8+
"extends": "eslint:recommended",
9+
"parserOptions": {
10+
"ecmaVersion": 12
11+
},
12+
"rules": {
13+
}
14+
};

Diff for: .gitignore

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
/coverage/
2+
/.nyc_output/
3+
/dist/
4+
/node_modules/
5+
/trash/
6+
/.idea/

Diff for: .npmignore

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
*
2+
!dist/**
3+
!lib/**

Diff for: .travis.yml

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
sudo: false
2+
language: node_js
3+
node_js:
4+
- "10"
5+
env:
6+
- NODE_ENV=TEST
7+
script:
8+
- npm run test:coverage
9+
after_success: npm run coveralls

Diff for: CHANGELOG.md

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Change Log
2+
All notable changes to this project will be documented in this file.
3+
4+
The format is based on [Keep a Changelog](http://keepachangelog.com/)
5+
and this project adheres to [Semantic Versioning](http://semver.org/).
6+
7+
For changes before version 0.1.1, please see the commit history

Diff for: LICENSE.txt

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
2+
The MIT License (MIT)
3+
4+
Copyright (c) 2020 Mozgovoy Dmitriy <http://www.github.com/DigitalBrainJS> and Contributors
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the 'Software'), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is furnished
11+
to do so, subject to the following conditions:
12+
13+
The above copyright notice and this permission notice shall be included in all
14+
copies or substantial portions of the Software.
15+
16+
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18+
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19+
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
20+
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Diff for: README.md

+178
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
![Travis (.com)](https://img.shields.io/travis/com/DigitalBrainJS/cp-axios)
2+
[![Coverage Status](https://coveralls.io/repos/github/DigitalBrainJS/cp-axios/badge.svg?branch=master)](https://coveralls.io/github/DigitalBrainJS/cp-axios?branch=master)
3+
![npm](https://img.shields.io/npm/dm/cp-axios)
4+
![npm bundle size](https://img.shields.io/bundlephobia/minzip/cp-axios)
5+
![David](https://img.shields.io/david/DigitalBrainJS/cp-axios)
6+
7+
##Table of contents
8+
- [SYNOPSIS](#synopsis-sparkles)
9+
- [Installation](#installation-hammer)
10+
- [CDN bundle](#cdn-bundle)
11+
- [Usage examples](#usage-examples)
12+
- [Request aborting using CPromise cancelation API](#request-aborting-using-cpromise-cancelation-api)
13+
- [Request aborting using AbortController signal](#request-aborting-using-abortcontroller-signal)
14+
- [Request aborting using Axios cancelToken](#request-aborting-using-axios-canceltoken)
15+
- [Using generators as async functions](#using-generators-as-async-functions)
16+
- [Abortable concurrent requests](#abortable-concurrent-requests)
17+
- [API Reference](#api-reference)
18+
- [License](#license)
19+
20+
21+
## SYNOPSIS :sparkles:
22+
23+
**cpAxios** is a simple [axios](https://www.npmjs.com/package/axios) wrapper that provides an advanced cancellation api.
24+
25+
This library supports three types of the cancelation API that could be used *simultaneously*:
26+
- Axios [cancelableToken](https://github.com/axios/axios#cancellation)
27+
- [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) signal
28+
- [CPromise](https://www.npmjs.com/package/c-promise2) promise cancelation API
29+
30+
## Installation :hammer:
31+
32+
```bash
33+
$ npm install cp-axios
34+
```
35+
36+
```bash
37+
$ yarn add cp-axios
38+
```
39+
40+
### CDN bundle
41+
42+
- [production UMD bundle](https://unpkg.com/cp-axios) (or [minified](https://unpkg.com/cp-axios/dist/cp-axios.umd.min.js) ~31KB)
43+
44+
module global export- `cpAxios`
45+
46+
## Usage examples
47+
48+
#### Live Example
49+
50+
[Live browser example](https://codesandbox.io/s/mutable-breeze-wdyp)
51+
52+
#### Request aborting using CPromise cancelation API:
53+
````javascript
54+
const cpAxios= require('cp-axios');
55+
56+
const chain = cpAxios(url)
57+
.timeout(5000)
58+
.then(request => {
59+
console.log(`Done: ${JSON.stringify(request.json())}`)
60+
}, err => {
61+
console.warn(`Request failed: ${err}`)
62+
});
63+
64+
setTimeout(() => {
65+
chain.cancel();
66+
}, 500);
67+
````
68+
69+
#### Request aborting using AbortController signal:
70+
````javascript
71+
const cpAxios= require('cp-axios');
72+
const CPromise= require('c-promise2');
73+
74+
// you could to use any other AbortController implementation, but CPromise already provides it
75+
const abortController = new CPromise.AbortController();
76+
const {signal} = abortController;
77+
78+
const chain = cpAxios(url, {signal})
79+
.timeout(5000)
80+
.then(request => {
81+
console.log(`Done: ${JSON.stringify(request.json())}`)
82+
}, err => {
83+
console.warn(`Request failed: ${err}`)
84+
});
85+
86+
setTimeout(() => {
87+
chain.cancel();
88+
}, 500);
89+
````
90+
91+
#### Request aborting using Axios cancelToken:
92+
````javascript
93+
const cpAxios= require('cp-axios');
94+
const CPromise= require('c-promise2');
95+
96+
const source = cpAxios.CancelToken.source();
97+
98+
const chain = cpAxios(url, {cancelToken: source.token})
99+
.timeout(5000)
100+
.then(request => {
101+
console.log(`Done: ${JSON.stringify(request.json())}`)
102+
}, err => {
103+
console.warn(`Request failed: ${err}`)
104+
});
105+
106+
setTimeout(() => {
107+
source.cancel();
108+
}, 500);
109+
````
110+
111+
#### Using generators as async functions:
112+
113+
````javascript
114+
const cpAxios= require('cp-axios');
115+
const CPromise= require('c-promise2');
116+
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
117+
118+
const chain= CPromise.from(function*(){
119+
try{
120+
const response= yield cpAxios(url).timeout(5000);
121+
console.log(`Done: `, response.data)
122+
}catch(err){
123+
console.log(`Error: `, err)
124+
}
125+
});
126+
127+
setTimeout(()=> chain.cancel(), 1000); // abort the request after 1000ms
128+
````
129+
130+
#### Abortable concurrent requests
131+
132+
````javascript
133+
const cpAxios= require('cp-axios');
134+
const CPromise = require('c-promise2');
135+
136+
// same as cpAxios.all([...])
137+
const chain= CPromise.all([
138+
cpFetch("https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=3s"),
139+
cpFetch("https://run.mocky.io/v3/30a97b24-ed0e-46e8-9f78-8f954aead2f8?mocky-delay=5s")
140+
]).timeout(10000).then(responses=> {
141+
console.log(`Results :`, responses);
142+
}, function (err) {
143+
console.warn(`We got an error: ${err}`);
144+
});
145+
146+
// other request will aborted if one fails
147+
148+
// setTimeout(()=> chain.cancel(), 1000); // abort the request after 1000ms
149+
````
150+
151+
## API Reference
152+
153+
The package exports a wrapped version of the axios instance.
154+
See the axios [documentation](https://www.npmjs.com/package/axios#axios) to gen more information.
155+
156+
`cpAxios(url, {signal, ...nativeFetchOptions}): CPromise`
157+
158+
Options:
159+
160+
- `signal`- the AbortController signal
161+
162+
- `...nativeAxiosOptions`- other options supported by [axios](https://www.npmjs.com/package/axios) package
163+
164+
Learn more about [CPromise](https://www.npmjs.com/package/c-promise2) features
165+
## License
166+
167+
The MIT License Copyright (c) 2020 Dmitriy Mozgovoy [email protected]
168+
169+
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:
170+
171+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
172+
173+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
174+
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
175+
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
176+
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
177+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
178+

Diff for: lib/core/CPAxios.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
const axios = require('axios');
2+
const CPromise = require('c-promise2');
3+
const {Axios} = axios;
4+
5+
const isThenable = (thing) => thing && typeof thing.then === 'function';
6+
7+
class CPAxios extends Axios {
8+
request(config) {
9+
10+
if (typeof config === 'string') {
11+
config = arguments[1] || {};
12+
config.url = arguments[0];
13+
}
14+
15+
const {cancelToken, signal, ...axiosConfig} = config;
16+
17+
if (cancelToken) {
18+
if (!isThenable(cancelToken.promise)) {
19+
return CPromise.reject(new Error('Unknown cancelToken object type'))
20+
}
21+
22+
cancelToken.promise.then((reason) => {
23+
promise.cancel(reason.message);
24+
})
25+
}
26+
27+
const promise= new CPromise((resolve, reject, {onCancel}) => {
28+
super.request({
29+
...axiosConfig,
30+
cancelToken: new axios.CancelToken(function executor(cancel) {
31+
onCancel(cancel)
32+
}),
33+
}).then(resolve, reject);
34+
}, {signal});
35+
36+
return promise;
37+
}
38+
}
39+
40+
module.exports = CPAxios;

Diff for: lib/index.js

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
const axios= require('axios');
2+
const utils = require('axios/lib/utils');
3+
const bind = require('axios/lib/helpers/bind');
4+
const mergeConfig = require('axios/lib/core/mergeConfig');
5+
const defaults = require('axios/lib/defaults');
6+
const CPAxios = require('./core/CPAxios');
7+
const CPromise= require('c-promise2');
8+
9+
function createInstance(defaultConfig) {
10+
var context = new CPAxios(defaultConfig);
11+
var instance = bind(CPAxios.prototype.request, context);
12+
13+
utils.extend(instance, CPAxios.prototype, context);
14+
15+
utils.extend(instance, context);
16+
17+
return instance;
18+
}
19+
20+
// Create the default instance to be exported
21+
var _axios = createInstance(defaults);
22+
23+
// Expose Axios class to allow class inheritance
24+
_axios.Axios = CPAxios;
25+
26+
(()=>{
27+
const props= Object.getOwnPropertyNames(axios);
28+
props.forEach(prop=>{
29+
if(!Object.prototype.hasOwnProperty.call(_axios, prop)){
30+
_axios[prop]= axios[prop];
31+
}
32+
});
33+
})();
34+
35+
// Factory for creating new instances
36+
_axios.create = function create(instanceConfig) {
37+
return createInstance(mergeConfig(_axios.defaults, instanceConfig));
38+
};
39+
40+
// Expose Cancel & CancelToken
41+
/*_axios.Cancel = axios.Cancel;
42+
_axios.CancelToken = axios.CancelToken;
43+
_axios.isCancel = axios.isCancel;*/
44+
45+
// Expose all/spread
46+
_axios.all = function all(promises) {
47+
return CPromise.all(promises);
48+
};
49+
50+
//_axios.spread = require('axios/lib/helpers/spread');
51+
52+
module.exports = _axios;
53+
54+
// Allow use of default import syntax in TypeScript
55+
module.exports.default = _axios;
56+

0 commit comments

Comments
 (0)