|
1 | | -import Redis from 'ioredis' |
| 1 | +import { Redis } from 'ioredis' |
2 | 2 |
|
3 | | -export default async function checkRateLimitExceeded(redis: Redis, key: string, maxRequests: number): Promise<boolean> { |
4 | | - const redisKey = `requests.${key}` |
5 | | - const current = await redis.incr(redisKey) |
| 3 | +const cache = new Map<string, { count: number, expires: number }>() |
6 | 4 |
|
7 | | - if (current === 1) { |
8 | | - // this is the first request in the window, so set the key to expire |
9 | | - await redis.expire(redisKey, 1) |
| 5 | +setInterval(() => { |
| 6 | + const now = Date.now() |
| 7 | + for (const [key, value] of cache.entries()) { |
| 8 | + if (now > value.expires) { |
| 9 | + cache.delete(key) |
| 10 | + } |
| 11 | + } |
| 12 | +}, 5000) |
| 13 | + |
| 14 | +const script = ` |
| 15 | + local current = redis.call('INCR', KEYS[1]) |
| 16 | + if current == 1 then |
| 17 | + redis.call('EXPIRE', KEYS[1], ARGV[1]) |
| 18 | + end |
| 19 | + return current |
| 20 | +` |
| 21 | + |
| 22 | +export default async function checkRateLimitExceeded( |
| 23 | + redis: Redis, |
| 24 | + key: string, |
| 25 | + maxRequests: number |
| 26 | +): Promise<boolean> { |
| 27 | + // Skip cache in test environment for predictable behavior |
| 28 | + if (process.env.NODE_ENV !== 'test') { |
| 29 | + const cached = cache.get(key) |
| 30 | + if (cached && Date.now() < cached.expires) { |
| 31 | + return cached.count > maxRequests |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + const current = await redis.eval(script, 1, key, 1) as number |
| 36 | + |
| 37 | + // Only cache in production |
| 38 | + if (process.env.NODE_ENV !== 'test') { |
| 39 | + cache.set(key, { |
| 40 | + count: current, |
| 41 | + expires: Date.now() + 500 |
| 42 | + }) |
10 | 43 | } |
11 | 44 |
|
12 | 45 | return current > maxRequests |
|
0 commit comments