import { Mapper } from '@automapper/core'; import { InjectMapper } from '@automapper/nestjs'; import { CommandHandler } from '@nestjs/cqrs'; import { UsersRepository } from '../../adapters/secondaries/users.repository'; import { CreateUserCommand } from '../../commands/create-user.command'; import { CreateUserRequest } from '../dtos/create-user.request'; import { User } from '../entities/user'; import { Inject } from '@nestjs/common'; import { MESSAGE_PUBLISHER } from '../../../../app.constants'; import { IPublishMessage } from '../../../../interfaces/message-publisher'; @CommandHandler(CreateUserCommand) export class CreateUserUseCase { constructor( private readonly repository: UsersRepository, @Inject(MESSAGE_PUBLISHER) private readonly messagePublisher: IPublishMessage, @InjectMapper() private readonly mapper: Mapper, ) {} execute = async (command: CreateUserCommand): Promise => { const entity = this.mapper.map( command.createUserRequest, CreateUserRequest, User, ); try { const user = await this.repository.create(entity); this.messagePublisher.publish('user.create', JSON.stringify(user)); this.messagePublisher.publish( 'logging.user.create.info', JSON.stringify(user), ); return user; } catch (error) { let key = 'logging.user.create.crit'; if (error.message.includes('Already exists')) { key = 'logging.user.create.warning'; } this.messagePublisher.publish( key, JSON.stringify({ command, error, }), ); throw error; } }; }