summaryrefslogtreecommitdiff
path: root/apps/web/lib/rate-limit.ts
blob: 506511d162f76e23157bcf7f1a774d8a484647fa (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
25
26
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 === 0) {
    requestTimestamps.delete(identifier)
  } else 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 }
}