UNPKG

advanced-retry

Version:
67 lines (66 loc) 3.04 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.delayErrorResolver = void 0; const base_1 = require("../filter/base"); function sleep(ms, abortSignal) { return __awaiter(this, void 0, void 0, function* () { return new Promise(resolve => { if (ms < 0) ms = 0; const timeout = setTimeout(() => resolve(undefined), ms); if (abortSignal) { abortSignal.addEventListener('abort', () => { clearTimeout(timeout); resolve(undefined); }); } }); }); } /** * @description Delayed retry error resolver is used to handle the error and retry the operation after a delay * @param configuration - Delayed retry policy * @param canHandleError - Can handle error function * @returns Error resolver */ const delayErrorResolver = ({ configuration, canHandleError = undefined, }) => (_a) => __awaiter(void 0, [_a], void 0, function* ({ error, attempt, retryContext: context, abortSignal }) { var _b, _c, _d, _e; if (!canHandleError || (0, base_1.toErrorFilter)(canHandleError).canHandleError(error, attempt, context)) { const delay = configuration.customDelay != undefined ? configuration.customDelay({ attempt, context, error, configuration, }) : configuration.maxDelayMs ? Math.min(((_b = configuration.initialDelayMs) !== null && _b !== void 0 ? _b : 0) * (attempt + 1) * ((_c = configuration.backoffMultiplier) !== null && _c !== void 0 ? _c : 1), configuration.maxDelayMs) : ((_d = configuration.initialDelayMs) !== null && _d !== void 0 ? _d : 0) * (attempt + 1) * ((_e = configuration.backoffMultiplier) !== null && _e !== void 0 ? _e : 1); yield sleep(delay, abortSignal); return { remainingAttempts: configuration.maxRetries - attempt, unrecoverable: false, context: { data: undefined }, }; } return { remainingAttempts: -1, unrecoverable: false, context: { data: undefined }, }; }); exports.delayErrorResolver = delayErrorResolver;