forked from thaerlabs/axios-cancel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (52 loc) · 1.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { CancelToken } from 'axios';
import RequestManager from './lib/RequestManager';
import extend from './lib/extend';
export default function patchAxios(axios, options) {
const defaults = {
debug: false,
};
const settings = extend({}, defaults, options);
const requestManager = new RequestManager(settings);
/**
* Global request interceptor
* Any request with a `requestId` key in the config will be:
* - cancelled if already sent
* - added to the `pendingRequests` hash if not, with a cancel function
*/
axios.interceptors.request.use((config) => {
const { requestId } = config;
if (requestId) {
const source = CancelToken.source();
config.cancelToken = source.token;
requestManager.addRequest(requestId, source.cancel);
}
return config;
});
/**
* Global response interceptor
* Check for the `requestId` and remove it from the `pendingRequests` hash
*/
axios.interceptors.response.use((response) => {
const { requestId } = response.config;
if (requestId) {
requestManager.removeRequest(requestId);
}
return response;
});
/**
* Global axios method to cancel a single request by ID
* @param requestId: string
* @param reason
*/
axios.cancel = (requestId, reason) => {
if (requestId) {
requestManager.cancelRequest(requestId, reason);
}
};
/**
* Global axios method to cancel all requests
*/
axios.cancelAll = (reason) => {
requestManager.cancelAllRequests(reason)
};
}