import { Mapper } from '@automapper/core'; import { InjectMapper } from '@automapper/nestjs'; import { BadRequestException } from '@nestjs/common'; import { CommandBus, CommandHandler } from '@nestjs/cqrs'; import { Messager } from '../../adapters/secondaries/messager'; import { UsernameRepository } from '../../adapters/secondaries/username.repository'; import { AddUsernameCommand } from '../../commands/add-username.command'; import { UpdateUsernameCommand } from '../../commands/update-username.command'; import { AddUsernameRequest } from '../dtos/add-username.request'; import { UpdateUsernameRequest } from '../dtos/update-username.request'; import { Username } from '../entities/username'; @CommandHandler(UpdateUsernameCommand) export class UpdateUsernameUseCase { constructor( private readonly _usernameRepository: UsernameRepository, private readonly _commandBus: CommandBus, @InjectMapper() private readonly _mapper: Mapper, private readonly _messager: Messager, ) {} async execute(command: UpdateUsernameCommand): Promise { const { uuid, username, type } = command.updateUsernameRequest; if (!username) throw new BadRequestException(); // update username if it exists, otherwise create it const existingUsername = await this._usernameRepository.findOne({ uuid, type, }); if (existingUsername) { try { return await this._usernameRepository.updateWhere( { uuid_type: { uuid, type, }, }, { username, }, ); } catch (error) { this._messager.publish( 'logging.auth.username.update.warning', JSON.stringify({ command, error, }), ); throw error; } } const addUsernameRequest = this._mapper.map( command.updateUsernameRequest, UpdateUsernameRequest, AddUsernameRequest, ); try { return await this._commandBus.execute( new AddUsernameCommand(addUsernameRequest), ); } catch (e) { throw e; } } }