-
Notifications
You must be signed in to change notification settings - Fork 1
/
error-retry.js
44 lines (40 loc) 路 1.28 KB
/
error-retry.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
// @ts-check
import sleep from 'lib/sleep';
import addHooks from './helpers/add-hooks';
/**
* A decorator to retry action until condition met or reach maxRetries.
*
* @template T
* @typedef {import('./types').ErrorHookMethod<T>} ErrorHookMethod
* @param {object} options - Config.
* @param {ErrorHookMethod<boolean>} [options.condition] - Condition to retry.
* @param {number} [options.maxRetries] - Max times of retry.
* @param {number} [options.delay] - Time to wait between retry.
* @returns {object|Array} The data returned from the original action call.
*/
const errorRetry = (options = {}) =>
addHooks({
/**
* @type {import('./types').ErrorHook}
*/
errorHook: async (e, param, meta, context, action) => {
const { condition = () => true, maxRetries = 3, delay } = options;
const { retries = 0 } = meta;
if (retries < maxRetries && condition(e, param, meta, context, action)) {
if (delay) await sleep(delay);
const updatedMeta = {
...meta,
retries: retries + 1,
maxRetries,
};
const result = await errorRetry(options)(action)(
param,
updatedMeta,
context,
);
return result;
}
throw e;
},
});
export default errorRetry;