second commit
This commit is contained in:
23
src/lib/rateLimit.ts
Normal file
23
src/lib/rateLimit.ts
Normal file
@ -0,0 +1,23 @@
|
||||
// src/lib/rateLimit.ts
|
||||
const rateLimits = new Map<string, { count: number; resetTime: number }>()
|
||||
|
||||
export function rateLimit(
|
||||
ip: string,
|
||||
limit: number = 100,
|
||||
windowMs: number = 60000 // 1 minute
|
||||
): { success: boolean; remaining: number; resetTime: number } {
|
||||
const now = Date.now()
|
||||
const record = rateLimits.get(ip)
|
||||
|
||||
if (!record || now > record.resetTime) {
|
||||
rateLimits.set(ip, { count: 1, resetTime: now + windowMs })
|
||||
return { success: true, remaining: limit - 1, resetTime: now + windowMs }
|
||||
}
|
||||
|
||||
if (record.count >= limit) {
|
||||
return { success: false, remaining: 0, resetTime: record.resetTime }
|
||||
}
|
||||
|
||||
record.count++
|
||||
return { success: true, remaining: limit - record.count, resetTime: record.resetTime }
|
||||
}
|
||||
Reference in New Issue
Block a user