UNPKG

@trendmoon/api-client

Version:
68 lines 2.55 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DEFAULT_RETRY_OPTIONS = void 0; exports.withRetry = withRetry; exports.createRetryWrapper = createRetryWrapper; const debug_js_1 = require("./debug.js"); const errors_js_1 = require("./errors.js"); /** * Default retry configuration */ exports.DEFAULT_RETRY_OPTIONS = { maxAttempts: 3, baseDelay: 1000, maxDelay: 10000, exponentialBackoff: true, shouldRetry: (error) => { // Retry on network errors and rate limit errors return error instanceof errors_js_1.TrendmoonNetworkError || error instanceof errors_js_1.TrendmoonRateLimitError; } }; /** * Retry utility function with exponential backoff */ async function withRetry(operation, options = {}) { var _a; const config = Object.assign(Object.assign({}, exports.DEFAULT_RETRY_OPTIONS), options); let lastError; for (let attempt = 1; attempt <= config.maxAttempts; attempt++) { try { const result = await operation(); if (attempt > 1) { debug_js_1.debugLog.info(`Operation succeeded on attempt ${attempt}`); } return result; } catch (error) { lastError = error; // Don't retry if this is the last attempt or if shouldRetry returns false if (attempt === config.maxAttempts || !((_a = config.shouldRetry) === null || _a === void 0 ? void 0 : _a.call(config, lastError))) { break; } // Calculate delay for next attempt let delay = config.baseDelay; if (config.exponentialBackoff) { delay = Math.min(config.baseDelay * Math.pow(2, attempt - 1), config.maxDelay); } // Add jitter to prevent thundering herd delay += Math.random() * 1000; debug_js_1.debugLog.warn(`Operation failed on attempt ${attempt}/${config.maxAttempts}. ` + `Retrying in ${Math.round(delay)}ms. Error:`, lastError.message); // Wait before next attempt await new Promise(resolve => setTimeout(resolve, delay)); } } // All attempts failed debug_js_1.debugLog.error(`Operation failed after ${config.maxAttempts} attempts`); throw lastError; } /** * Create a retry wrapper for a function */ function createRetryWrapper(fn, options = {}) { return ((...args) => { return withRetry(() => fn(...args), options); }); } //# sourceMappingURL=retry.js.map