@olakai/sdk
Version:
This document demonstrates how to use the Olakai SDK with all its features.
60 lines • 2.22 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCircuitBreakerMiddleware = createCircuitBreakerMiddleware;
const exceptions_1 = require("../exceptions");
/**
* Create a circuit breaker middleware
* This middleware implements a circuit breaker pattern to prevent a function from being called if it fails too many times.
* @param options - The options for the middleware
* @returns A middleware function
* @default options - {
* failureThreshold: 5, // Number of failures before the circuit breaker opens
* resetTimeoutMs: 30000, // Time in milliseconds before the circuit breaker closes
* }
* @throws {CircuitBreakerOpenError} if the circuit breaker is OPEN
*/
function createCircuitBreakerMiddleware(options) {
const { failureThreshold, resetTimeoutMs } = options;
let state = "CLOSED";
let failureCount = 0;
let lastFailureTime = 0;
let successCount = 0;
return {
name: "circuitBreaker",
beforeCall: async (args) => {
const now = Date.now();
if (state === "OPEN") {
if (now - lastFailureTime > resetTimeoutMs) {
state = "HALF_OPEN";
successCount = 0;
}
else {
throw new exceptions_1.CircuitBreakerOpenError("Circuit breaker is OPEN");
}
}
return args;
},
afterCall: async (result, _args) => {
if (state === "HALF_OPEN") {
successCount++;
if (successCount >= 3) {
// Require 3 successes to close
state = "CLOSED";
failureCount = 0;
}
}
else if (state === "CLOSED") {
failureCount = 0; // Reset failure count on success
}
return result;
},
onError: async (_error, _args) => {
failureCount++;
lastFailureTime = Date.now();
if (state === "HALF_OPEN" || failureCount >= failureThreshold) {
state = "OPEN";
}
},
};
}
//# sourceMappingURL=circuitBreaker.js.map