hrms-shared
Version:
HRMS shared code: models, middleware, utils
31 lines (23 loc) • 1 kB
JavaScript
const CircuitBreaker = require('opossum');
/**
* Create a reusable circuit breaker for any async function
* @param {Function} actionFn - the function (e.g., API call) you want to wrap
* @param {Object} options - breaker options
* @param {Function} fallbackFn - optional fallback
*/
function createCircuitBreaker(actionFn, options = {}, fallbackFn = null) {
const defaultOptions = {
timeout: 5000,
errorThresholdPercentage: 50,
resetTimeout: 10000,
};
const breaker = new CircuitBreaker(actionFn, { ...defaultOptions, ...options });
if (fallbackFn) {
breaker.fallback(fallbackFn);
}
breaker.on('open', () => console.log('🚨 Circuit breaker OPEN - Service is unhealthy'));
breaker.on('halfOpen', () => console.log('⚠️ Circuit breaker HALF-OPEN - Testing service...'));
breaker.on('close', () => console.log('✅ Circuit breaker CLOSED - Service recovered'));
return breaker;
}
module.exports = createCircuitBreaker;