Files
decoda/app/src/services/analytics/EventBatcher.js
2026-06-05 00:11:45 -03:00

63 lines
1.4 KiB
JavaScript

/**
* EventBatcher - Acumula eventos e os envia em lotes
* Reduz latência e consumo de banda, melhorando performance em conexões lentas
*/
export class EventBatcher {
constructor(config = {}) {
this.batchSize = config.batchSize || 10; // Envia a cada 10 eventos
this.batchTimeout = config.batchTimeout || 30000; // Ou a cada 30 segundos
this.onBatch = config.onBatch || (() => {}); // Callback quando lote está pronto
this.queue = [];
this.timeoutId = null;
}
add(event) {
if (!event) return;
this.queue.push({
...event,
timestamp: new Date().toISOString(),
});
// Se atingiu tamanho do lote, enviar imediatamente
if (this.queue.length >= this.batchSize) {
this.flush();
} else if (!this.timeoutId) {
// Se não tem timer, iniciar
this.timeoutId = setTimeout(() => this.flush(), this.batchTimeout);
}
}
flush() {
if (this.queue.length === 0) {
if (this.timeoutId) {
clearTimeout(this.timeoutId);
this.timeoutId = null;
}
return;
}
const batch = [...this.queue];
this.queue = [];
if (this.timeoutId) {
clearTimeout(this.timeoutId);
this.timeoutId = null;
}
this.onBatch(batch);
}
getPendingCount() {
return this.queue.length;
}
destroy() {
if (this.timeoutId) {
clearTimeout(this.timeoutId);
}
this.queue = [];
}
}