-
-
Notifications
You must be signed in to change notification settings - Fork 195
Expand file tree
/
Copy pathBurstyRateLimiter.js
More file actions
68 lines (68 loc) · 2.22 KB
/
Copy pathBurstyRateLimiter.js
File metadata and controls
68 lines (68 loc) · 2.22 KB
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
60
61
62
63
64
65
66
67
68
import RateLimiterRes from "./RateLimiterRes.js";
/**
* Bursty rate limiter exposes only msBeforeNext time and doesn't expose points from bursty limiter by default
* @type {BurstyRateLimiter}
*/
export default (class BurstyRateLimiter {
constructor(rateLimiter, burstLimiter) {
this._rateLimiter = rateLimiter;
this._burstLimiter = burstLimiter;
}
/**
* Merge rate limiter response objects. Responses can be null
*
* @param {RateLimiterRes} [rlRes] Rate limiter response
* @param {RateLimiterRes} [blRes] Bursty limiter response
*/
_combineRes(rlRes, blRes) {
if (!rlRes) {
return null;
}
return new RateLimiterRes(rlRes.remainingPoints, Math.min(rlRes.msBeforeNext, blRes ? blRes.msBeforeNext : 0), rlRes.consumedPoints, rlRes.isFirstInDuration);
}
/**
* @param key
* @param pointsToConsume
* @param options
* @returns {Promise<any>}
*/
consume(key, pointsToConsume = 1, options = {}) {
return this._rateLimiter.consume(key, pointsToConsume, options)
.catch((rlRej) => {
if (rlRej instanceof RateLimiterRes) {
return this._burstLimiter.consume(key, pointsToConsume, options)
.then((blRes) => {
return Promise.resolve(this._combineRes(rlRej, blRes));
})
.catch((blRej) => {
if (blRej instanceof RateLimiterRes) {
return Promise.reject(this._combineRes(rlRej, blRej));
}
else {
return Promise.reject(blRej);
}
});
}
else {
return Promise.reject(rlRej);
}
});
}
/**
* It doesn't expose available points from burstLimiter
*
* @param key
* @returns {Promise<RateLimiterRes>}
*/
get(key) {
return Promise.all([
this._rateLimiter.get(key),
this._burstLimiter.get(key),
]).then(([rlRes, blRes]) => {
return this._combineRes(rlRes, blRes);
});
}
get points() {
return this._rateLimiter.points;
}
});