UNPKG

@moonwell-fi/moonwell-sdk

Version:

TypeScript Interface for Moonwell

63 lines 2.37 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.isRetriableError = isRetriableError; exports.attachRetryInterceptor = attachRetryInterceptor; exports.retry = retry; const axios_1 = __importDefault(require("axios")); const DEFAULT_MAX_ATTEMPTS = 3; const DEFAULT_INITIAL_DELAY_MS = 250; const DEFAULT_MAX_DELAY_MS = 5_000; async function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } function backoffDelay(attemptIndex, initialDelay, maxDelay) { return Math.min(initialDelay * 2 ** attemptIndex, maxDelay); } function isRetriableError(error) { if (!axios_1.default.isAxiosError(error)) return false; if (!error.response) return true; return error.response.status >= 500; } function attachRetryInterceptor(instance, options = {}) { const { maxAttempts = DEFAULT_MAX_ATTEMPTS, initialDelay = DEFAULT_INITIAL_DELAY_MS, maxDelay = DEFAULT_MAX_DELAY_MS, } = options; const attemptsByConfig = new WeakMap(); instance.interceptors.response.use((response) => response, async (error) => { const config = error.config; if (!config) throw error; if (!isRetriableError(error)) throw error; const previousAttempts = attemptsByConfig.get(config) ?? 0; if (previousAttempts >= maxAttempts - 1) throw error; attemptsByConfig.set(config, previousAttempts + 1); await sleep(backoffDelay(previousAttempts, initialDelay, maxDelay)); return instance.request(config); }); } async function retry(fn, options = {}) { const { maxAttempts = DEFAULT_MAX_ATTEMPTS, initialDelay = DEFAULT_INITIAL_DELAY_MS, maxDelay = DEFAULT_MAX_DELAY_MS, } = options; let attempt = 0; let lastError; while (attempt < maxAttempts) { try { return await fn(); } catch (error) { lastError = error; attempt++; if (!isRetriableError(error)) throw error; if (attempt >= maxAttempts) break; await sleep(backoffDelay(attempt - 1, initialDelay, maxDelay)); } } throw lastError; } //# sourceMappingURL=retry.js.map