diff --git a/lib/supabase/get-user.ts b/lib/supabase/get-user.ts index 1d74bc53..4078f667 100644 --- a/lib/supabase/get-user.ts +++ b/lib/supabase/get-user.ts @@ -1,4 +1,5 @@ import { isAuthRetryableFetchError } from "@supabase/supabase-js"; +import { cache } from "react"; import { withRetry } from "../utils"; import { createClient } from "./server"; @@ -11,7 +12,7 @@ import { createClient } from "./server"; * IMPORTANT: This function will throw an error if executed while the user is not authenticated. * Make sure the user is logged in before calling this function. */ -export const getUser = async () => { +const getUser = async () => { const supabase = await createClient(); const getUserFunc = async () => { @@ -39,3 +40,7 @@ export const getUser = async () => { return user; }; + +const cachedGetUser = cache(getUser); + +export { cachedGetUser as getUser }; diff --git a/services/accounts/fetch-current-user.ts b/services/accounts/fetch-current-user.ts index 5d8a9e09..b3ed642b 100644 --- a/services/accounts/fetch-current-user.ts +++ b/services/accounts/fetch-current-user.ts @@ -1,8 +1,9 @@ import { db, supabaseUserMappings, users } from "@/drizzle"; import { getUser } from "@/lib/supabase"; import { eq } from "drizzle-orm"; +import { cache } from "react"; -export async function fetchCurrentUser() { +async function fetchCurrentUser() { const supabaseUser = await getUser(); const user = await db .select({ dbId: users.dbId }) @@ -17,3 +18,6 @@ export async function fetchCurrentUser() { } return user[0]; } + +const cachedFetchCurrentUser = cache(fetchCurrentUser); +export { cachedFetchCurrentUser as fetchCurrentUser }; diff --git a/services/teams/fetch-current-team.ts b/services/teams/fetch-current-team.ts index ac3f505b..e18f12f9 100644 --- a/services/teams/fetch-current-team.ts +++ b/services/teams/fetch-current-team.ts @@ -8,6 +8,7 @@ import { import { getGiselleSession } from "@/lib/giselle-session"; import { getUser } from "@/lib/supabase"; import { and, asc, eq } from "drizzle-orm"; +import { cache } from "react"; import type { CurrentTeam } from "./types"; /** @@ -15,7 +16,7 @@ import type { CurrentTeam } from "./types"; * This function uses session to get the teamDbId. * If the user does not have a team, the first team is returned. */ -export async function fetchCurrentTeam(): Promise { +async function fetchCurrentTeam(): Promise { const supabaseUser = await getUser(); const session = await getGiselleSession(); const teamDbId = session?.teamDbId; @@ -32,6 +33,9 @@ export async function fetchCurrentTeam(): Promise { return team; } +const cachedFetchCurrentTeam = cache(fetchCurrentTeam); +export { cachedFetchCurrentTeam as fetchCurrentTeam }; + async function fetchTeam(teamDbId: number, supabaseUserId: string) { const result = await db .select({