Created
January 22, 2023 14:41
-
-
Save Prosen-Ghosh/dc11ce700b3002a40191020210a63678 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Redis = require("ioredis"); | |
const redis = new Redis(); | |
app.use(async (req, res, next) => { | |
const userIp = req.ip; | |
const currentTime = Date.now(); | |
const rateLimit = 100; // Number of requests per hour | |
const rateLimitPeriod = 3600; // 1 hour | |
const rateLimitKey = `rate_limit:${userIp}`; | |
const requests = await redis.lrange(rateLimitKey, 0, -1); | |
const filteredRequests = requests.filter(r => currentTime - r < rateLimitPeriod); | |
await redis.ltrim(rateLimitKey, filteredRequests.length, -1); | |
await redis.rpush(rateLimitKey, currentTime); | |
if (filteredRequests.length >= rateLimit) { | |
return res.status(429).send("Too Many Requests"); | |
} | |
next(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment