UNPKG

@vpriem/kafka-broker

Version:

Easily compose and manage your kafka resources in one place

72 lines 2.89 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ProducerContainer = void 0; const events_1 = __importDefault(require("events")); const BatchProducer_1 = require("./BatchProducer"); const BrokerError_1 = require("./BrokerError"); class ProducerContainer extends events_1.default { kafka; config; producers = {}; batchProducers = {}; constructor(kafka, config) { super({ captureRejections: true }); this.kafka = kafka; this.config = config; } async createAndConnect({ kafka: kafkaName, producer: producerConfig, }) { const producer = this.kafka.producer(kafkaName, producerConfig); Object.values(producer.events).forEach((eventName) => { producer.on(eventName, (event) => this.emit(eventName, event)); }); await producer.connect(); return producer; } async create(name) { if (typeof this.producers[name] === 'undefined') { const producerConfig = this.config[name]; if (typeof producerConfig === 'undefined') { throw new BrokerError_1.BrokerError(`Unknown producer "${name}"`); } this.producers[name] = this.createAndConnect(producerConfig); } return this.producers[name]; } batchProducer(name, producer) { if (typeof this.batchProducers[name] === 'undefined') { const { batch: batchConfig } = this.config[name]; this.batchProducers[name] = batchConfig ? new BatchProducer_1.BatchProducer(producer, batchConfig).on('batch.start', (event) => this.emit('producer.batch.start', event)) : null; } return this.batchProducers[name]; } async publish(name, record) { const producer = await this.create(name); const batchProducer = this.batchProducer(name, producer); if (batchProducer) { batchProducer.push(record); return null; } if ((0, BatchProducer_1.isProducerBatch)(record)) { this.emit('producer.batch.start', record); return producer.sendBatch(record); } return producer.send(record); } async disconnect() { const { producers, batchProducers } = this; this.producers = {}; this.batchProducers = {}; await Promise.all(Object.values(batchProducers).map((batchProducer) => batchProducer?.flush())); await Promise.all(Object.values(producers).map(async (getProducer) => { const producer = await getProducer; return producer.disconnect(); })); } } exports.ProducerContainer = ProducerContainer; //# sourceMappingURL=ProducerContainer.js.map