Files

24 lines
571 B
TypeScript

type Bucket = {
count: number;
resetAt: number;
};
const buckets = new Map<string, Bucket>();
export function checkRateLimit(key: string, limit = 5, windowMs = 15 * 60 * 1000) {
const now = Date.now();
const bucket = buckets.get(key);
if (!bucket || bucket.resetAt <= now) {
buckets.set(key, { count: 1, resetAt: now + windowMs });
return { allowed: true, remaining: limit - 1 };
}
if (bucket.count >= limit) {
return { allowed: false, remaining: 0 };
}
bucket.count += 1;
return { allowed: true, remaining: limit - bucket.count };
}