import { CommandHandler } from '@nestjs/cqrs'; import { AuthenticationRepository } from '../../adapters/secondaries/authentication.repository'; import { CreateAuthenticationCommand } from '../../commands/create-authentication.command'; import { Authentication } from '../entities/authentication'; import * as bcrypt from 'bcrypt'; import { UsernameRepository } from '../../adapters/secondaries/username.repository'; import { LoggingMessager } from '../../adapters/secondaries/logging.messager'; @CommandHandler(CreateAuthenticationCommand) export class CreateAuthenticationUseCase { constructor( private readonly _authenticationRepository: AuthenticationRepository, private readonly _usernameRepository: UsernameRepository, private readonly _loggingMessager: LoggingMessager, ) {} async execute(command: CreateAuthenticationCommand): Promise { const { uuid, password, ...username } = command.createAuthenticationRequest; const hash = await bcrypt.hash(password, 10); try { const auth = await this._authenticationRepository.create({ uuid, password: hash, }); await this._usernameRepository.create({ uuid, ...username, }); return auth; } catch (error) { this._loggingMessager.publish( 'auth.create.crit', JSON.stringify({ command, error, }), ); throw error; } } }