File size: 667 Bytes
5383ef0 | 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 | // Simple sliding window rate limiter
const windows = new Map();
export function rateLimiter(key, maxRequests, windowMs) {
const now = Date.now();
if (!windows.has(key)) {
windows.set(key, { count: 1, resetAt: now + windowMs });
return true;
}
const entry = windows.get(key);
if (now > entry.resetAt) {
entry.count = 1;
entry.resetAt = now + windowMs;
return true;
}
if (entry.count >= maxRequests) return false;
entry.count++;
return true;
}
// Cleanup every 5 minutes
setInterval(() => {
const now = Date.now();
for (const [k, v] of windows.entries()) {
if (now > v.resetAt) windows.delete(k);
}
}, 5 * 60 * 1000);
|