@goparrot/pubsub-event-bus
Version:
NestJS EventBus extension for RabbitMQ PubSub
67 lines • 2.56 kB
JavaScript
import { __decorate, __metadata, __param } from "tslib";
import { Inject, Injectable } from '@nestjs/common';
import { PubsubEvent } from '../decorator';
import { appInTestingMode, toEventName } from '../utils';
import { CQRS_PRODUCER_CONFIG } from '../utils/configuration';
import { PubsubManager } from './PubsubManager';
import { PubSubReflector } from './PubSubReflector';
let Producer = class Producer extends PubsubManager {
constructor(reflector, producerOptions) {
super();
this.reflector = reflector;
this.producerOptions = producerOptions;
this.exchanges = new Set();
}
async onModuleInit() {
if (appInTestingMode()) {
return;
}
this.initConnectionIfRequired();
this.initChannelIfRequired();
}
async produce(event) {
if (appInTestingMode()) {
return;
}
const metadata = this.reflector.extractEventMetadata(event);
if (!metadata) {
throw new Error(`Event should be decorated with "${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 ?? 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;
}
};
Producer = __decorate([
Injectable(),
__param(1, Inject(CQRS_PRODUCER_CONFIG)),
__metadata("design:paramtypes", [PubSubReflector, Object])
], Producer);
export { Producer };
//# sourceMappingURL=Producer.js.map