UNPKG

@kontent-ai/core-sdk

Version:

Core package with shared / common functionality for Kontent.ai SDKs

106 lines 3.52 kB
import { getRetryAfterHeaderValue } from "./header.utils.js"; const defaultMaxRetries = 3; const getDefaultDelayBetweenRetriesMs = (error) => { if (error.reason === "notFound" || error.reason === "invalidResponse") { return getRetryFromHeaderMs({ error }); } return 0; }; const defaultCanRetryError = (error) => { if (error.reason === "invalidResponse") { if (error.kontentErrorResponse) { // The request is clearly invalid as we got an error response from the API return false; } return error.status >= 500 || error.status === 429; } return true; }; export async function runWithRetryAsync(data) { const { success, response, error } = await data.funcAsync(); if (success) { return { success: true, response, }; } const newRetryAttempt = data.retryAttempt + 1; const retryResult = getRetryResult({ error, retryAttempt: data.retryAttempt, options: data.retryStrategyOptions, }); if (!retryResult.canRetry) { return { success: false, error: { ...error, retryAttempt: data.retryAttempt, retryStrategyOptions: data.retryStrategyOptions, }, }; } logRetryAttempt(data.retryStrategyOptions, newRetryAttempt, data.url); await waitAsync(retryResult.retryInMs); return await runWithRetryAsync({ funcAsync: data.funcAsync, retryStrategyOptions: data.retryStrategyOptions, retryAttempt: newRetryAttempt, url: data.url, requestHeaders: data.requestHeaders, method: data.method, }); } export function toRequiredRetryStrategyOptions(options) { const maxRetries = options?.maxRetries ?? defaultMaxRetries; return { maxRetries: maxRetries, canRetryError: options?.canRetryError ?? defaultCanRetryError, getDelayBetweenRetriesMs: options?.getDelayBetweenRetriesMs ?? getDefaultDelayBetweenRetriesMs, logRetryAttempt: options?.logRetryAttempt === false ? false : (attempt, url) => { if (options?.logRetryAttempt) { options.logRetryAttempt(attempt, url); } else { console.warn(getDefaultRetryAttemptLogMessage(attempt, maxRetries, url)); } }, }; } export function getDefaultRetryAttemptLogMessage(retryAttempt, maxRetries, url) { return `Retry attempt '${retryAttempt}' from a maximum of '${maxRetries}' retries. Requested url: '${url}'`; } function logRetryAttempt(opts, retryAttempt, url) { if (opts.logRetryAttempt) { opts.logRetryAttempt(retryAttempt, url); } } function waitAsync(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } function getRetryResult({ retryAttempt, error, options, }) { if (retryAttempt >= options.maxRetries) { return { canRetry: false, }; } if (!options.canRetryError(error)) { return { canRetry: false, }; } return { canRetry: true, retryInMs: options.getDelayBetweenRetriesMs(error), }; } function getRetryFromHeaderMs({ error }) { const retryAfterHeaderValue = getRetryAfterHeaderValue(error.responseHeaders); if (retryAfterHeaderValue) { return retryAfterHeaderValue * 1000; } return 0; } //# sourceMappingURL=retry.utils.js.map