UNPKG

@mgiamberardino/rate-limiter

Version:
60 lines 1.76 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const memory_store_1 = require("./memory.store"); class RateLimiter { constructor(options) { this.isRunning = false; this.options = Object.assign({}, RateLimiter.DEFAULT_OPTIONS, options); this.store = options && options.store ? options.store : new memory_store_1.MemoryStore(); } ; cyclicReset() { this.store.resetAll(); this.timeoutId = setTimeout(() => this.cyclicReset(), this.options.timeWindow); } start() { if (this.isRunning) { throw new Error('This RateLimiter is already running'); } this.isRunning = true; this.cyclicReset(); } stop() { if (!this.isRunning) { throw new Error('This RateLimiter is not running'); } clearTimeout(this.timeoutId); this.isRunning = false; this.store.resetAll(); } skip(req) { return false; } isValid(req) { if (!this.isRunning || this.skip(req)) { return true; } const key = this.options.keyMapper(req); const calls = this.store.increment(key); if (calls > this.options.requestsLimit) { return false; } return true; } reset() { this.stop(); this.store.resetAll(); this.start(); } } RateLimiter.DEFAULT_REQUESTS_LIMIT = 100; RateLimiter.DEFAULT_TIME_WINDOW = 1000; RateLimiter.DEFAULT_OPTIONS = { requestsLimit: RateLimiter.DEFAULT_REQUESTS_LIMIT, timeWindow: RateLimiter.DEFAULT_TIME_WINDOW }; exports.RateLimiter = RateLimiter; exports.default = RateLimiter; //# sourceMappingURL=rate.limiter.js.map