UNPKG

@goparrot/pubsub-event-bus

Version:
70 lines 2.85 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Producer = void 0; const tslib_1 = require("tslib"); const common_1 = require("@nestjs/common"); const decorator_1 = require("../decorator"); const utils_1 = require("../utils"); const configuration_1 = require("../utils/configuration"); const PubsubManager_1 = require("./PubsubManager"); const PubSubReflector_1 = require("./PubSubReflector"); let Producer = class Producer extends PubsubManager_1.PubsubManager { constructor(reflector, producerOptions) { super(); this.reflector = reflector; this.producerOptions = producerOptions; this.exchanges = new Set(); } async onModuleInit() { if ((0, utils_1.appInTestingMode)()) { return; } this.initConnectionIfRequired(); this.initChannelIfRequired(); } async produce(event) { if ((0, utils_1.appInTestingMode)()) { return; } const metadata = this.reflector.extractEventMetadata(event); if (!metadata) { throw new Error(`Event should be decorated with "${decorator_1.PubsubEvent.name}"`); } const { exchange, customRoutingKey } = metadata; if (!this.exchanges.has(exchange)) { await this.channelWrapper.addSetup(async (channel) => channel.assertExchange(exchange, 'topic', this.assertExchangeOptions)); this.exchanges.add(exchange); } const routingKey = customRoutingKey !== null && customRoutingKey !== void 0 ? customRoutingKey : (0, utils_1.toEventName)(event.constructor.name); const headers = { ...this.headers(event.getOptions()), type: routingKey }; const message = `Event "${routingKey}" to "${exchange}" with ${JSON.stringify({ event, headers })}`; try { await this.channelWrapper.publish(exchange, routingKey, event.payload, headers); this.logger().log(`${message} -> PUBLISHED.`); } catch (e) { if (e instanceof Error) { this.logger().error(`${message} -> FAILED TO PUBLISH -> [${e.message}]`, e.stack); } else { this.logger().error(`${message} -> FAILED TO PUBLISH -> [${JSON.stringify(e)}]`); } } } headers(extra) { return { ...this.producerConfiguration(), ...extra, }; } producerConfiguration() { return this.producerOptions; } }; exports.Producer = Producer; exports.Producer = Producer = tslib_1.__decorate([ (0, common_1.Injectable)(), tslib_1.__param(1, (0, common_1.Inject)(configuration_1.CQRS_PRODUCER_CONFIG)), tslib_1.__metadata("design:paramtypes", [PubSubReflector_1.PubSubReflector, Object]) ], Producer); //# sourceMappingURL=Producer.js.map