@lumenlabs-dev/fast-async-retry
v0.1.1
Published
Retrying made simple, easy and async - TypeScript version
Readme
fast-async-retry
This is a TypeScript refactor of the async-retry library. Retrying made simple, easy, and async with full type safety.
Features
- Full TypeScript support with type definitions
- Automatic retrying with configurable options
- Bail functionality to abort retries
- Retry callbacks for logging/monitoring
- Randomized retry delays
- Built on top of the
retrypackage
Installation
npm install @lumenlabs-dev/fast-async-retry
# or
yarn add @lumenlabs-dev/fast-async-retryUsage
Basic Example
import retry from '@lumenlabs-dev/fast-async-retry';
import fetch from 'node-fetch';
const result = await retry(async (bail, attempt, operation) => {
// If anything throws, we retry
const res = await fetch('https://google.com');
if (res.status === 403) {
// Don't retry upon 403
bail(new Error('Unauthorized'));
return;
}
const data = await res.text();
return data.substr(0, 500);
}, {
retries: 5,
});With Type Parameters
import retry, { Options } from '@lumenlabs-dev/fast-async-retry';
// Define return type and error type
const result = await retry<string, Error>(
async (bail, attempt, operation) => {
console.log(`Attempt ${attempt}`);
if (Math.random() > 0.5) {
throw new Error('Random failure');
}
return 'Success!';
},
{
retries: 3,
onRetry: (error, attempt) => {
console.log(`Retry ${attempt}: ${error.message}`);
}
}
);API
retry<TRet, TErr>(fn, opts?)
Executes the given function with retry logic.
Parameters
fn: RetryFunction<TRet, TErr>- The function to retrybail: (e: TErr) => void- Call this to abort retryingattempt: number- The current attempt number (starts at 1)operation: Operation- The retry operation object for advanced control
opts?: Options<TErr>- Retry optionsretries?: number- Maximum number of retries (default: 10)factor?: number- Exponential backoff factor (default: 2)minTimeout?: number- Minimum timeout in ms (default: 1000)maxTimeout?: number- Maximum timeout in ms (default: Infinity)randomize?: boolean- Randomize timeouts (default: true)forever?: boolean- Retry forever (default: false)unref?: boolean- Unref timers (default: false)maxRetryTime?: number- Maximum total time in msonRetry?: (e: TErr, attempt: number) => any- Callback on retry
Returns
Promise<TRet> - Resolves with the return value of fn
Type Exports
import { Options, RetryFunction } from '@lumenlabs-dev/fast-async-retry';
type MyOptions = Options<Error>;
type MyRetryFn = RetryFunction<string, Error>;
// Example usage with operation parameter
const myRetryFn: MyRetryFn = async (bail, attempt, operation) => {
// operation provides access to advanced retry control
return "success";
};Building
# Install dependencies
npm install
# Build TypeScript
npm run build
# Run tests
npm test
# Watch mode
npm run build:watchProject Structure
fast-async-retry/
├── src/
│ ├── index.ts # Main implementation
│ └── types/ # Type declarations
│ ├── global.d.ts
│ └── then-sleep.d.ts
├── test/
│ └── index.test.ts # Comprehensive test suite
├── dist/ # Compiled output
│ ├── cjs/ # CommonJS build
│ └── esm/ # ES Module build
├── scripts/
│ └── post-build.js # Post-build utilities
├── tsconfig.json # Base TypeScript config
├── tsconfig.cjs.json # CommonJS build config
├── tsconfig.esm.json # ES Module build config
└── package.json # Package manifestMigration from JavaScript
The TypeScript version is fully compatible with the JavaScript version. Simply update your imports:
// Before (JavaScript)
const retry = require('async-retry');
// After (TypeScript/ES Modules)
import retry from '@lumenlabs-dev/fast-async-retry';
// Or CommonJS
const retry = require('@lumenlabs-dev/fast-async-retry').default;Notes
- The supplied function can be
asyncor not. In other words, it can be a function that returns aPromiseor a synchronous value. - The retry options are passed to the underlying
retrypackage. See its documentation for more details on how the retry timing algorithm works.
Credits
This is a TypeScript refactor of the original async-retry package.
Original Authors:
- Guillermo Rauch (@rauchg) - Vercel
- Leo Lamprecht (@notquiteleo) - Vercel
License
MIT
