1.0.7 • Published 4 years ago

fn-retry v1.0.7

Weekly downloads
5
License
MIT
Repository
github
Last release
4 years ago

fn-retry

npm npm GitHub repo GitHub followers Build Status

Installation

npm install fn-retry
yarn add fn-retry

Usage

ES6

import { fnRetry } from 'fn-retry'

// basic example
const fn = () => {
  // function that should be retried in case of errors
  return 'Hello'
}

const result = await fnRetry(fn, {
  delays: [100, 200, 300],
})
console.log(result)

CommonJS

const { fnRetry } = require('fn-retry')

// basic example
const fn = () => {
  // function that should be retried in case of errors
  return 'Hello'
}

const result = await fnRetry(fn, {
  delays: [100, 200, 300],
})
console.log(result)

More examples

API

fnRetry

Base strategy with custom delays. Fn will be called at least one time. In case of errors it will wait specified amount of ms (delays array) before the next call.

fnRetry(fn: Function, options: Object) => Promise

fn

Function that should be retried in case of errors

options

NameTypeDefaultDescription
delaysArray[]Represents delays (in ms) between failed calls, e.g. [100, 200, 300] - in case of error fn will be called 4 times, with specified delays between calls.
onCallErrorFunction() => nullCalled on failed fn call with the object { error: Error, call: number, maxCalls: number } as an argument . It can return optional should-stop-retries value. If returnes true, further retries will be stopped. It can be useful, e.g., in case of auth errors. The default value of the fn can be returned from onMaxCallsExceeded as well.
onMaxCallsExceededFunction() => nullCalled when max number of fn calls is exceeded or when retries cancelled by true returned from onCallError. It can return optional default value.
waiterGeneratornullIf passed, delays option will be ignored. Represents generator of delay values. Can be used for making till-success calls. In this case maxCalls is not passed from onCallError callback.

Example

// Base example

const fn = () => {
  // some function that should be retried in case of errors
  return 'Hello'
}

const result = await fnRetry(fn, {
  delays: [100],
  onCallError: ({ error, call, maxCalls }) =>
    console.log(`Call ${call} of ${maxCalls}: ${error}`),
  onMaxCallsExceeded: () => console.log('max calls exceeded'),
})

// Example with generator, till-success strategy

const fn = () => {
  // ...
}

function* waiter() {
  let waitMs = 100
  while (true) {
    yield waitMs
    waitMs *= 2
  }
}
await fnRetry(fn, {
  waiter,
  onCallError: ({ error, call }) => console.log(`Call ${call}: ${error}`),
})

// Example with generator, custom delays

const fn = () => {
  // ...
}

// it is the same as passing delays: [ 100, 200, 400, 800, 600 ]
function* waiter() {
  let waitMs = 100
  for (let i = 0; i < 5; i++) {
    yield waitMs
    waitMs *= 2
  }
}
await fnRetry(fn, {
  waiter,
  onMaxCallsExceeded: () => ({}),
})

fnRetryWithFibonacci

In case of errors it will wait according to Fibonacci sequence before the next call. Fn will be called at least one time, e.g.:\ with calls equal to 5: call failed -> wait 1s -> call failed -> wait 1s -> call failed -> wait 2s -> call failed -> wait 3s -> call failed

fnRetryWithFibonacci(fn: Function, options: Object) => Promise

fn

Function that should be retried in case of errors

options

NameTypeDefaultDescription
callsnumber1Max number of calls, e.g. if calls is equal to 2, then flow will look like: call failed -> wait 1s -> call succeded.
onCallErrorFunction() => nullCalled on failed fn call with the object { error: Error, call: number, maxCalls: number } as an argument. It can return optional should-stop-retries value. If returnes true, further retries will be stopped. It can be useful, e.g., in case of auth errors. The default value of the fn can be returned from onMaxCallsExceeded as well.
onMaxCallsExceededFunction() => nullCalled when max number of fn calls is exceeded or when retries cancelled by true returned from onCallError. It can return optional default value.

Example

const fn = () => {
  // some function that should be retried in case of errors
  return 'Hello'
}

const result = await fnRetryWithFibonacci(fn, {
  calls: 2,
  onCallError: ({ error, call, maxCalls }) =>
    console.log(`Call ${call} of ${maxCalls}: ${error}`),
  onMaxCallsExceeded: () => console.log('max calls exceeded'),
})

Higher-order functions: fnRetriable, fnRetriableWithFibonacci

You can use wrapper version of retry functions. They just wrap fn that needs to be retried in case of errors, and return retriable version of the fn. See options in corresponding APIs above. This allows you to use retried version just like you use original fn.

// function that should be retried in case of errors
const getPostById = ({ id }) =>
  fetch(`https://jsonplaceholder.typicode.com/posts/${id}`).then(response =>
    response.json()
  )

// wrap getPostById to make it retriable
const getPostByIdWithRetry = fnRetriable(getPostById, {
  delays: [1000],
})
// call retriable version of getPostById
const post = await getPostByIdWithRetry({ id: 1 })
console.log(post)

Testing

Clone the repository and execute:

yarn test
npm test
1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.2

4 years ago

1.0.3

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago