UNPKG

@the-node-forge/api-rate-limit

Version:

A simple and efficient API rate limiter for JavaScript/TypeScript applications

22 lines (21 loc) 723 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class RateLimiter { constructor(options) { this.windowMs = options.windowMs; this.maxRequests = options.maxRequests; this.requests = new Map(); } isAllowed(userId) { const now = Date.now(); const timestamps = this.requests.get(userId) || []; const filteredTimestamps = timestamps.filter((timestamp) => now - timestamp < this.windowMs); if (filteredTimestamps.length >= this.maxRequests) { return false; } filteredTimestamps.push(now); this.requests.set(userId, filteredTimestamps); return true; } } exports.default = RateLimiter;