Skip to content

fabrix-app/spool-retry

Repository files navigation

spool-retry

Gitter NPM version Build Status Test Coverage Dependency Status Follow @FabrixApp on Twitter

📦 retry Spool

A Spool to make it easy to use Retries with Fabrix

Install

$ npm install --save @fabrix/spool-retry

Configure

// config/main.ts
import { RetrySpool } from '@fabrix/spool-retry'
export const main = {
  spools: [
    // ... other spools
    RetrySpool
  ]
}

Configuration

// config/retry.ts
export const retry = {
  // retries: The maximum amount of times to retry the operation. Default is 10.
  retries: null, // 10,
  // factor: The exponential factor to use. Default is 2.
  factor: null, // 2,
  // minTimeout: The number of milliseconds before starting the first retry. Default is 1000.
  minTimeout: null, // 1000,
  // maxTimeout: The maximum number of milliseconds between two retries. Default is Infinity.
  maxTimeout: null,
  // randomize: Randomizes the timeouts by multiplying with a factor between 1 to 2. Default is false.
  randomize: false
}

For more information about store (type and configuration) please see the retry documentation.

Usage

For the best results, create a Base Class and override or extend the default methods.

  import { RetryManager } from '@fabrix/spool-retry'
  
  export class MyRetry extends RetryManager {
    myFunc(data, opts) {
      const func = this.app.services.somePromiseService(data, opts)
      return this.attempt(func)
        .catch(err => {
           this.app.log.error(err)
           return Promise.reject(err)
        })
    }

    cancelByNameAt5 (name, number) {
      if (number === 5) {
        this.cancelled_retries.add(name)
      }
      return
    }

    // We are overriding the AfterEachFailure function to have it cancel softly at 5 tries
    afterEachFailure(name, params, retry, number, err) {
      this.cancelByNameAt5(name, number)
      return retry(err)
    }
  }

Or simply

 this.app.retries.MyRetry.attempt(func, params)