matcher/src/modules/ad/adapters/primaries/ad-messager.controller.ts

57 lines
2.0 KiB
TypeScript
Raw Normal View History

2023-04-24 14:44:52 +00:00
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';
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 {
constructor(
2023-04-26 10:10:22 +00:00
private readonly commandBus: CommandBus,
@InjectMapper() private readonly mapper: Mapper,
) {}
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> {
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(
new CreateAdCommand(createAdRequest),
);
2023-04-26 10:10:22 +00:00
console.log(ad);
} 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-24 14:44:52 +00:00
}
}