This commit is contained in:
hailin 2025-05-20 19:50:38 +08:00
parent 85ab58e2fd
commit 0fbcdbe7dc
1 changed files with 10 additions and 21 deletions

View File

@ -43,35 +43,24 @@
import { createBrowserClient } from "@supabase/ssr";
import { Database } from "@/supabase/types";
// 缓存 supabase 客户端实例
// 缓存 Supabase 客户端实例
let _supabase: ReturnType<typeof createBrowserClient<Database>> | null = null;
// 创建 Supabase 客户端实例的工厂方法
export async function createClient() {
// 如果已经初始化了客户端,直接返回
// 创建 Supabase 客户端的工厂方法,改为同步初始化
export function createClient() {
// 如果客户端已创建,直接返回已创建的客户端
if (_supabase) return _supabase;
// 获取动态的 SUPABASE_URL
const url = await getRuntimeSupabaseUrl();
const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!; // 使用环境变量中的匿名密钥
// 从 window.RUNTIME_ENV 中同步获取 SUPABASE_URL
const url = window?.RUNTIME_ENV?.SUPABASE_URL || "http://localhost:8000"; // 默认回退地址
const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!; // 保留写死的 anon key
// 初始化并缓存 Supabase 客户端实例
_supabase = createBrowserClient(url, key);
return _supabase;
}
// 获取动态的 SUPABASE_URL
async function getRuntimeSupabaseUrl(retry = 30, interval = 50): Promise<string> {
for (let i = 0; i < retry; i++) {
const url = window?.RUNTIME_ENV?.SUPABASE_URL;
if (url) return url;
await new Promise((r) => setTimeout(r, interval));
}
throw new Error("RUNTIME_ENV.SUPABASE_URL not ready");
}
// 直接返回 Supabase 客户端实例
export const supabase = async () => {
const client = await createClient(); // 等待创建客户端实例
return client; // 返回已初始化的客户端实例
// 返回已初始化的 Supabase 客户端实例
export const supabase = () => {
return createClient(); // 直接返回已经初始化好的 Supabase 客户端实例
};