UNPKG

725 BJavaScriptView Raw
1class MemoryRateLimit {
2 constructor (options = {}) {
3 this.options = options
4 this.limits = {}
5 }
6
7 check (id, limit, duration) {
8 const now = Date.now()
9
10 // If first time
11 if (!this.limits[id]) {
12 this.limits[id] = {used: 0, time: now}
13 }
14
15 // Get status
16 const status = this.limits[id]
17
18 // Calculate reset time
19 const reset = (status.time + duration) - now
20
21 if (reset <= 0) {
22 // Time to reset
23 status.used = 0
24 status.time = now
25 return this.check(id, limit, duration)
26 }
27
28 // Calculate remaining
29 const remaining = limit - status.used
30
31 // +1 used
32 status.used++
33
34 return {limit, remaining, reset}
35 }
36}
37
38module.exports = MemoryRateLimit