summaryrefslogtreecommitdiff
path: root/apps/web/lib/queries/use-mark-all-as-read.ts
blob: fdda661b6053f8958f3691b225ea59fe91424002 (plain) (blame)
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
"use client"

import { useMutation, useQueryClient } from "@tanstack/react-query"
import { createSupabaseBrowserClient } from "@/lib/supabase/client"
import { queryKeys } from "./query-keys"
import { notify } from "@/lib/notify"

export function useMarkAllAsRead() {
  const supabaseClient = createSupabaseBrowserClient()
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async ({
      feedIdentifier,
      folderIdentifier,
      readState = true,
    }: {
      feedIdentifier?: string | null
      folderIdentifier?: string | null
      readState?: boolean
    } = {}) => {
      const { data, error } = await supabaseClient.rpc("mark_all_as_read", {
        p_feed_id: feedIdentifier ?? null,
        p_folder_id: folderIdentifier ?? null,
        p_read_state: readState,
      })

      if (error) throw error

      return data as number
    },
    onSuccess: (affectedCount, variables) => {
      queryClient.invalidateQueries({ queryKey: queryKeys.timeline.all })
      queryClient.invalidateQueries({ queryKey: queryKeys.unreadCounts.all })
      queryClient.invalidateQueries({ queryKey: queryKeys.savedEntries.all })

      const action = variables?.readState === false ? "unread" : "read"

      if (affectedCount > 0) {
        notify(`marked ${affectedCount} entries as ${action}`)
      }
    },
    onError: (_, variables) => {
      const action = variables?.readState === false ? "unread" : "read"
      notify(`failed to mark entries as ${action}`)
    },
  })
}