1 | class 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 |
|
11 | if (!this.limits[id]) {
|
12 | this.limits[id] = {used: 0, time: now}
|
13 | }
|
14 |
|
15 |
|
16 | const status = this.limits[id]
|
17 |
|
18 |
|
19 | const reset = (status.time + duration) - now
|
20 |
|
21 | if (reset <= 0) {
|
22 |
|
23 | status.used = 0
|
24 | status.time = now
|
25 | return this.check(id, limit, duration)
|
26 | }
|
27 |
|
28 |
|
29 | const remaining = limit - status.used
|
30 |
|
31 |
|
32 | status.used++
|
33 |
|
34 | return {limit, remaining, reset}
|
35 | }
|
36 | }
|
37 |
|
38 | module.exports = MemoryRateLimit
|