CircuitBreaker
Main class for managing circuit breakers.
Constructor
typescript
constructor(eventHandlers?: EventHandlers)Creates a new instance of CircuitBreaker.
Parameters
eventHandlers(optional): Object containing event handler functions
Example
typescript
const circuitBreaker = new CircuitBreaker({
timeout: () => console.error('Request timeout'),
failure: () => console.error('Request failed'),
open: () => console.error('Circuit breaker opened'),
});Methods
execute
typescript
execute<T>(params: CircuitBreakerParams<T>): Promise<T>Executes a request function with circuit breaker protection.
Parameters
params: Object containing:level(optional): The level of the circuit breaker (CircuitBreakerLevel)name: The name of the circuit breaker (string)requestFn: The request function to be wrapped by the circuit breakerargs(optional): Arguments to be passed to therequestFnfallbackFn(optional): Fallback function to be executed in case of failurefallbackFnArgs(optional): Arguments to be passed to thefallbackFnoptions(optional): Custom circuit breaker options
Returns
Promise<T>: A promise that resolves to the result of therequestFn
Example
typescript
const result = await circuitBreaker.execute({
level: CircuitBreakerLevel.External,
name: 'fetchUserData',
requestFn: fetchUserData,
args: [userId],
fallbackFn: fallbackUserData,
options: {
timeout: 5000,
errorThresholdPercentage: 50,
},
});getCircuitBreakerStats
typescript
getCircuitBreakerStats(): Record<string, any>Gets statistics for all circuit breakers.
Returns
Record<string, any>: An object containing statistics for all circuit breakers
Example
typescript
const stats = circuitBreaker.getCircuitBreakerStats();
console.log(stats);
// {
// 'External::fetchUserData': {
// fires: 100,
// successes: 95,
// failures: 5,
// ...
// }
// }Event Handlers
The following event handlers can be provided in the constructor:
fire?: () => void- Emitted when a request is madereject?: () => void- Emitted when a request is rejectedtimeout?: () => void- Emitted when a request times outsuccess?: () => void- Emitted when a request succeedsfailure?: () => void- Emitted when a request failsopen?: () => void- Emitted when the circuit opensclose?: () => void- Emitted when the circuit closeshalfOpen?: () => void- Emitted when the circuit transitions to half-openfallback?: () => void- Emitted when a fallback function is executedsemaphoreLocked?: () => void- Emitted when the semaphore is lockedhealthCheckFailed?: () => void- Emitted when a health check failsshutdown?: () => void- Emitted when the circuit breaker shuts downcacheHit?: () => void- Emitted when a cached response is usedcacheMiss?: () => void- Emitted when a cache miss occurs
