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 '../../../geography/adapters/secondaries/geo-timezone-finder'; import { plainToInstance } from 'class-transformer'; import { DefaultParamsProvider } from '../secondaries/default-params.provider'; import { GeorouterCreator } from '../../../geography/adapters/secondaries/georouter-creator'; @Controller() export class AdMessagerController { constructor( private readonly messager: Messager, private readonly commandBus: CommandBus, @InjectMapper() private readonly mapper: Mapper, private readonly defaultParamsProvider: DefaultParamsProvider, private readonly georouterCreator: GeorouterCreator, private readonly timezoneFinder: GeoTimezoneFinder, ) {} @RabbitSubscribe({ name: 'adCreated', }) async adCreatedHandler(message: string): Promise { try { 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; } } createAdRequest.timezone = this.timezoneFinder.timezones( createAdRequest.waypoints[0].lon, createAdRequest.waypoints[0].lat, )[0]; const ad: Ad = await this.commandBus.execute( new CreateAdCommand( createAdRequest, this.defaultParamsProvider.getParams(), this.georouterCreator, this.timezoneFinder, ), ); console.log(ad); } catch (e) { console.log(e); this.messager.publish( 'logging.matcher.ad.crit', JSON.stringify({ message, error: e, }), ); } } }