import { RabbitSubscribe } from '@golevelup/nestjs-rabbitmq'; import { Controller } from '@nestjs/common'; import { Ad } from '../../domain/entities/ad'; import { InjectMapper } from '@automapper/nestjs'; import { Mapper } from '@automapper/core'; import { CommandBus } from '@nestjs/cqrs'; import { CreateAdCommand } from '../../commands/create-ad.command'; import { CreateAdRequest } from '../../domain/dtos/create-ad.request'; import { ValidationError, validateOrReject } from 'class-validator'; @Controller() export class AdMessagerController { constructor( private readonly commandBus: CommandBus, @InjectMapper() private readonly mapper: Mapper, ) {} @RabbitSubscribe({ name: 'adCreated', }) async adCreatedHandler(message: string): Promise { try { // parse message to conform to CreateAdRequest (not a real instance yet) const parsedMessage: CreateAdRequest = JSON.parse(message); console.log(parsedMessage); // create a real instance of CreateAdRequest from parsed message const createAdRequest: CreateAdRequest = this.mapper.map( parsedMessage, CreateAdRequest, CreateAdRequest, ); console.log(createAdRequest); // validate instance await validateOrReject(createAdRequest); const ad: Ad = await this.commandBus.execute( new CreateAdCommand(createAdRequest), ); console.log(ad); } catch (e) { if (Array.isArray(e)) { e.forEach((error) => error instanceof ValidationError ? console.log(error.constraints) : console.log(error), ); } } } }