|
| 1 | +import { |
| 2 | + Injectable, |
| 3 | + Logger, |
| 4 | + OnModuleDestroy, |
| 5 | + OnModuleInit, |
| 6 | +} from '@nestjs/common'; |
| 7 | +import { ConfigService } from '@nestjs/config'; |
| 8 | +import { Kafka, Producer } from 'kafkajs'; |
| 9 | +import { TraceEventDto } from './dto/trace-event.dto'; |
| 10 | +import { instanceToPlain } from 'class-transformer'; |
| 11 | +import { TraceMessageDto } from './dto/trace-message.dto'; |
| 12 | + |
| 13 | +@Injectable() |
| 14 | +export class TraceService implements OnModuleInit, OnModuleDestroy { |
| 15 | + private readonly logger = new Logger(TraceService.name); |
| 16 | + private readonly topic?: string; |
| 17 | + private readonly kafka?: Kafka; |
| 18 | + private readonly producer?: Producer; |
| 19 | + |
| 20 | + constructor(private readonly configService: ConfigService) { |
| 21 | + const brokerUrl = this.configService.get<string>('OBB_KAFKA_BROKER'); |
| 22 | + const topic = this.configService.get<string>('OBB_KAFKA_TOPIC'); |
| 23 | + const clientId = this.configService.get<string>('OBB_KAFKA_CLIENT_ID'); |
| 24 | + if (!brokerUrl || !topic || !clientId) { |
| 25 | + return; |
| 26 | + } |
| 27 | + const brokers = brokerUrl.split(','); |
| 28 | + this.topic = topic; |
| 29 | + this.kafka = new Kafka({ |
| 30 | + clientId, |
| 31 | + brokers, |
| 32 | + }); |
| 33 | + this.producer = this.kafka.producer(); |
| 34 | + } |
| 35 | + |
| 36 | + async onModuleInit() { |
| 37 | + if (this.producer) { |
| 38 | + await this.producer.connect(); |
| 39 | + this.logger.log('Kafka producer connected successfully'); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + async onModuleDestroy() { |
| 44 | + if (this.producer) { |
| 45 | + await this.producer.disconnect(); |
| 46 | + this.logger.log('Kafka producer disconnected'); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + async emitTraceEvents( |
| 51 | + events: TraceEventDto[], |
| 52 | + userId?: string, |
| 53 | + userAgent?: string, |
| 54 | + ): Promise<void> { |
| 55 | + if (!this.producer || !this.topic) { |
| 56 | + return; |
| 57 | + } |
| 58 | + const messages = events.map((event) => { |
| 59 | + const dto = TraceMessageDto.fromEvent(event, userId, userAgent); |
| 60 | + return { |
| 61 | + value: JSON.stringify(instanceToPlain(dto)), |
| 62 | + }; |
| 63 | + }); |
| 64 | + await this.producer.send({ |
| 65 | + topic: this.topic, |
| 66 | + messages, |
| 67 | + }); |
| 68 | + } |
| 69 | +} |
0 commit comments