-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcircuitBreaker.js
44 lines (40 loc) · 1.01 KB
/
circuitBreaker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const circuitBreaker = (fn, failureCount, timeThreshold) => {
let failures = 0;
let timeSinceLastFailure = 0;
let isClosed = false;
return function(...args){
// if service is closed
if(isClosed){
const diff = Date.now() - timeSinceLastFailure;
// if the time since last failure has exceeded
// the time threshold
// open the service
if(diff > timeThreshold){
isClosed = false;
}
// else throw error
else{
console.error("Service unavailable");
return;
}
}
// try running the function
// if it passes reset the failure count
try{
const result = fn(...args);
failures = 0;
return result;
}
// if function throws error / fails
// increase the failure count and
// timewhen it fails
catch(error){
failures++;
timeSinceLastFailure = Date.now();
if(failures >= failureCount){
isClosed = true;
}
console.log("Error");
}
}
}