tianji-client-sdk
Version:
97 lines (96 loc) • 2.72 kB
JavaScript
"use strict";
/**
* Generic Batch Manager for request batching
* Provides throttling and automatic batch sending functionality
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BatchManager = void 0;
class BatchManager {
queue = [];
timer = null;
options;
constructor(options) {
this.options = {
batchDelay: 200,
maxBatchSize: 100,
disableBatch: false,
...options,
};
}
/**
* Add item to batch queue
*/
add(type, payload) {
if (this.options.disableBatch) {
// Fire and forget, but catch errors to prevent unhandled promise rejection
this.options.onSingleSend({ type, payload }).catch((error) => {
console.error('Error in onSingleSend:', error);
});
return;
}
this.queue.push({ type, payload });
// Send immediately if queue reaches the limit
if (this.queue.length >= (this.options.maxBatchSize || 100)) {
// Fire and forget, but catch errors to prevent unhandled promise rejection
this.flush().catch((error) => {
console.error('Error in auto-flush:', error);
});
return;
}
// Start timer only if not already running (throttling behavior)
if (!this.timer) {
this.timer = setTimeout(() => {
this.sendBatch().catch((error) => {
console.error('Error in scheduled batch send:', error);
});
}, this.options.batchDelay);
}
}
/**
* Send batch request
*/
async sendBatch() {
if (this.queue.length === 0) {
return;
}
const requestData = [...this.queue];
this.queue = [];
this.timer = null;
await this.options.onBatchSend(requestData);
}
/**
* Flush batch queue manually (send all pending requests immediately)
*/
async flush() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
if (this.queue.length > 0) {
await this.sendBatch();
}
}
/**
* Clear batch queue without sending
*/
clear() {
this.queue = [];
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
/**
* Update batch manager options
*/
updateOptions(options) {
this.options = { ...this.options, ...options };
}
/**
* Get current queue size
*/
getQueueSize() {
return this.queue.length;
}
}
exports.BatchManager = BatchManager;