gqty
Version:
The No-GraphQL Client for TypeScript
37 lines (35 loc) • 1.27 kB
JavaScript
const defaultMaxRetries = 3;
const defaultRetryDelay = (attemptIndex) => Math.min(1e3 * 2 ** attemptIndex, 3e4);
function doRetry(options, state) {
var _a, _b;
if (options === false) {
throw new Error(`Retries are disabled.`);
}
const maxRetries = typeof options === "number" ? options : (_a = typeof options === "object" ? options.maxRetries : void 0) != null ? _a : defaultMaxRetries;
if (maxRetries < 1) {
throw new Error(`Maximum retries must be >= 1`);
}
const retryDelay = (_b = typeof options === "object" ? options.retryDelay : void 0) != null ? _b : defaultRetryDelay;
const { attemptIndex = 0, onRetry, onLastTry } = state;
if (onLastTry && attemptIndex === maxRetries - 1) {
setTimeout(
() => {
onLastTry(attemptIndex).catch(console.error);
},
typeof retryDelay === "function" ? retryDelay(attemptIndex) : retryDelay
);
} else if (attemptIndex < maxRetries) {
setTimeout(
() => {
onRetry(attemptIndex).catch(() => {
doRetry(
options,
Object.assign({}, state, { attemptIndex: attemptIndex + 1 })
);
});
},
typeof retryDelay === "function" ? retryDelay(attemptIndex) : retryDelay
);
}
}
export { doRetry };