UNPKG

anti-rate-limit

Version:

anti-rate-limit is a powerful task queue rate limiter designed for Node.js applications. It allows developers to efficiently manage and control the rate at which tasks are executed by enforcing customizable rate limits, concurrency, and automatic retries

62 lines 1.99 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AntiRateLimit = void 0; class AntiRateLimit { constructor(options) { this.queue = []; this.activeTasks = 0; this.requestCount = 0; this.maxRequests = options.maxRequests; this.interval = options.interval; this.concurrency = options.concurrency || 1; this.retryLimit = options.retryLimit || 3; // Reset request count periodically setInterval(() => { this.requestCount = 0; this.processQueue(); }, this.interval); } async addTask(task) { return new Promise((resolve, reject) => { const wrappedTask = { ...task, resolve, reject, retries: 0, }; this.queue.push(wrappedTask); this.queue.sort((a, b) => (b.priority || 0) - (a.priority || 0)); // Higher priority first this.processQueue(); }); } async processQueue() { while (this.queue.length > 0 && this.activeTasks < this.concurrency && this.requestCount < this.maxRequests) { const task = this.queue.shift(); if (!task) return; this.activeTasks++; this.requestCount++; try { const result = await task.execute(); task.resolve(result); } catch (error) { if (task.retries < this.retryLimit) { task.retries++; this.queue.push(task); // Retry failed task } else { task.reject(error); } } finally { this.activeTasks--; this.processQueue(); } } } } exports.AntiRateLimit = AntiRateLimit; //# sourceMappingURL=antiRateLimit.js.map