Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import * as fs from 'fs';
import * as CircuitBreaker from 'opossum';
import { promisify } from 'util';
let breaker: CircuitBreaker;
const callbackNoArgs = async () => console.log('foo');
CircuitBreaker.isOurError(new Error()); // $ExpectType boolean
breaker = new CircuitBreaker(async () => true, {
timeout: 1000,
maxFailures: 50,
resetTimeout: 10,
rollingCountTimeout: 500,
rollingCountBuckets: 20,
name: 'test',
group: 'group',
rollingPercentilesEnabled: true,
capacity: 1,
errorThresholdPercentage: 1,
enabled: true,
allowWarmUp: true,
volumeThreshold: 1,
cache: true,
constructor () {
super();
// state
this.state = { requestState: [] };
// binds
this.makeRequest = this.makeRequest.bind(this);
this.makeNode = this.makeNode.bind(this);
this.clearNodes = this.clearNodes.bind(this);
// circuit breaker settings
this.circuitBreakerOptions = { timeout: 500, maxFailures: 3, resetTimeout: 5000 };
this.route = 'http://localhost:3000/flakeyService';
this.circuit = circuitBreaker(() => $.get(this.route), this.circuitBreakerOptions);
// circuit breaker events
this.circuit.fallback(() =>
({ body: `${this.route} unavailable right now. Try later.` }));
this.circuit.on('success', (result) =>
this.makeNode({ state: `SUCCESS`, body: `${JSON.stringify(result)}` }));
this.circuit.on('timeout', () =>
this.makeNode({ state: `TIMEOUT`, body: `${this.route} is taking too long to respond.` }));
this.circuit.on('reject', () =>
this.makeNode({ state: `REJECTED`, body: `The breaker for ${this.route} is open. Failing fast.` }));
this.circuit.on('open', () =>
this.makeNode({ state: `OPEN`, body: `The breaker for ${this.route} just opened.` }));
this.circuit.on('halfOpen', () =>
this.makeNode({ state: `HALF_OPEN`, body: `The breaker for ${this.route} is half open.` }));
this.circuit.on('close', () =>
this.makeNode({ state: `CLOSE`, body: `The breaker for ${this.route} has closed. Service OK.` }));
return (url, options) => {
const { host } = new URL(url);
let circuitBreaker = circuitBreakers[host];
if (!circuitBreaker) {
const circuitBreakerOptions = {
name: host,
timeout: 5000,
resetTimeout: 10000,
};
circuitBreakers[host] = new CircuitBreaker(fetch, circuitBreakerOptions);
circuitBreaker = circuitBreakers[host];
}
return !options
? circuitBreaker.fire(url)
: circuitBreaker.fire(url, options);
};
}