UNPKG

@oxog/delay

Version:

A comprehensive, zero-dependency delay/timeout utility library with advanced timing features

84 lines 3.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.retryDelay = retryDelay; exports.createRetryWithDefaults = createRetryWithDefaults; exports.retryWithExponentialBackoff = retryWithExponentialBackoff; exports.retryWithLinearBackoff = retryWithLinearBackoff; const index_js_1 = require("../types/index.js"); const validation_js_1 = require("../utils/validation.js"); const random_js_1 = require("../utils/random.js"); const delay_js_1 = require("./delay.js"); async function retryDelay(fn, options) { (0, validation_js_1.validateFunction)(fn, 'retry function'); (0, validation_js_1.validateRetryOptions)(options); const { attempts, delay, backoff = 'linear', backoffFactor = 2, maxDelay = Infinity, onRetry, retryIf, } = options; let lastError; for (let attempt = 1; attempt <= attempts; attempt++) { try { const result = await fn(); return result; } catch (error) { lastError = error instanceof Error ? error : new Error(String(error)); // Check if we should retry this error if (retryIf && !retryIf(lastError)) { throw lastError; } // If this was the last attempt, throw the error if (attempt === attempts) { throw new index_js_1.DelayError(`Retry exhausted after ${attempts} attempts: ${lastError.message}`, index_js_1.DelayErrorCode.RETRY_EXHAUSTED, { attempts, lastError: lastError.message, originalError: lastError, }); } // Call the retry callback if provided if (onRetry) { try { onRetry(lastError, attempt); } catch (callbackError) { // Don't let callback errors break the retry logic console.error('Error in retry callback:', callbackError); } } // Calculate delay for next attempt let delayMs; if (typeof delay === 'function') { delayMs = delay(attempt); } else { delayMs = (0, random_js_1.calculateBackoffDelay)(delay, attempt, backoff, backoffFactor, maxDelay); } // Wait before next attempt if (delayMs > 0) { await (0, delay_js_1.createBasicDelay)(delayMs); } } } // This should never be reached, but TypeScript needs it throw lastError; } function createRetryWithDefaults(defaultOptions) { return function (fn, options) { const mergedOptions = { ...defaultOptions, ...options }; return retryDelay(fn, mergedOptions); }; } function retryWithExponentialBackoff(fn, attempts = 3, baseDelay = 1000, maxDelay = 30000) { return retryDelay(fn, { attempts, delay: baseDelay, backoff: 'exponential', maxDelay, }); } function retryWithLinearBackoff(fn, attempts = 3, baseDelay = 1000, maxDelay = 10000) { return retryDelay(fn, { attempts, delay: baseDelay, backoff: 'linear', maxDelay, }); } //# sourceMappingURL=retry.js.map