user/.old/domain/usecases/create-user.usecase.ts

52 lines
1.6 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';
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';
import { Inject } from '@nestjs/common';
import { MESSAGE_PUBLISHER } from '../../../../app.constants';
import { IPublishMessage } from '../../../../interfaces/message-publisher';
2022-12-14 10:37:13 +00:00
@CommandHandler(CreateUserCommand)
export class CreateUserUseCase {
constructor(
2023-05-05 14:56:30 +00:00
private readonly repository: UsersRepository,
@Inject(MESSAGE_PUBLISHER)
private readonly messagePublisher: IPublishMessage,
2023-05-05 14:56:30 +00:00
@InjectMapper() private readonly mapper: Mapper,
2022-12-14 10:37:13 +00:00
) {}
2023-05-05 14:56:30 +00:00
execute = async (command: CreateUserCommand): Promise<User> => {
const entity = this.mapper.map(
2022-12-14 10:37:13 +00:00
command.createUserRequest,
CreateUserRequest,
User,
);
2022-12-23 14:14:51 +00:00
try {
2023-05-05 14:56:30 +00:00
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),
);
2022-12-23 14:14:51 +00:00
return user;
} catch (error) {
let key = 'logging.user.create.crit';
2022-12-26 14:23:53 +00:00
if (error.message.includes('Already exists')) {
key = 'logging.user.create.warning';
2022-12-26 14:23:53 +00:00
}
this.messagePublisher.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
}
2023-05-05 14:56:30 +00:00
};
2022-12-14 10:37:13 +00:00
}