-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjquery.circuitbreaker.js
59 lines (47 loc) · 1.45 KB
/
jquery.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* CircuitBreaker
*
* Wrap a protected function call in a circuit breaker object,
* which monitors for failures. Once the failures reach a certain
* threshold, the circuit breaker trips, and all further calls to
* the circuit breaker return with an error, without the protected call
* being made at all.
*
* Copyright 2018 Kjel Delaey
* Released under the MIT license
* https://raw.githubusercontent.com/trimentor/jquery-circuitbreaker/master/LICENSE
*/
var CircuitBreaker = function (asyncFn, options) {
this.asyncFn = asyncFn;
this.deferred = $.Deferred();
this.failures = 0;
this.options = $.extend({
failureTreshold: 5
}, options);
};
CircuitBreaker.prototype.fire = function () {
var cb = this;
if (cb.getState() === 'OPEN') cb.deferred.reject(new CircuitBreakerError());
cb.asyncFn().done(function (result) {
cb.failures = 0;
cb.deferred.resolve(result);
}).fail(function (result) {
if (cb.getState() === 'CLOSED') {
cb.failures += 1;
cb.fire();
} else {
cb.deferred.reject(new CircuitBreakerError());
}
});
return cb.deferred;
};
CircuitBreaker.prototype.getFailures = function () {
return this.failures;
};
CircuitBreaker.prototype.getState = function () {
return (this.getFailures() < this.getFailureThreshold()) ? 'CLOSED' : 'OPEN';
};
CircuitBreaker.prototype.getFailureThreshold = function () {
return this.options.failureTreshold;
};
var CircuitBreakerError = function () {};