rate-limiter-custom
Version:
A fast, customizable, and efficient rate-limiting middleware for Express in TypeScript.
27 lines (26 loc) • 1.18 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.tokenBucketRateLimiter = tokenBucketRateLimiter;
const tokenBuckets = new Map();
function tokenBucketRateLimiter(options) {
const tokensPerInterval = options.tokensPerInterval || options.maxRequests;
return (req, res, next) => {
var _a;
const ip = (_a = req.ip) !== null && _a !== void 0 ? _a : "unknown";
const currentTime = Date.now();
if (!tokenBuckets.has(ip)) {
tokenBuckets.set(ip, { tokens: tokensPerInterval, lastRefill: currentTime });
}
const bucket = tokenBuckets.get(ip);
const timeElapsed = currentTime - bucket.lastRefill;
// Refill tokens based on elapsed time
const newTokens = Math.floor(timeElapsed / options.windowMs) * tokensPerInterval;
bucket.tokens = Math.min(bucket.tokens + newTokens, tokensPerInterval);
bucket.lastRefill = currentTime;
if (bucket.tokens > 0) {
bucket.tokens--;
return next();
}
return res.status(429).json({ message: options.errorMessage || "Too many requests, please try again later." });
};
}