2023-04-24 14:44:52 +00:00
|
|
|
import { RabbitSubscribe } from '@golevelup/nestjs-rabbitmq';
|
|
|
|
import { Controller } from '@nestjs/common';
|
2023-04-25 15:49:47 +00:00
|
|
|
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';
|
2023-04-26 10:10:22 +00:00
|
|
|
import { ValidationError, validateOrReject } from 'class-validator';
|
2023-04-24 14:44:52 +00:00
|
|
|
|
|
|
|
@Controller()
|
|
|
|
export class AdMessagerController {
|
2023-04-25 15:49:47 +00:00
|
|
|
constructor(
|
2023-04-26 10:10:22 +00:00
|
|
|
private readonly commandBus: CommandBus,
|
|
|
|
@InjectMapper() private readonly mapper: Mapper,
|
2023-04-25 15:49:47 +00:00
|
|
|
) {}
|
|
|
|
|
2023-04-24 14:44:52 +00:00
|
|
|
@RabbitSubscribe({
|
|
|
|
name: 'adCreated',
|
|
|
|
})
|
2023-04-26 10:10:22 +00:00
|
|
|
async adCreatedHandler(message: string): Promise<void> {
|
2023-04-25 15:49:47 +00:00
|
|
|
try {
|
2023-04-26 10:10:22 +00:00
|
|
|
// parse message to conform to CreateAdRequest (not a real instance yet)
|
|
|
|
const parsedMessage: CreateAdRequest = JSON.parse(message);
|
2023-04-26 12:14:46 +00:00
|
|
|
console.log(parsedMessage);
|
2023-04-26 10:10:22 +00:00
|
|
|
// create a real instance of CreateAdRequest from parsed message
|
2023-04-27 15:52:43 +00:00
|
|
|
// const createAdRequest: CreateAdRequest = this.mapper.map(
|
|
|
|
// parsedMessage,
|
|
|
|
// CreateAdRequest,
|
|
|
|
// CreateAdRequest,
|
|
|
|
// );
|
|
|
|
const createAdRequest = new CreateAdRequest();
|
|
|
|
createAdRequest.originType = parsedMessage.originType;
|
|
|
|
createAdRequest.destinationType = parsedMessage.destinationType;
|
|
|
|
createAdRequest.waypoints = parsedMessage.waypoints.map((waypoint) => ({
|
|
|
|
lon: waypoint.lon,
|
|
|
|
lat: waypoint.lat,
|
|
|
|
}));
|
2023-04-26 10:10:22 +00:00
|
|
|
console.log(createAdRequest);
|
|
|
|
// validate instance
|
2023-04-27 15:52:43 +00:00
|
|
|
await validateOrReject(createAdRequest.waypoints[0]);
|
2023-04-26 10:10:22 +00:00
|
|
|
const ad: Ad = await this.commandBus.execute(
|
2023-04-25 15:49:47 +00:00
|
|
|
new CreateAdCommand(createAdRequest),
|
|
|
|
);
|
2023-04-26 10:10:22 +00:00
|
|
|
console.log(ad);
|
2023-04-25 15:49:47 +00:00
|
|
|
} catch (e) {
|
2023-04-26 10:10:22 +00:00
|
|
|
if (Array.isArray(e)) {
|
|
|
|
e.forEach((error) =>
|
|
|
|
error instanceof ValidationError
|
|
|
|
? console.log(error.constraints)
|
|
|
|
: console.log(error),
|
|
|
|
);
|
|
|
|
}
|
2023-04-25 15:49:47 +00:00
|
|
|
}
|
2023-04-24 14:44:52 +00:00
|
|
|
}
|
|
|
|
}
|