chenyc
2026-03-22 7885cede659f3255be56f77c1eef2ada7387d6f1
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
class RateLimiter {
  constructor() {
    this.records = new Map(); // key -> lastTs
  }
 
  checkLimit(key, intervalMs) {
    const now = Date.now();
    const last = this.records.get(key) || 0;
    const diff = now - last;
    if (diff < intervalMs) {
      return {
        allowed: false,
        waitMs: intervalMs - diff
      };
    }
    this.records.set(key, now);
    return { allowed: true, waitMs: 0 };
  }
 
  getStats() {
    const result = [];
    for (const [key, ts] of this.records.entries()) {
      result.push({ key, lastAt: ts });
    }
    return result;
  }
 
  clear() {
    this.records.clear();
  }
}
 
module.exports = RateLimiter;