1 2
export 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 2
    this.lastTime = Date.now()
9 2
    this.capacity = (typeof capacity !== 'undefined') ? capacity : refillCount
10 2
    this.left = this.capacity
11 2
    this.refillRate = refillCount / refillPeriod
12
  }
13

14 2
  take (count: number = 1) {
15 2
    const now = Date.now()
16 2
    const delta = Math.max(now - this.lastTime, 0)
17 2
    const amount = delta * this.refillRate
18

19 2
    this.lastTime = now
20 2
    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 2
    if (this.left < count) {
28 2
      return false
29
    }
30

31 2
    this.left -= count
32 2
    return true
33
  }
34
}

Read our documentation on viewing source code .

Loading