UNPKG

rate-limiter-custom

Version:

A fast, customizable, and efficient rate-limiting middleware for Express in TypeScript.

26 lines (25 loc) 988 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.slidingWindowRateLimiter = slidingWindowRateLimiter; const rateLimitMap = new Map(); function slidingWindowRateLimiter(options) { return (req, res, next) => { var _a; const ip = (_a = req.ip) !== null && _a !== void 0 ? _a : "unknown"; const currentTime = Date.now(); if (!rateLimitMap.has(ip)) { rateLimitMap.set(ip, { count: 1, startTime: currentTime }); return next(); } const userData = rateLimitMap.get(ip); if (currentTime - userData.startTime > options.windowMs) { rateLimitMap.set(ip, { count: 1, startTime: currentTime }); return next(); } if (userData.count >= options.maxRequests) { return res.status(429).json({ message: options.errorMessage || "Too many requests, please try again later." }); } userData.count++; next(); }; }