All files / src/application/user update-user-profile.use-case.ts

100% Statements 18/18
100% Branches 20/20
100% Functions 2/2
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66                                      32x 32x       20x   20x 2x     18x   20x   10x   8x 5x       13x 3x   3x 2x         11x   20x               20x   10x      
import { User } from '../../domain/user/user';
import { UserRepository } from './user-repository';
import { PasswordHasher } from './password-hasher';
import { EmailAlreadyInUseError } from './errors/email-already-in-use.error';
import { IncorrectPasswordError } from './errors/incorrect-password.error';
import { UserNotFoundError } from './errors/user-not-found.error';
 
export interface UpdateUserProfileInput {
  userId: string;
  name?: string;
  avatarUrl?: string | null;
  email?: string;
  password?: string;
  currentPassword?: string;
  emailNotificationsEnabled?: boolean;
}
 
export class UpdateUserProfileUseCase {
  constructor(
    private readonly userRepository: UserRepository,
    private readonly passwordHasher: PasswordHasher,
  ) {}
 
  async execute(input: UpdateUserProfileInput): Promise<User> {
    const existingUser = await this.userRepository.findById(input.userId);
 
    if (!existingUser) {
      throw new UserNotFoundError();
    }
 
    const changesSensitiveField = input.email !== undefined || input.password !== undefined;
 
    if (changesSensitiveField) {
      const isCurrentPasswordValid =
        !!input.currentPassword && (await this.passwordHasher.compare(input.currentPassword, existingUser.passwordHash));
 
      if (!isCurrentPasswordValid) {
        throw new IncorrectPasswordError();
      }
    }
 
    if (input.email !== undefined && input.email !== existingUser.email) {
      const otherUser = await this.userRepository.findByEmail(input.email);
 
      if (otherUser && otherUser.id !== existingUser.id) {
        throw new EmailAlreadyInUseError(input.email);
      }
    }
 
    const passwordHash =
      input.password !== undefined ? await this.passwordHasher.hash(input.password) : existingUser.passwordHash;
 
    const updatedUser = existingUser.withProfile({
      name: input.name,
      email: input.email,
      passwordHash,
      avatarUrl: input.avatarUrl,
      emailNotificationsEnabled: input.emailNotificationsEnabled,
    });
 
    await this.userRepository.save(updatedUser);
 
    return updatedUser;
  }
}