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

80.76% Statements 21/26
83.33% Branches 10/12
60% Functions 6/10
82.6% Lines 19/23

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            3x           57x                                         37x 37x   6x 6x 6x 7x 7x 3x 3x 6x     4x 3x 1x 1x   2x     5x     6x        
import { ApiError } from '@/lib/http-client'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
 
import { fetchNotifications, markNotificationRead } from './notifications.api'
import type { Notification } from './notifications.schemas'
 
export const notificationsQueryKey = ['notifications'] as const
 
// No websocket/push channel in the contract, and no timed poll either: a poll kept the
// database awake for as long as a tab stayed open. The list refreshes when the app
// loads and when the tab regains focus (React Query's default, once the data is stale).
export function useNotifications() {
  return useQuery({
    queryKey: notificationsQueryKey,
    queryFn: fetchNotifications,
  })
}
 
export function useMarkNotificationRead() {
  const queryClient = useQueryClient()
 
  return useMutation({
    mutationFn: markNotificationRead,
    onSuccess: (updated) => {
      queryClient.setQueryData<Notification[]>(notificationsQueryKey, (prev) =>
        prev?.map((notification) => (notification.id === updated.id ? updated : notification)),
      )
    },
  })
}
 
/** Serialize bulk updates to avoid a request burst against the API rate limit. */
export function useMarkNotificationsRead() {
  const client = useQueryClient()
  return useMutation({
    mutationFn: async (ids: string[]) => {
      let failed = 0
      const uniqueIds = [...new Set(ids)]
      for (const [index, id] of uniqueIds.entries()) {
        try {
          const updated = await markNotificationRead(id)
          await client.cancelQueries({ queryKey: notificationsQueryKey })
          client.setQueryData<Notification[]>(notificationsQueryKey, (previous) =>
            previous?.map((item) => (item.id === updated.id ? updated : item)),
          )
        } catch (error) {
          if (error instanceof ApiError && error.status === 401) throw error
          if (error instanceof ApiError && error.status === 429) {
            failed += uniqueIds.length - index
            break
          }
          failed += 1
        }
      }
      return { failed }
    },
    onSettled: () => {
      void client.invalidateQueries({ queryKey: notificationsQueryKey })
    },
  })
}