@naturalcycles/js-lib
Version:
Standard library for universal (browser + Node.js) javascript
84 lines (83 loc) • 2.17 kB
TypeScript
import type { ErrorData } from '../error/error.model.js';
import type { CommonLogger } from '../log/commonLogger.js';
import type { AnyFunction } from '../types.js';
export interface PRetryOptions {
/**
* If set - will be included in the error message.
* Can be used to identify the place in the code that failed.
*/
name?: string;
/**
* Timeout for each Try, in milliseconds.
*
* Defaults to no timeout.
*/
timeout?: number;
/**
* How many attempts to try.
* First attempt is not a retry, but "initial try". It still counts.
* maxAttempts of 4 will be 1 try and 3 retries.
*
* @default 4
*/
maxAttempts?: number;
/**
* @default 1000 ms
*/
delay?: number;
/**
* @default 2
*/
delayMultiplier?: number;
/**
* Called on every retry (since 2nd attempt, cause 1st attempt is not a retry).
*
* True - keep retrying.
* False - stop retrying and return immediately.
*
* @default () => true
*/
predicate?: (err: Error, attempt: number, maxAttempts: number) => boolean;
/**
* Log the first attempt (which is not a "retry" yet).
*
* @default false
*/
logFirstAttempt?: boolean;
/**
* Log retries - attempts that go after the first one.
*
* @default true
*/
logRetries?: boolean;
/**
* @default false
*/
logSuccess?: boolean;
/**
* @default true
*/
logFailures?: boolean;
/**
* @default false
*/
logAll?: boolean;
/**
* @default false
*/
logNone?: boolean;
/**
* Default to `console`
*/
logger?: CommonLogger;
/**
* Will be merged with `err.data` object.
*/
errorData?: ErrorData;
}
/**
* Returns a Function (!), enhanced with retry capabilities.
* Implements "Exponential back-off strategy" by multiplying the delay by `delayMultiplier` with each try.
*/
export declare function pRetryFn<T extends AnyFunction>(fn: T, opt?: PRetryOptions): T;
export declare function pRetry<T>(fn: (attempt: number) => Promise<T>, opt?: PRetryOptions): Promise<T>;