dienst_echo_whatsappgroep/src/rateLimiter.js

35 lines
878 B
JavaScript

const configuredLimit = parseInt(process.env.MAX_REQUESTS_PER_DAY, 10)
const MAX_REQUESTS_PER_DAY = Number.isFinite(configuredLimit) && configuredLimit > 0
? configuredLimit
: Infinity
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 }