diff --git a/src/rateLimiter.js b/src/rateLimiter.js new file mode 100644 index 0000000..311dce4 --- /dev/null +++ b/src/rateLimiter.js @@ -0,0 +1,32 @@ +const MAX_REQUESTS_PER_DAY = parseInt(process.env.MAX_REQUESTS_PER_DAY, 10) || 5 + +const userCounts = new Map() +let currentDate = new Date().toDateString() + +function resetIfNeeded() { + const today = new Date().toDateString() + if (today !== currentDate) { + userCounts.clear() + currentDate = today + console.log('Rate limiter: daily counters reset') + } +} + +function checkLimit(userId) { + resetIfNeeded() + const count = userCounts.get(userId) || 0 + return { + allowed: count < MAX_REQUESTS_PER_DAY, + count, + max: MAX_REQUESTS_PER_DAY + } +} + +function increment(userId) { + resetIfNeeded() + const count = (userCounts.get(userId) || 0) + 1 + userCounts.set(userId, count) + return count +} + +module.exports = { checkLimit, increment, MAX_REQUESTS_PER_DAY }