summaryrefslogtreecommitdiff
path: root/apps/web/lib/queries/use-user-profile.ts
blob: 854d4a83e86373a7f92e54571ce1c3b08060e098 (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
"use client"

import { useQuery } from "@tanstack/react-query"
import { createSupabaseBrowserClient } from "@/lib/supabase/client"
import { queryKeys } from "./query-keys"
import type { UserProfile } from "@/lib/types/user-profile"

export function useUserProfile() {
  const supabaseClient = createSupabaseBrowserClient()

  return useQuery({
    queryKey: queryKeys.userProfile.all,
    queryFn: async () => {
      const {
        data: { user },
      } = await supabaseClient.auth.getUser()

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

      const { data, error } = await supabaseClient
        .from("user_profiles")
        .select(
          "id, tier, feed_count, folder_count, muted_keyword_count, custom_feed_count, stripe_subscription_status, stripe_current_period_end"
        )
        .eq("id", user.id)
        .single()

      if (error) throw error

      const profile: UserProfile = {
        identifier: data.id,
        email: user.email ?? null,
        displayName: (user.user_metadata?.display_name as string) ?? null,
        tier: data.tier,
        feedCount: data.feed_count,
        folderCount: data.folder_count,
        mutedKeywordCount: data.muted_keyword_count,
        customFeedCount: data.custom_feed_count,
        stripeSubscriptionStatus: data.stripe_subscription_status,
        stripeCurrentPeriodEnd: data.stripe_current_period_end,
      }

      return profile
    },
  })
}