The first commit, the core and all files is adding to repo
This commit is contained in:
54
lib/supabase.ts
Normal file
54
lib/supabase.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import "server-only";
|
||||
import { createClient } from "@supabase/supabase-js";
|
||||
import { createServerClient } from "@supabase/ssr";
|
||||
import { cookies } from "next/headers";
|
||||
import type { Database } from "@/shared/database";
|
||||
let singleton: ReturnType<typeof createClient<Database>> | undefined;
|
||||
export function admin() {
|
||||
if (!process.env.NEXT_PUBLIC_SUPABASE_URL || !process.env.SUPABASE_SECRET_KEY)
|
||||
throw new Error(
|
||||
"Supabase configuration missing. Run npm run setup and configure .env.local.",
|
||||
);
|
||||
return (singleton ??= createClient<Database>(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL,
|
||||
process.env.SUPABASE_SECRET_KEY,
|
||||
{ auth: { persistSession: false, autoRefreshToken: false } },
|
||||
));
|
||||
}
|
||||
export async function authClient() {
|
||||
const jar = await cookies();
|
||||
return createServerClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
|
||||
{
|
||||
cookies: {
|
||||
getAll: () => jar.getAll(),
|
||||
setAll: (values) => {
|
||||
try {
|
||||
values.forEach(({ name, value, options }) =>
|
||||
jar.set(name, value, options),
|
||||
);
|
||||
} catch {
|
||||
/* Server components refresh through proxy. */
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
export async function user() {
|
||||
const client = await authClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await client.auth.getUser();
|
||||
return user;
|
||||
}
|
||||
export function required<T>(result: {
|
||||
data: T;
|
||||
error: { message: string } | null;
|
||||
}): NonNullable<T> {
|
||||
if (result.error) throw new Error(result.error.message);
|
||||
if (result.data === null || result.data === undefined)
|
||||
throw new Error("Record not found");
|
||||
return result.data as NonNullable<T>;
|
||||
}
|
||||
Reference in New Issue
Block a user