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

81 lines
2.5 KiB
TypeScript

import { RabbitSubscribe } from '@golevelup/nestjs-rabbitmq';
import { Controller } from '@nestjs/common';
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 { plainToInstance } from 'class-transformer';
import { DatabaseException } from 'src/modules/database/exceptions/database.exception';
import { ExceptionCode } from 'src/modules/utils/exception-code.enum';
@Controller()
export class AdMessagerController {
constructor(
private readonly messager: Messager,
private readonly commandBus: CommandBus,
) {}
@RabbitSubscribe({
name: 'adCreated',
})
async adCreatedHandler(message: string): Promise<void> {
let createAdRequest: CreateAdRequest;
// parse message to request instance
try {
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;
}
}
} catch (e) {
this.messager.publish(
'matcher.ad.crit',
JSON.stringify({
message: `Can't validate message : ${message}`,
error: e,
}),
);
}
try {
await this.commandBus.execute(new CreateAdCommand(createAdRequest));
} catch (e) {
if (e instanceof DatabaseException) {
if (e.message.includes('already exists')) {
this.messager.publish(
'matcher.ad.crit',
JSON.stringify({
code: ExceptionCode.ALREADY_EXISTS,
message: 'Already exists',
uuid: createAdRequest.uuid,
}),
);
}
if (e.message.includes("Can't reach database server")) {
this.messager.publish(
'matcher.ad.crit',
JSON.stringify({
code: ExceptionCode.UNAVAILABLE,
message: 'Database server unavailable',
uuid: createAdRequest.uuid,
}),
);
}
}
this.messager.publish(
'logging.matcher.ad.crit',
JSON.stringify({
message,
error: e,
}),
);
}
}
}