-
Notifications
You must be signed in to change notification settings - Fork 61
/
index.ts
278 lines (245 loc) · 7.47 KB
/
index.ts
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import axios, {
AxiosError,
AxiosInstance,
AxiosRequestConfig,
AxiosResponse,
} from 'axios';
/**
* Configuration for the Axios `request` method.
*/
export interface RetryConfig {
/**
* The number of times to retry the request. Defaults to 3.
*/
retry?: number;
/**
* The number of retries already attempted.
*/
currentRetryAttempt?: number;
/**
* The amount of time to initially delay the retry. Defaults to 100.
*/
retryDelay?: number;
/**
* The instance of the axios object to which the interceptor is attached.
*/
instance?: AxiosInstance;
/**
* The HTTP Methods that will be automatically retried.
* Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE']
*/
httpMethodsToRetry?: string[];
/**
* The HTTP response status codes that will automatically be retried.
* Defaults to: [[100, 199], [429, 429], [500, 599]]
*/
statusCodesToRetry?: number[][];
/**
* Function to invoke when a retry attempt is made.
*/
onRetryAttempt?: (err: AxiosError) => void;
/**
* Function to invoke which determines if you should retry
*/
shouldRetry?: (err: AxiosError) => boolean;
/**
* When there is no response, the number of retries to attempt. Defaults to 2.
*/
noResponseRetries?: number;
/**
* Backoff Type; 'linear', 'static' or 'exponential'.
*/
backoffType?: 'linear' | 'static' | 'exponential';
}
export type RaxConfig = {
raxConfig: RetryConfig;
} & AxiosRequestConfig;
/**
* Attach the interceptor to the Axios instance.
* @param instance The optional Axios instance on which to attach the
* interceptor.
* @returns The id of the interceptor attached to the axios instance.
*/
export function attach(instance?: AxiosInstance) {
instance = instance || axios;
return instance.interceptors.response.use(onFulfilled, onError);
}
/**
* Eject the Axios interceptor that is providing retry capabilities.
* @param interceptorId The interceptorId provided in the config.
* @param instance The axios instance using this interceptor.
*/
export function detach(interceptorId: number, instance?: AxiosInstance) {
instance = instance || axios;
instance.interceptors.response.eject(interceptorId);
}
function onFulfilled(res: AxiosResponse) {
return res;
}
/**
* Some versions of axios are converting arrays into objects during retries.
* This will attempt to convert an object with the following structure into
* an array, where the keys correspond to the indices:
* {
* 0: {
* // some property
* },
* 1: {
* // another
* }
* }
* @param obj The object that (may) have integers that correspond to an index
* @returns An array with the pucked values
*/
function normalizeArray<T>(obj?: T[]): T[] | undefined {
const arr: T[] = [];
if (!obj) {
return undefined;
}
if (Array.isArray(obj)) {
return obj;
}
if (typeof obj === 'object') {
Object.keys(obj).forEach(key => {
if (typeof key === 'number') {
arr[key] = obj[key];
}
});
}
return arr;
}
function onError(err: AxiosError) {
if (axios.isCancel(err)) {
return Promise.reject(err);
}
const config = getConfig(err) || {};
config.currentRetryAttempt = config.currentRetryAttempt || 0;
config.retry =
config.retry === undefined || config.retry === null ? 3 : config.retry;
config.retryDelay = config.retryDelay || 100;
config.instance = config.instance || axios;
config.backoffType = config.backoffType || 'exponential';
config.httpMethodsToRetry = normalizeArray(config.httpMethodsToRetry) || [
'GET',
'HEAD',
'PUT',
'OPTIONS',
'DELETE',
];
config.noResponseRetries =
config.noResponseRetries === undefined || config.noResponseRetries === null
? 2
: config.noResponseRetries;
// If this wasn't in the list of status codes where we want
// to automatically retry, return.
const retryRanges = [
// https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
// 1xx - Retry (Informational, request still processing)
// 2xx - Do not retry (Success)
// 3xx - Do not retry (Redirect)
// 4xx - Do not retry (Client errors)
// 429 - Retry ("Too Many Requests")
// 5xx - Retry (Server errors)
[100, 199],
[429, 429],
[500, 599],
];
config.statusCodesToRetry =
normalizeArray(config.statusCodesToRetry) || retryRanges;
// Put the config back into the err
err.config = err.config || {}; // allow for wider range of errors
(err.config as RaxConfig).raxConfig = {...config};
// Determine if we should retry the request
const shouldRetryFn = config.shouldRetry || shouldRetryRequest;
if (!shouldRetryFn(err)) {
return Promise.reject(err);
}
// Create a promise that invokes the retry after the backOffDelay
const onBackoffPromise = new Promise(resolve => {
// Calculate time to wait with exponential backoff.
// Formula: (2^c - 1 / 2) * 1000
let delay: number;
if (config.backoffType === 'linear') {
delay = config.currentRetryAttempt! * 1000;
} else if (config.backoffType === 'static') {
delay = config.retryDelay!;
} else {
delay = ((Math.pow(2, config.currentRetryAttempt!) - 1) / 2) * 1000;
}
// We're going to retry! Incremenent the counter.
(err.config as RaxConfig).raxConfig!.currentRetryAttempt! += 1;
setTimeout(resolve, delay);
});
// Notify the user if they added an `onRetryAttempt` handler
const onRetryAttemptPromise = config.onRetryAttempt
? Promise.resolve(config.onRetryAttempt(err))
: Promise.resolve();
// Return the promise in which recalls axios to retry the request
return Promise.resolve()
.then(() => onBackoffPromise)
.then(() => onRetryAttemptPromise)
.then(() => config.instance!.request(err.config));
}
/**
* Determine based on config if we should retry the request.
* @param err The AxiosError passed to the interceptor.
*/
function shouldRetryRequest(err: AxiosError) {
const config = (err.config as RaxConfig).raxConfig;
// If there's no config, or retries are disabled, return.
if (!config || config.retry === 0) {
return false;
}
// Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc)
if (
!err.response &&
(config.currentRetryAttempt || 0) >= config.noResponseRetries!
) {
return false;
}
// Only retry with configured HttpMethods.
if (
!err.config.method ||
config.httpMethodsToRetry!.indexOf(err.config.method.toUpperCase()) < 0
) {
return false;
}
// If this wasn't in the list of status codes where we want
// to automatically retry, return.
if (err.response && err.response.status) {
let isInRange = false;
for (const [min, max] of config.statusCodesToRetry!) {
const status = err.response.status;
if (status >= min && status <= max) {
isInRange = true;
break;
}
}
if (!isInRange) {
return false;
}
}
// If we are out of retry attempts, return
config.currentRetryAttempt = config.currentRetryAttempt || 0;
if (config.currentRetryAttempt >= config.retry!) {
return false;
}
return true;
}
/**
* Acquire the raxConfig object from an AxiosError if available.
* @param err The Axios error with a config object.
*/
export function getConfig(err: AxiosError) {
if (err && err.config) {
return (err.config as RaxConfig).raxConfig;
}
return;
}
// Include this so `config.raxConfig` works easily.
// See https://github.com/JustinBeckwith/retry-axios/issues/64.
declare module 'axios' {
export interface AxiosRequestConfig {
raxConfig?: RetryConfig;
}
}