UNPKG

@intlayer/config

Version:

Retrieve Intlayer configurations and manage environment variables for both server-side and client-side environments.

45 lines (43 loc) 1.26 kB
import { extractErrorMessage } from "./extractErrorMessage.mjs"; import { logger } from "../logger.mjs"; //#region src/utils/retryManager.ts const DEFAULT_MAX_RETRY = 3; const DEFAULT_DELAY = 0; /** * Wrap an async function `fn` so it’s retried on failure. * * @param fn The async function to wrap * @param options { maxRetry, delay } * @returns A new function with the same signature as `fn` */ const retryManager = (fn, { maxRetry = DEFAULT_MAX_RETRY, delay = DEFAULT_DELAY, onError, onMaxTryReached } = {}) => async (...args) => { let lastError; for (let attempt = 0; attempt <= maxRetry; attempt++) try { return await fn(...args); } catch (err) { lastError = err; const error = extractErrorMessage(err); if (attempt >= maxRetry) { if (onMaxTryReached) { onMaxTryReached?.({ error, attempt, maxRetry }); return null; } throw err; } if (onError) onError?.({ error, attempt, maxRetry }); else logger(error, { level: "error" }); if (delay > 0) await new Promise((res) => setTimeout(res, delay)); } throw lastError ?? /* @__PURE__ */ new Error("Unexpected: retry loop completed without result"); }; //#endregion export { retryManager }; //# sourceMappingURL=retryManager.mjs.map