/** * Batcher class to batch data and send it to the server * @author [Vivek Sudarsan] * @version 0.1.0 */ export class Batcher { private queue: any[] = []; private batchSize: number; private delay: number; private callback: any; private timer: ReturnType | null = null; /** * Create a new Batcher instance with the given batch size and delay * @param batchSize * @param delay */ constructor(batchSize: number, delay: number, callback: any) { this.batchSize = batchSize; this.delay = delay; this.callback = callback; } /** * Add data to the queue * @param data */ addToQueue(data: any) { this.queue = [...this.queue, ...data]; if (this.queue.length >= this.batchSize) { this.sendBatch(); } else if (!this.timer) { this.timer = setTimeout(() => this.sendBatch(), this.delay); } } /** * Send the current batch to the server * and clear the queue. Retry failed requests. */ private async sendBatch() { if (this.timer) { clearTimeout(this.timer); this.timer = null; } const batch = this.queue.splice(0, this.batchSize); try { await this.callback(batch); } catch (error) { console.error('Failed to send batch', error); // For now not retrying failed requests // uncomment below code to retry failed requests // this.queue = [...batch, ...this.queue]; } if (this.queue.length > 0) { this.timer = setTimeout(() => this.sendBatch(), this.delay); } } }