All files / src/application/baby remove-baby-guardian.use-case.ts

100% Statements 14/14
90% Branches 9/10
100% Functions 2/2
100% Lines 14/14

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                              22x 22x       5x   5x       5x   5x 1x     4x 1x     3x 3x   5x 1x     2x      
import { BabyRepository } from './baby-repository';
import { BabyGuardianRepository } from './baby-guardian-repository';
import { ensureBabyAccess } from './ensure-baby-access';
import { GuardianNotFoundError } from './errors/guardian-not-found.error';
import { CannotRemoveOwnerError } from './errors/cannot-remove-owner.error';
import { GuardianForbiddenError } from './errors/guardian-forbidden.error';
 
export interface RemoveBabyGuardianInput {
  babyId: string;
  targetUserId: string;
  requestingUserId: string;
}
 
export class RemoveBabyGuardianUseCase {
  constructor(
    private readonly babyRepository: BabyRepository,
    private readonly babyGuardianRepository: BabyGuardianRepository,
  ) {}
 
  async execute(input: RemoveBabyGuardianInput): Promise<void> {
    await ensureBabyAccess(this.babyRepository, this.babyGuardianRepository, input.babyId, input.requestingUserId);
 
    const requesterGuardian = await this.babyGuardianRepository.findByBabyAndUser(
      input.babyId,
      input.requestingUserId,
    );
    const targetGuardian = await this.babyGuardianRepository.findByBabyAndUser(input.babyId, input.targetUserId);
 
    if (!targetGuardian) {
      throw new GuardianNotFoundError();
    }
 
    if (targetGuardian.role !== 'GUARDIAN') {
      throw new CannotRemoveOwnerError();
    }
 
    const isSelfRemoval = input.requestingUserId === input.targetUserId;
    const requesterIsOwner = requesterGuardian?.isOwner() ?? false;
 
    if (!isSelfRemoval && !requesterIsOwner) {
      throw new GuardianForbiddenError('Only the baby profile owner can remove another guardian');
    }
 
    await this.babyGuardianRepository.delete(input.babyId, input.targetUserId);
  }
}