Skip to content

A flexible, functional-style async retry utility with composable predicates and delay strategies — designed to simplify robust retry logic in JavaScript/TypeScript.

Notifications You must be signed in to change notification settings

walkerrandolphsmith/retry-fp

Repository files navigation

retry-fp

Hero Image

A flexible, functional-style async retry utility with composable predicates and delay strategies — designed to simplify robust retry logic in JavaScript/TypeScript.

🚀 Features

  • Composable: Separate your retry exit conditions (untilFn) and delay strategies (getNextTickFn) for maximum flexibility.
  • Type-safe: Built with TypeScript for strong typing and developer confidence.
  • Pre-built predicates & delay functions: Includes useful defaults like untilHttpStatusOk, untilMaxAttempts, withJitter, advanceFirstAttempt, withExponentialDecay, and everyNSeconds.
  • Zero dependencies: Lightweight and easy to integrate.
  • Tested and reliable: Comprehensive test coverage with Jest.

📦 Installation

npm install retry-fp
# or
yarn add retry-fp

Usage

Backoff

import retry, {
  untilFirst,
  untilHttpStatusOk,
  untilMaxAttempts,
  withExponentialDecay,
  advanceFirstAttempt,
} from 'retry-fp'

// Your async work function (e.g., HTTP request)
async function fetchData(): Promise<{ status: number; data?: any }> {
  // simulate fetch logic here
}

// Retry until HTTP status is 200 or max 5 attempts
// With exponentially backoff with a jitter to avoid the thundering heard problem
const result = await retry(
  fetchData,
  untilFirst(untilHttpStatusOk(), untilMaxAttempts(5)),
  advanceFirstAttempt(withJitter()(withExponentialDecay(500)))
)

if (result.error) {
  console.error('Failed after retries:', result.error)
} else {
  console.log('Success:', result.workOutput)
}

Poll

import retry, {
  untilForever,
  withExponentialDecay,
  advanceFirstAttempt,
} from 'retry-fp'

let latestResult

// Poll for data every 10 seconds
const result = retry(
  async () => {
    const response = await fetchData()
    latestResult = response
    return response
  },
  untilForever(),
  everyNSeconds(10),
)

🧪 Testing

Tests use Jest with fake timers to simulate delay and retries. Run tests with:

yarn test

🤝 Contributing

Contributions, issues, and feature requests are welcome! Feel free to check issues page or submit a pull request.

About

A flexible, functional-style async retry utility with composable predicates and delay strategies — designed to simplify robust retry logic in JavaScript/TypeScript.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published