summaryrefslogtreecommitdiff
path: root/apps/web/lib/queries/use-muted-keyword-mutations.ts
blob: 0b92dbd96e3a584fd56a089632f4c7b18b58bb64 (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"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 useAddMutedKeyword() {
  const supabaseClient = createSupabaseBrowserClient()
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async ({ keyword }: { keyword: string }) => {
      const {
        data: { user },
      } = await supabaseClient.auth.getUser()

      if (!user) throw new Error("not authenticated")

      const { error } = await supabaseClient.from("muted_keywords").insert({
        user_id: user.id,
        keyword: keyword.toLowerCase().trim(),
      })

      if (error) throw error
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.mutedKeywords.all })
      queryClient.invalidateQueries({ queryKey: queryKeys.timeline.all })
      queryClient.invalidateQueries({ queryKey: queryKeys.userProfile.all })
      notify("phrase muted")
    },
    onError: (error: Error) => {
      notify(error.message.includes("limit")
        ? "muted phrase limit reached for your plan"
        : "failed to mute phrase: " + error.message)
    },
  })
}

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

  return useMutation({
    mutationFn: async ({
      keywordIdentifier,
    }: {
      keywordIdentifier: string
    }) => {
      const { error } = await supabaseClient
        .from("muted_keywords")
        .delete()
        .eq("id", keywordIdentifier)

      if (error) throw error
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.mutedKeywords.all })
      queryClient.invalidateQueries({ queryKey: queryKeys.timeline.all })
      queryClient.invalidateQueries({ queryKey: queryKeys.userProfile.all })
      notify("phrase unmuted")
    },
    onError: (error: Error) => {
      notify("failed to unmute keyword: " + error.message)
    },
  })
}