@shogun-sdk/money-legos
Version:
Shogun Money Legos: clients and types for quotes, memes, prices, balances, fees, validations, etc.
46 lines • 1.52 kB
JavaScript
export class RateLimiter {
constructor() {
Object.defineProperty(this, "tokens", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "lastRefill", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "capacity", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.capacity = 1200; // 1200 tokens per minute
this.tokens = this.capacity;
this.lastRefill = Date.now();
}
refillTokens() {
const now = Date.now();
const elapsedMinutes = (now - this.lastRefill) / (1000 * 60); // convert to minutes
if (elapsedMinutes >= 1) {
this.tokens = this.capacity;
this.lastRefill = now;
}
}
async waitForToken(weight = 1) {
this.refillTokens();
if (this.tokens >= weight) {
this.tokens -= weight;
return;
}
const waitTime = (60 - (Date.now() - this.lastRefill) / 1000) * 1000; // wait until next refill
return new Promise((resolve) => setTimeout(resolve, waitTime)).then(() => {
this.refillTokens();
return this.waitForToken(weight); // recursively check again after refill
});
}
}
//# sourceMappingURL=rateLimiter.js.map