File size: 678 Bytes
03b405b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const buckets = new Map();

function allowRate(key, limit, windowMs) {
  const now = Date.now();
  const bucket = buckets.get(key) || [];
  const recent = bucket.filter((time) => now - time < windowMs);
  if (recent.length >= limit) {
    buckets.set(key, recent);
    return false;
  }
  recent.push(now);
  buckets.set(key, recent);
  return true;
}

setInterval(() => {
  const cutoff = Date.now() - 24 * 60 * 60 * 1000;
  for (const [key, values] of buckets.entries()) {
    const recent = values.filter((time) => time > cutoff);
    if (recent.length) buckets.set(key, recent);
    else buckets.delete(key);
  }
}, 60 * 60 * 1000).unref();

module.exports = { allowRate };