user/src/modules/users/domain/usecases/create-user.usecase.ts

48 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-12-14 10:37:13 +00:00
import { Mapper } from '@automapper/core';
import { InjectMapper } from '@automapper/nestjs';
import { CommandHandler } from '@nestjs/cqrs';
2022-12-23 14:14:51 +00:00
import { LoggingMessager } from '../../adapters/secondaries/logging.messager';
2022-12-22 13:24:51 +00:00
import { UserMessager } from '../../adapters/secondaries/user.messager';
2022-12-14 10:37:13 +00:00
import { UsersRepository } from '../../adapters/secondaries/users.repository';
import { CreateUserCommand } from '../../commands/create-user.command';
2022-12-16 16:31:08 +00:00
import { CreateUserRequest } from '../dtos/create-user.request';
2022-12-14 10:37:13 +00:00
import { User } from '../entities/user';
@CommandHandler(CreateUserCommand)
export class CreateUserUseCase {
constructor(
private readonly _repository: UsersRepository,
2022-12-23 14:14:51 +00:00
private readonly _userMessager: UserMessager,
private readonly _loggingMessager: LoggingMessager,
2022-12-14 10:37:13 +00:00
@InjectMapper() private readonly _mapper: Mapper,
) {}
async execute(command: CreateUserCommand): Promise<User> {
const entity = this._mapper.map(
command.createUserRequest,
CreateUserRequest,
User,
);
2022-12-23 14:14:51 +00:00
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) {
2022-12-26 14:23:53 +00:00
let key = 'user.create.crit';
if (error.message.includes('Already exists')) {
key = 'user.create.warning';
}
2022-12-23 14:14:51 +00:00
this._loggingMessager.publish(
2022-12-26 14:23:53 +00:00
key,
2022-12-23 14:14:51 +00:00
JSON.stringify({
command,
error,
}),
);
throw error;
2022-12-22 13:24:51 +00:00
}
2022-12-14 10:37:13 +00:00
}
}