class ThrottledApiClient {
constructor(maxRequestsPerSecond = 5) {
this.queue = [];
this.processing = false;
this.maxRequestsPerSecond = maxRequestsPerSecond;
this.interval = 1000 / maxRequestsPerSecond;
this.lastRequestTime = 0;
}
async request(url, options) {
return new Promise((resolve, reject) => {
this.queue.push({ url, options, resolve, reject });
this.processQueue();
});
}
async processQueue() {
if (this.processing || this.queue.length === 0) return;
this.processing = true;
const now = Date.now();
const timeToWait = Math.max(0, this.lastRequestTime + this.interval - now);
await new Promise(resolve => setTimeout(resolve, timeToWait));
const { url, options, resolve, reject } = this.queue.shift();
try {
const response = await fetch(url, options);
resolve(response);
} catch (error) {
reject(error);
} finally {
this.lastRequestTime = Date.now();
this.processing = false;
this.processQueue();
}
}
}
// Usage
const apiClient = new ThrottledApiClient(5); // 5 requests per second
apiClient.request('https://api.bilanc.co/metrics/v2/cycle-time', {
method: 'POST',
headers: { /* ... */ },
body: JSON.stringify({ /* ... */ })
}).then(response => {
// Handle response
});