An open API service indexing awesome lists of open source software.

https://github.com/blackglory/extra-retry

🌲 Yet another retry library, but functional style
https://github.com/blackglory/extra-retry

browser esm library nodejs npm-package typescript

Last synced: 2 months ago
JSON representation

🌲 Yet another retry library, but functional style

Awesome Lists containing this project

README

          

# extra-retry
Yet another retry library, but functional style.

## Install
```sh
npm install --save extra-retry
# or
yarn add extra-retry
```

## Usage
```ts
import { retryUntil, anyOf, maxRetries, delay } from 'extra-retry'
import ms from 'ms'

await retryUntil(
anyOf(
maxRetries(3)
, delay(ms('5s'))
)
, fn
)
```

## API
```ts
interface IContext {
error: unknown
retries: number // the number of retries, starting from 0.
}

type IPredicate = (context: IContext) => Awaitable
```

### retryUntil
```ts
function retryUntil(predicate: IPredicate): (fn: () => Awaitable) => Promise
function retryUntil(predicate: IPredicate, fn: () => Awaitable): Promise
```

If `fn` throws an error,
retry until the return value of the `predicate` is [Truthy].

[Truthy]: https://developer.mozilla.org/en-US/docs/Glossary/Truthy

### withRetryUntil
```ts
function withRetryUntil(
predicate: IPredicate
): (
fn: (...args: Args) => Awaitable
) => (...args: Args) => Promise
function withRetryUntil(
predicate: IPredicate
, fn: (...args: Args) => Awaitable
): (...args: Args) => Promise
```

A simple wrapper around `retryUntil`.

### Helpers
#### anyOf
```ts
function anyOf(...predicates: Array): IPredicate
```

Equivalent to
```ts
context => (predicate1 && await predicate1(context))
|| (predicate2 && await predicate2(context))
|| ...
|| (predicateN && await predicateN(context))
```

#### delay
```ts
function delay(ms: number): IPredicate
```

#### exponentialBackoff
```ts
function exponentialBackoff({
baseTimeout
, maxTimeout = Infinity
, factor = 2
, jitter = true
}: {
baseTimeout: number
maxTimeout?: number
factor?: number
jitter?: boolean
}): IPredicate
```

Equivalent to
```ts
const timeout = Math.min(factor ** retries * baseTimeout, maxTimeout)
delay(jitter ? randomIntInclusive(0, timeout) : timeout)
```

#### maxRetries
```ts
function maxRetries(times: number): IPredicate
```

#### notRetryOn
```ts
function notRetryOn(errors: Array>): IPredicate
```

Blacklist.

#### notRetryOnCommonFatalErrors
```ts
const notRetryOnCommonFatalErrors: IPredicate
```

This predicate blacklists theses errors:
- `SyntaxError`
- `ReferenceError`
- `RangeError`
- `URIError`

There is no `TypeError` because `TypeError` does not mean
"a value is not of the expected type",
it has been abused for various purposes.

#### retryOn
```ts
function retryOn(errors: Array>): IPredicate
```

Whitelist.

#### signal
```ts
function signal(abortSignal: AbortSignal): IPredicate
```

#### tap
```ts
function tap(fn: (context: IContext) => void): IPredicate
```