UNPKG

contentful-management

Version:
50 lines (47 loc) 2.18 kB
import { sleep } from './utils.js'; /* eslint-disable @typescript-eslint/no-explicit-any */ const DEFAULT_MAX_RETRIES = 30; const DEFAULT_INITIAL_DELAY_MS = 1000; const DEFAULT_RETRY_INTERVAL_MS = 2000; class AsyncActionProcessingError extends Error { constructor(message, action) { super(message); this.action = action; this.name = this.constructor.name; } } class AsyncActionFailedError extends AsyncActionProcessingError { } /** * @description Waits for an Action to be completed and to be in one of the final states (failed or succeeded) * @param {Function} actionFunction - GET function that will be called every interval to fetch an Action status * @throws {ActionFailedError} throws an error if `throwOnFailedExecution = true` with the Action that failed. * @throws {AsyncActionProcessingError} throws an error with a Action when processing takes too long. */ async function pollAsyncActionStatus(actionFunction, options) { let retryCount = 0; let done = false; let action; const maxRetries = options?.retryCount ?? DEFAULT_MAX_RETRIES; const retryIntervalMs = options?.retryIntervalMs ?? DEFAULT_RETRY_INTERVAL_MS; const initialDelayMs = options?.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS; const throwOnFailedExecution = options?.throwOnFailedExecution ?? true; // Initial delay for short-running Actions await sleep(initialDelayMs); while (retryCount < maxRetries && !done) { action = await actionFunction(); // Terminal states if (action && ['succeeded', 'failed'].includes(action.sys.status)) { done = true; if (action.sys.status === 'failed' && throwOnFailedExecution) { throw new AsyncActionFailedError(`${action.sys.type} failed to execute.`, action); } return action; } await sleep(retryIntervalMs); retryCount += 1; } throw new AsyncActionProcessingError(`${action?.sys.type} didn't finish processing within the expected timeframe.`, action); } export { AsyncActionFailedError, AsyncActionProcessingError, pollAsyncActionStatus }; //# sourceMappingURL=action.js.map