![codecov](https://codecov.io/gh/yveskaufmann/retry/branch/main/graph/badge.svg?token=QXZVS68R36)
@yveskaufmann/retry - retry-utility
Utility for retrying promise based operation when a certain response or error is returned.
- Provides an imperative API for non class methods
- Class decorators to mark async methods to be retryable
- Supports various backoff strategies: fixed, linear, exponential
Installation
npm install @yveskaufmann/retry
Usage
The example below demonstrates how to annotate
methods to mark them as retriable. When retryWhen
return true
the method is retried until it reaches the
maxRetries
limit.
When the retry limit is reached, the last return value is returned
or the last thrown error is thrown.
NOTE: The Retryable annotation only works with methods that returning promises like async methods.
class Service {
@Retryable({
retryWhen: (result, err) => err != null,
delay: Retry.Delays.linear(50),
maxRetries: 3,
})
async retryOnAnyError() {
}
@Retryable({
retryWhen: (result, err) => err == null && result == false,
delay: Retry.Delays.linear(50),
maxRetries: 3,
})
async retryWhenFalseIsReturned() {
return Math.random() < 0.6;
}
}
This utility can also be used with async functions:
const response = await Retry.do({
operation: () => client.get(...),
retryWhen: (result, err) => HttpError.isTooManyRequest(err)
maxRetries: 3,
delay: Retry.Delays.constant(50),
});
API Reference
RetryOptions
interface RetryOptions<T> {
maxRetries?: number;
throwMaxAttemptError?: boolean;
nameOfOperation?: string;
retryWhen: (result: T, err: Error) => boolean;
delay?: (attempts: number, error?: Error) => number;
}
Retry
This is the retry class that provides access to built-in delay(backoff) strategies and built-in retry conditions.
class Retry {
public static readonly Delays = new Delays();
public static readonly Conditions = new Conditions();
public static async do<T>(options: RetryOptions<T>): Promise<T>;
}
RetryDelays
class Delays {
public none();
public constant(delayInMs: number);
public linear(delayInMs: number);
public potential(delayInMs: number);
}
A custom delay strategy can be created by implementing
a function that fulfill the interface below:
() => (attempts: number, error?: Error) => number
RetryConditions
class Conditions {
public onAnyError();
public always();
public onNullResult();
}
A custom retry-condition can be created by implementing
a function that fulfills the following interface:
retryWhen: (result: T, err: Error) => boolean;
Retryable
function Retryable(options: RetryOptions<unknown>): MethodDecorator
MaxRetryAttemptsReached
class MaxRetryAttemptsReached extends Error {
public readonly cause: Error;
constructor(message: string, cause?: Error);
}