* Check and update rate limit for a user. * Returns true if the request is allowed, false if rate limited.
(userId: string)
| 46 | * Returns true if the request is allowed, false if rate limited. |
| 47 | */ |
| 48 | function checkRateLimit(userId: string): boolean { |
| 49 | const now = Date.now() |
| 50 | const hourMs = 60 * 60 * 1000 |
| 51 | |
| 52 | // Periodically clean up expired entries to prevent memory leak |
| 53 | if (now - lastCleanupTime > CLEANUP_INTERVAL_MS) { |
| 54 | cleanupExpiredEntries() |
| 55 | lastCleanupTime = now |
| 56 | } |
| 57 | |
| 58 | const userLimit = impressionRateLimiter.get(userId) |
| 59 | |
| 60 | if (!userLimit || now >= userLimit.resetAt) { |
| 61 | // Reset or initialize the counter |
| 62 | impressionRateLimiter.set(userId, { count: 1, resetAt: now + hourMs }) |
| 63 | return true |
| 64 | } |
| 65 | |
| 66 | if (userLimit.count >= MAX_IMPRESSIONS_PER_HOUR) { |
| 67 | return false |
| 68 | } |
| 69 | |
| 70 | userLimit.count++ |
| 71 | return true |
| 72 | } |
| 73 | |
| 74 | const bodySchema = z.object({ |
| 75 | impUrl: z.url(), |
no test coverage detected