| |
| 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; |
| } |
|
|
| |
| setInterval(() => { |
| const now = Date.now(); |
| for (const [k, v] of windows.entries()) { |
| if (now > v.resetAt) windows.delete(k); |
| } |
| }, 5 * 60 * 1000); |
|
|