Files
myeasycms-v2/packages/supabase/src/clients/server-actions.client.ts
giancarlo f0bc6959e1 Refactor Supabase client and service role key usage
The refactoring includes the moving of the `getSupabaseClientKeys()` and `getServiceRoleKey()` function calls to the module scope and the addition of a `warnServiceRoleKeyUsage()` function, used to display a warning when the Supabase Service Role is accessed. The change aims to improve code readability and maintainability.
2024-04-13 20:03:08 +08:00

62 lines
1.4 KiB
TypeScript

import 'server-only';
import { cookies } from 'next/headers';
import { createServerClient } from '@supabase/ssr';
import { Database } from '../database.types';
import {
getServiceRoleKey,
warnServiceRoleKeyUsage,
} from '../get-service-role-key';
import { getSupabaseClientKeys } from '../get-supabase-client-keys';
const keys = getSupabaseClientKeys();
const serviceRoleKey = getServiceRoleKey();
function createServerSupabaseClient() {
return createServerClient<Database>(keys.url, keys.anonKey, {
cookies: getCookiesStrategy(),
});
}
export function getSupabaseServerActionClient<
GenericSchema = Database,
>(params?: { admin: boolean }) {
const keys = getSupabaseClientKeys();
const admin = params?.admin ?? false;
if (admin) {
warnServiceRoleKeyUsage();
return createServerClient<GenericSchema>(keys.url, serviceRoleKey, {
auth: {
persistSession: false,
},
cookies: {},
});
}
return createServerSupabaseClient();
}
function getCookiesStrategy() {
const cookieStore = cookies();
return {
get: (name: string) => {
return cookieStore.get(name)?.value;
},
set: (name: string, value: string, options: object) => {
cookieStore.set({ name, value, ...options });
},
remove: (name: string, options: object) => {
cookieStore.set({
name,
value: '',
...options,
});
},
};
}