44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
import { redis } from './redis'
|
|
|
|
export async function rateLimit(
|
|
identifier: string,
|
|
limit: number,
|
|
window: number // seconds
|
|
): Promise<{ success: boolean; remaining: number }> {
|
|
const key = `ratelimit:${identifier}`
|
|
const now = Date.now()
|
|
const windowStart = now - window * 1000
|
|
|
|
try {
|
|
await redis.zremrangebyscore(key, 0, windowStart)
|
|
|
|
const count = await redis.zcard(key)
|
|
|
|
if (count >= limit) {
|
|
return { success: false, remaining: 0 }
|
|
}
|
|
|
|
await redis.zadd(key, now, `${now}`)
|
|
await redis.expire(key, window)
|
|
|
|
return { success: true, remaining: limit - count - 1 }
|
|
} catch (error) {
|
|
console.error('Rate limit error:', error)
|
|
return { success: true, remaining: limit }
|
|
}
|
|
}
|
|
|
|
export async function checkRateLimit(fid: string, action: string): Promise<boolean> {
|
|
const limits: Record<string, { limit: number; window: number }> = {
|
|
vote: { limit: 10, window: 60 },
|
|
comment: { limit: 5, window: 60 },
|
|
search: { limit: 10, window: 60 }
|
|
}
|
|
|
|
const config = limits[action]
|
|
if (!config) return true
|
|
|
|
const result = await rateLimit(`${action}:${fid}`, config.limit, config.window)
|
|
return result.success
|
|
}
|