blob: 40167811dbec92199621e14154da3b3407309453 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
const requestTimestamps = new Map<string, number[]>()
export function rateLimit(
identifier: string,
limit: number,
windowMilliseconds: number
): { success: boolean; remaining: number } {
const now = Date.now()
const timestamps = requestTimestamps.get(identifier) ?? []
const windowStart = now - windowMilliseconds
const recentTimestamps = timestamps.filter(
(timestamp) => timestamp > windowStart
)
if (recentTimestamps.length >= limit) {
requestTimestamps.set(identifier, recentTimestamps)
return { success: false, remaining: 0 }
}
recentTimestamps.push(now)
requestTimestamps.set(identifier, recentTimestamps)
return { success: true, remaining: limit - recentTimestamps.length }
}
|