import { Mapper } from '@automapper/core'; import { InjectMapper } from '@automapper/nestjs'; import { CommandHandler } from '@nestjs/cqrs'; import { LoggingMessager } from '../../adapters/secondaries/logging.messager'; import { UserMessager } from '../../adapters/secondaries/user.messager'; 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'; @CommandHandler(CreateUserCommand) export class CreateUserUseCase { constructor( private readonly _repository: UsersRepository, private readonly _userMessager: UserMessager, private readonly _loggingMessager: LoggingMessager, @InjectMapper() private readonly _mapper: Mapper, ) {} async execute(command: CreateUserCommand): Promise { const entity = this._mapper.map( command.createUserRequest, CreateUserRequest, User, ); try { const user = await this._repository.create(entity); this._userMessager.publish('create', JSON.stringify(user)); this._loggingMessager.publish('user.create.info', JSON.stringify(user)); return user; } catch (error) { this._loggingMessager.publish( 'user.create.critical', JSON.stringify({ command, error, }), ); throw error; } } }