All files / src/features/medications/api medications.hooks.ts

89.74% Statements 35/39
64% Branches 16/25
86.66% Functions 26/30
94.28% Lines 33/35

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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141                              162x             1x       26x                                                         167x 167x   167x 158x   27x           167x 158x 158x               167x     158x     158x         91x   91x 2x   1x               91x   91x   1x   1x 1x             18x   18x   2x   1x 1x             91x   91x 2x   1x 1x          
import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query'
 
import { useBabies } from '@/features/babies/api/babies.hooks'
import type { Baby } from '@/features/babies/api/babies.schemas'
 
import {
  createMedication,
  deleteMedication,
  endMedication,
  fetchMedications,
  updateMedication,
} from './medications.api'
import type { Medication, MedicationFormInput } from './medications.schemas'
 
export function medicationsQueryKey(babyId: string) {
  return ['babies', babyId, 'medications'] as const
}
 
// Most recently started first, matching what the API already sends. The order is repeated here
// because optimistic cache writes below insert into an existing list, and a list that drifts out
// of order between a write and the next fetch reads as the app losing track of the record.
function byNewestFirst(a: Medication, b: Medication) {
  return b.startedOn.localeCompare(a.startedOn)
}
 
function sortByNewestFirst(items: Medication[]): Medication[] {
  return [...items].sort(byNewestFirst)
}
 
export function useMedications(babyId: string | null) {
  return useQuery({
    queryKey: medicationsQueryKey(babyId ?? ''),
    queryFn: () => fetchMedications(babyId!),
    enabled: !!babyId,
    select: sortByNewestFirst,
  })
}
 
export interface BabyMedicationsEntry {
  baby: Baby
  items: Medication[]
  isPending: boolean
  isError: boolean
}
 
export interface AllBabiesMedications {
  babies: Baby[]
  isPending: boolean
  isError: boolean
  isEmpty: boolean
  perBaby: BabyMedicationsEntry[]
  items: Medication[]
}
 
export function useAllBabiesMedications(): AllBabiesMedications {
  const babies = useBabies()
  const babyList = babies.data ?? []
 
  const results = useQueries({
    queries: babyList.map((baby) => ({
      queryKey: medicationsQueryKey(baby.id),
      queryFn: () => fetchMedications(baby.id),
      enabled: babies.isSuccess,
      select: sortByNewestFirst,
    })),
  })
 
  const perBaby: BabyMedicationsEntry[] = babyList.map((baby, index) => {
    const result = results[index]
    return {
      baby,
      items: result?.data ?? [],
      isPending: result?.isPending ?? true,
      isError: result?.isError ?? false,
    }
  })
 
  return {
    babies: babyList,
    isPending: babies.isPending || (babies.isSuccess && results.some((result) => result.isPending)),
    isError: babies.isError || results.some((result) => result.isError),
    isEmpty: babies.isSuccess && babyList.length === 0,
    perBaby,
    items: perBaby.flatMap((entry) => entry.items),
  }
}
 
export function useCreateMedication(babyId: string | null) {
  const queryClient = useQueryClient()
 
  return useMutation({
    mutationFn: (input: MedicationFormInput) => createMedication(babyId!, input),
    onSuccess: (medication) => {
      queryClient.setQueryData<Medication[]>(medicationsQueryKey(babyId ?? ''), (prev) =>
        (prev ? [...prev, medication] : [medication]).sort(byNewestFirst),
      )
    },
  })
}
 
export function useUpdateMedication(babyId: string) {
  const queryClient = useQueryClient()
 
  return useMutation({
    mutationFn: ({ medicationId, input }: { medicationId: string; input: MedicationFormInput }) =>
      updateMedication(babyId, medicationId, input),
    onSuccess: (medication) => {
      queryClient.setQueryData<Medication[]>(medicationsQueryKey(babyId), (prev) =>
        prev?.map((item) => (item.id === medication.id ? medication : item)).sort(byNewestFirst),
      )
    },
  })
}
 
export function useEndMedication(babyId: string) {
  const queryClient = useQueryClient()
 
  return useMutation({
    mutationFn: ({ medicationId, endedOn }: { medicationId: string; endedOn: string }) =>
      endMedication(babyId, medicationId, endedOn),
    onSuccess: (medication) => {
      queryClient.setQueryData<Medication[]>(medicationsQueryKey(babyId), (prev) =>
        prev?.map((item) => (item.id === medication.id ? medication : item)),
      )
    },
  })
}
 
export function useDeleteMedication(babyId: string) {
  const queryClient = useQueryClient()
 
  return useMutation({
    mutationFn: (medicationId: string) => deleteMedication(babyId, medicationId),
    onSuccess: (_data, deletedId) => {
      queryClient.setQueryData<Medication[]>(medicationsQueryKey(babyId), (prev) =>
        prev?.filter((item) => item.id !== deletedId),
      )
    },
  })
}