Skip to content

Commit

Permalink
chore: Add guard guardUserDoesNotExists in CreateUserCommandHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
mapeveri committed Apr 21, 2024
1 parent 9ad98d2 commit 193add8
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,25 @@ import Email from '@src/shared/domain/valueObjects/email';
import User from '@src/languages/domain/user/user';
import { Inject } from '@src/shared/domain/injector/inject.decorator';
import { CommandHandler, ICommandHandler } from '@src/shared/domain/bus/commandBus/commandHandler';
import UserAlreadyExistsException from '@src/languages/domain/user/userAlreadyExistsException';

@CommandHandler(CreateUserCommand)
export default class CreateUserCommandHandler implements ICommandHandler<CreateUserCommand> {
constructor(@Inject(USER_REPOSITORY) private readonly userRepository: UserRepository) {}

async execute(command: CreateUserCommand): Promise<void> {
const user = User.create(
UserId.of(command.id),
command.name,
command.provider,
Email.of(command.email),
command.photo,
);
const userId = UserId.of(command.id);
await this.guardUserDoesNotExists(userId);

const user = User.create(userId, command.name, command.provider, Email.of(command.email), command.photo);

await this.userRepository.save(user);
}

private async guardUserDoesNotExists(userId: UserId): Promise<void> {
const user = await this.userRepository.findById(userId);
if (!user) {
throw new UserAlreadyExistsException(userId.value);
}
}
}
7 changes: 7 additions & 0 deletions src/languages/domain/user/userAlreadyExistsException.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import ConflictException from '@src/shared/domain/exceptions/conflictException';

export default class UserAlreadyExistsException extends ConflictException {
constructor(id: string) {
super(`User with id ${id} already exists`, 'user_already_exists');
}
}

0 comments on commit 193add8

Please sign in to comment.