import { RabbitSubscribe } from '@golevelup/nestjs-rabbitmq'; import { Controller } from '@nestjs/common'; import { Ad } from '../../domain/entities/ad'; import { CommandBus } from '@nestjs/cqrs'; import { CreateAdCommand } from '../../commands/create-ad.command'; import { CreateAdRequest } from '../../domain/dtos/create-ad.request'; import { validateOrReject } from 'class-validator'; import { Messager } from '../secondaries/messager'; import { plainToInstance } from 'class-transformer'; @Controller() export class AdMessagerController { constructor( private readonly messager: Messager, private readonly commandBus: CommandBus, ) {} @RabbitSubscribe({ name: 'adCreated', }) async adCreatedHandler(message: string): Promise { try { // parse message to request instance const createAdRequest: CreateAdRequest = plainToInstance( CreateAdRequest, JSON.parse(message), ); // validate instance await validateOrReject(createAdRequest); // validate nested objects (fixes direct nested validation bug) for (const waypoint of createAdRequest.waypoints) { try { await validateOrReject(waypoint); } catch (e) { throw e; } } const ad: Ad = await this.commandBus.execute( new CreateAdCommand(createAdRequest), ); console.log(ad); } catch (e) { console.log(e); this.messager.publish( 'logging.matcher.ad.crit', JSON.stringify({ message, error: e, }), ); } } }