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 { validateOrReject } from 'class-validator'; import { Messager } from '../secondaries/messager'; import { GeoTimezoneFinder } from 'src/modules/geography/adapters/secondaries/geo-timezone-finder'; @Controller() export class AdMessagerController { constructor( private readonly messager: Messager, private readonly commandBus: CommandBus, @InjectMapper() private readonly mapper: Mapper, private readonly timezoneFinder: GeoTimezoneFinder, ) {} @RabbitSubscribe({ name: 'adCreated', }) async adCreatedHandler(message: string): Promise { let createAdRequest: CreateAdRequest; try { // parse message to conform to CreateAdRequest (not a real instance yet) const parsedMessage: CreateAdRequest = JSON.parse(message); // create a real instance of CreateAdRequest from parsed message createAdRequest = this.mapper.map( parsedMessage, CreateAdRequest, CreateAdRequest, ); // 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; } } createAdRequest.timezone = this.timezoneFinder.timezones( createAdRequest.waypoints[0].lon, createAdRequest.waypoints[0].lat, )[0]; const ad: Ad = await this.commandBus.execute( new CreateAdCommand(createAdRequest), ); console.log(ad); } catch (e) { this.messager.publish( 'logging.matcher.ad.crit', JSON.stringify({ createAdRequest, error: e, }), ); } } }