All files / src/application/specialist update-specialist.use-case.ts

100% Statements 9/9
92.85% Branches 13/14
100% Functions 2/2
100% Lines 9/9

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                                    25x 25x       6x                   6x 2x     4x                 4x                     6x   3x      
import { BabyGuardianRepository } from '../baby/baby-guardian-repository';
import { Specialist } from '../../domain/specialist/specialist';
import { SpecialistRepository } from './specialist-repository';
import { SpecialistNotFoundError } from './errors/specialist-not-found.error';
import { resolveSpecialistLinks } from './resolve-specialist-links';
 
export interface UpdateSpecialistInput {
  specialistId: string;
  requestingUserId: string;
  name?: string;
  specialty?: string | null;
  phone?: string | null;
  babyIds?: string[];
  sharedWithUserIds?: string[];
}
 
export class UpdateSpecialistUseCase {
  constructor(
    private readonly babyGuardianRepository: BabyGuardianRepository,
    private readonly specialistRepository: SpecialistRepository,
  ) {}
 
  async execute(input: UpdateSpecialistInput): Promise<Specialist> {
    const existing = await this.specialistRepository.findById(input.specialistId);
 
    /**
     * Only the owner edits, and the answer to "not yours" is 404 rather than 403.
     *
     * Seeing an entry — through a child, or because it was shared — does not make it yours to
     * rewrite: the phone number a co-guardian relies on should not change under them because
     * somebody else tidied their own list. A 403 would also confirm the id exists to whoever
     * guessed it.
     */
    if (!existing || existing.userId !== input.requestingUserId) {
      throw new SpecialistNotFoundError();
    }
 
    const links = await resolveSpecialistLinks(
      this.babyGuardianRepository,
      input.requestingUserId,
      // Absent means "leave the links alone"; an empty array means "no child", which is a real
      // answer and has to survive the difference.
      input.babyIds ?? existing.babyIds,
      input.sharedWithUserIds ?? existing.sharedWithUserIds,
    );
 
    const updated = Specialist.register({
      id: existing.id,
      userId: existing.userId,
      name: input.name ?? existing.name,
      specialty: input.specialty !== undefined ? input.specialty : existing.specialty,
      phone: input.phone !== undefined ? input.phone : existing.phone,
      babyIds: links.babyIds,
      sharedWithUserIds: links.sharedWithUserIds,
      createdAt: existing.createdAt,
    });
 
    await this.specialistRepository.save(updated);
 
    return updated;
  }
}