feat: add rate limiter module
This commit is contained in:
parent
f9d56fec33
commit
52c51fbf3f
1 changed files with 32 additions and 0 deletions
32
src/rateLimiter.js
Normal file
32
src/rateLimiter.js
Normal file
|
|
@ -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 }
|
||||||
Loading…
Reference in a new issue