add analytics
This commit is contained in:
62
app/src/services/analytics/EventBatcher.js
Normal file
62
app/src/services/analytics/EventBatcher.js
Normal file
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* 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 = [];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user