22 lines
628 B
TypeScript
22 lines
628 B
TypeScript
export function createRateLimiter(windowMs = 60_000, cleanupIntervalMs = 5 * 60_000) {
|
|
const map = new Map<string, { count: number; resetAt: number }>();
|
|
|
|
setInterval(() => {
|
|
const now = Date.now();
|
|
for (const [key, entry] of map) {
|
|
if (now > entry.resetAt) map.delete(key);
|
|
}
|
|
}, cleanupIntervalMs);
|
|
|
|
return function check(key: string, max: number): boolean {
|
|
const now = Date.now();
|
|
const entry = map.get(key);
|
|
if (!entry || now > entry.resetAt) {
|
|
map.set(key, { count: 1, resetAt: now + windowMs });
|
|
return true;
|
|
}
|
|
entry.count++;
|
|
return entry.count <= max;
|
|
};
|
|
}
|