diff options
Diffstat (limited to 'apps/web/lib/rate-limit.ts')
| -rw-r--r-- | apps/web/lib/rate-limit.ts | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/apps/web/lib/rate-limit.ts b/apps/web/lib/rate-limit.ts new file mode 100644 index 0000000..4016781 --- /dev/null +++ b/apps/web/lib/rate-limit.ts @@ -0,0 +1,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 } +} |