UNPKG

traffic-monitor-mqtt

Version:

Zentrales Traffic Monitoring via MQTT für Node.js Anwendungen

68 lines (67 loc) 2.24 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.EventBatcher = void 0; const debug_1 = __importDefault(require("debug")); const log = (0, debug_1.default)('traffic-monitor:event-batcher'); class EventBatcher { constructor(mqttHandler, batchSize = 10, flushInterval = 1000) { this.mqttHandler = mqttHandler; this.batchSize = batchSize; this.flushInterval = flushInterval; this.events = []; this.flushTimeout = null; } async addEvent(event) { // Für Tests: Sofort senden if (process.env.NODE_ENV === 'test') { await this.mqttHandler.publishEvent(event); return; } // Normaler Batch-Modus this.events.push(event); log('Event added to batch:', event); if (this.events.length >= this.batchSize) { await this.flush(); } else if (!this.flushTimeout) { this.flushTimeout = setTimeout(() => this.flush(), this.flushInterval); if (this.flushTimeout.unref) { this.flushTimeout.unref(); } } } async flush() { if (this.flushTimeout) { clearTimeout(this.flushTimeout); this.flushTimeout = null; } if (this.events.length === 0) { return; } const eventsToSend = [...this.events]; this.events = []; try { for (const event of eventsToSend) { await this.mqttHandler.publishEvent(event); } log('Batch flushed successfully:', eventsToSend.length, 'events'); } catch (error) { log('Error flushing batch:', error); // Füge die Events wieder zur Warteschlange hinzu this.events.unshift(...eventsToSend); throw error; } } async stop() { if (this.flushTimeout) { clearTimeout(this.flushTimeout); this.flushTimeout = null; } await this.flush(); } } exports.EventBatcher = EventBatcher;