@haandev/core
Version:
Core library for @haandev packages
61 lines (59 loc) • 2.39 kB
TypeScript
type Retrier<R> = (previousResult?: R, previousError?: Error, lastAttempt?: number) => Promise<R> | R;
type EnforcerOptions<RetrierResult, FixResult> = {
/**
* Optional function to determine if the operation should be cancelled. If
* this returns `true`, the process will stop immediately.
*/
isCancelled?: () => boolean;
/**
* The maximum number of retry attempts after the initial failure. Defaults to
* 3.
*/
maxRetries?: number;
/**
* Delay in milliseconds between consecutive retry attempts. Defaults to 1000
* ms.
*/
retryDelay?: number;
/** Timeout in milliseconds for each `retrier` attempt. Defaults to 10,000 ms. */
timeout?: number;
/**
* Optional function executed after a failed retrier attempt. Can be used to
* apply any changes before retrying.
*/
fix?: (resolved: RetrierResult) => Promise<FixResult> | FixResult;
/** Called if the `fix` function completes successfully. */
onFix?: (result: FixResult) => any;
/**
* Called after the first `retrier` attempt fails and retries are about to
* begin.
*/
onInvalid?: () => any;
/** Called at the beginning of the operation, before the first attempt. */
onStart?: () => any;
/**
* Called when the operation is cancelled either by `isCancelled` or an abort
* signal.
*/
onCancelled?: () => any;
/** Called when the operation times out. */
onTimeout?: () => any;
/** Called if the `fix` function throws an error. */
onFixError?: (error: unknown) => any;
/** Optional AbortSignal to cancel the operation externally. */
abortSignal?: AbortSignal;
};
/**
* Attempts to ensure that a given state is valid by checking a `retrier`
* condition and retrying a `fix` operation if needed.
*
* @param retrier - A function that checks whether the current state is valid.
* If it throws an error, the state is considered invalid. Errors are safely
* caught and treated as failure.
* @param options Configuration for how to validate and enforce the desired
* state.
* @returns A Promise that resolves once the state is either successfully
* enforced or considered irrecoverable.
*/
declare const enforcer: <R, F>(retrier: Retrier<R>, options: EnforcerOptions<R, F>) => Promise<R>;
export { type EnforcerOptions, type Retrier, enforcer };