@elasticapi/wpengine-typescript-sdk
Version:
Unofficial TypeScript SDK for the WP Engine API
73 lines • 2.22 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RateLimitError = exports.RateLimiter = void 0;
/**
* Token bucket rate limiter implementation
*/
class RateLimiter {
constructor(maxRequestsPerSecond = 5) {
this.maxTokens = maxRequestsPerSecond;
this.tokens = maxRequestsPerSecond;
this.lastRefill = Date.now();
this.refillRate = maxRequestsPerSecond;
this.refillInterval = 1000; // 1 second in milliseconds
}
/**
* Refills tokens based on time elapsed
*/
refillTokens() {
const now = Date.now();
const timePassed = now - this.lastRefill;
const tokensToAdd = (timePassed / this.refillInterval) * this.refillRate;
this.tokens = Math.min(this.maxTokens, this.tokens + tokensToAdd);
this.lastRefill = now;
}
/**
* Checks if a request can be made and consumes a token if available
* @returns Promise that resolves when a token is available
*/
async acquireToken() {
this.refillTokens();
if (this.tokens >= 1) {
this.tokens -= 1;
return Promise.resolve();
}
// Calculate wait time until next token is available
const waitTime = ((1 - this.tokens) / this.refillRate) * 1000;
return new Promise(resolve => {
setTimeout(() => {
this.refillTokens();
this.tokens -= 1;
resolve();
}, waitTime);
});
}
/**
* Gets the number of tokens currently available
*/
getAvailableTokens() {
this.refillTokens();
return this.tokens;
}
/**
* Gets the time in milliseconds until the next token will be available
*/
getWaitTime() {
this.refillTokens();
if (this.tokens >= 1)
return 0;
return ((1 - this.tokens) / this.refillRate) * 1000;
}
}
exports.RateLimiter = RateLimiter;
/**
* Rate limiter error class
*/
class RateLimitError extends Error {
constructor(message) {
super(message);
this.name = 'RateLimitError';
}
}
exports.RateLimitError = RateLimitError;
//# sourceMappingURL=rate-limiter.js.map