Confused on how to use RPC to get account info.
salvinoto opened this issue · comments
Hi, so I am confused how to use the RPC methods to get the account info. What I'm trying to do is just have a single function to get the account for me, and it automatically determines whether the account selector is on a team or not. Currently is what I have below, and basically, it just checks to see if there is a slug in the URL. Basically im wondering if theres a better way to do this, because its very sloppy and its a huge mess. A huge issue too is that the RPCs dont get types when generated with the supabase CLI. Basically I'd like advice on how to implement this with it being disaster. Thanks.
EDIT: Even more so, it seems like Supabase is trying to find these RPC on the public schema, where they dont exist. Dont know how to fix that either or something like that
Searched for the function public.get_account_by_slug without parameters or with a single unnamed json/jsonb parameter, but no matches were found in the schema cache
`import { createClient } from "@/utils/supabase/server";
export interface AccountData {
account_id: string;
account_role: string;
is_primary_owner: boolean;
name: string;
slug: string;
personal_account: boolean;
billing_enabled: boolean;
billing_status: string;
created_at: string; // Assuming timestamp is a string, adjust if it's a Date object
updated_at: string; // Same assumption as created_at
metadata: {
[key: string]: any; // Adjust according to the known structure or keep it flexible
};
}
export async function getAccountData({ params }: { params: { slug: string } }) {
const supabase = createClient();
if (params.slug === "personal") {
const { data, error } = await supabase.rpc("get_personal_account");
return { data: data as unknown as AccountData, error };
}
const { data, error } = await supabase.rpc("get_account_by_slug", {
slug: params.slug,
});
return { data: data as unknown as AccountData, error };
}
`
I did the same. Then, I ended up removing the basejump_accounts_slug_null_if_personal_account_true
constraint and making slug
not null and unique for personal accounts, too.
ALTER TABLE basejump.accounts
DROP CONSTRAINT basejump_accounts_slug_null_if_personal_account_true;
ALTER TABLE basejump.accounts
ALTER COLUMN slug
SET NOT NULL;
On user sign-up, I use their email address to create a username and slug. I apply this to both the user metadata object and basejump.accounts
. This doesn't solve the TypeScript issue, but it does solve the confusing RPC queries. Only need to use get_account_by_slug
.
I see that makes a lot of sense. Thank you. Also have you found a way to retain the current slug across navigations? I definitely cant hardcode the slug in, how do you handle links to other pages?
I check the user account membership slugs in app/[accountSlug]/layout.tsx:
export default async function AccountDashboardLayout({
children,
params,
}: {
children: React.ReactNode;
params: { accountSlug: string };
}) {
const supabase = createClient();
const { data: allAccounts, error: allAccountsError } = await supabase.rpc('get_accounts');
if (allAccountsError || !allAccounts) {
console.error('account dashboard layout get_accounts', allAccountsError);
notFound();
}
// @ts-ignore
if (!allAccounts.some((account) => params.accountSlug === account.slug)) {
console.log('account dashboard layout - no matching accountslug');
notFound();
}
return (
<>
<DashboardHeader accountSlug={decodeURIComponent(params.accountSlug)} />
<div className="h-full w-full p-8">{children}</div>
</>
);
}
And just in case, I blacklisted the words personal
and dashboard
for slugs and I have this check set up in middleware.ts:
......
if (['/personal', '/dashboard'].includes(`/${decodeURIComponent(path.split('/')[1])}`)) {
return NextResponse.redirect(
new URL(`/${user?.user_metadata?.username}${path === '/' ? '' : `/${decodeURIComponent(path.split('/').slice(2).join('/'))}`}`, req.url)
);
}
....
On linking to other pages, getting data in action, etc.: That sucks. I usually send either account.slug
, or account.account_id
between pages, components, actions, etc.
I had an idea to maybe use the TeamSwitch to set a cookie with the current team slug when switching teams, and accessing the cookie from the server should be allowed as long as httpOnly is off I think. Then every link I'll just append the slug.
set a cookie with the current team slug when switching teams
Sounds reasonable. I may give this a try. I use server actions with useFormState()
. I tried 2 things:
-
use
bind()
to access the current slug inside server actions.
In server components, I use{ params }
, in client components,usePathname()
:const whateverActionWithSlug = whateverAction.bind(null, accountSlug);
(In this case, you need to validate the slug inside server action and have the correct RLS policies setup.) -
Start server action with an
auth.getUser()
call, and then use the returneduser.user_metadata.username
(that I saved on sign up and it's same as the personal account slug). Tho, this only works if the action has to do something with the user's personal account.
I don't know. All feels kinda "hacky" to me.
It does seem pretty hacky but I think basejump is great at managing the db part of things. Ideally there would be a basejump package that handles the API like Supabase js does on the front end, so I'm trying to make it modular so that I can import it easily if I make something else or if someone else wants to use it. But my thought is manually type everything in a util file, set the cookie on the client from the team switcher, and access the cookie throughout the app to append the slug to links, whether it's client or server. I'll implement this today, but after mind mapping it I'm pretty confident it will be the smoothest solution when dealing with server and client components together.