Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including simple-circuit-breaker with all npm packages installed. Try it out:

var simpleCircuitBreaker = require("simple-circuit-breaker")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

simple-circuit-breaker v1.0.0

Simple circuit breaker in plain ES6 for functions returning Promises. No dependencies, configurable grace period, threshold and error message.

simple-circuit-breaker

Simple JavaScript (ES6) circuit breaker wrapper for functions returning Promises. No dependencies. Just plain ES6.

Module has configurable grace period, threshold and error message. It simply wraps any function that return promise.

More information about circuit breakers: Circuit Breakers

Usage

Basic usage with defaults

const circuitBreaker = require('simple-circuit-breaker')

function callBackend(url) {
  return fetch(url)
    .then(parseResponse)
}

const withCircuitBreaker = circuitBreaker(callBackend)

withCircuitBreaker('http://my.backend.com')
  .then(doSomethingWithData, handleError)

Passing configuration options

Parameters

  1. asyncFn - Function that we want to guard with circuit breaker Must return a Promise
  2. gracePeriodMs - How long do we wait before retrying after switched to CLOSED state
  3. threshold - How many failures do we need to stop calling backend and start failing immediately - HALF OPEN
  4. message - This will be the error message in OPEN state
const withCircuitBreaker = circuitBreaker(callBackend, 15000, 3, 'Damn, it failed too many times!')

Default values

  • gracePeriodMs = 3000
  • threshold = 1
  • message = 'Functionality disabled due to previous errors.'
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free