UNPKG

1.01 kBPlain TextView Raw
1export default class TokenBucket {
2 private lastTime: number
3 private left: number
4 private capacity: number
5 private refillRate: number
6
7 constructor ({ refillPeriod, refillCount, capacity }: { refillPeriod: number, refillCount: number, capacity?: number }) {
8 this.lastTime = Date.now()
9 this.capacity = (typeof capacity !== 'undefined') ? capacity : refillCount
10 this.left = this.capacity
11 this.refillRate = refillCount / refillPeriod
12 }
13
14 take (count: number = 1) {
15 const now = Date.now()
16 const delta = Math.max(now - this.lastTime, 0)
17 const amount = delta * this.refillRate
18
19 this.lastTime = now
20 this.left = Math.min(this.left + amount, this.capacity)
21
22 // this debug statement is commented out for performance, uncomment when
23 // debugging rate limit middleware
24 //
25 // log.debug('took token from bucket. accountId=%s remaining=%s', accountId, bucket.left)
26
27 if (this.left < count) {
28 return false
29 }
30
31 this.left -= count
32 return true
33 }
34}