This commit is contained in:
hailin 2025-05-20 19:47:43 +08:00
parent b258867873
commit 85ab58e2fd
1 changed files with 19 additions and 11 deletions

View File

@ -40,30 +40,38 @@
// throw new Error("RUNTIME_ENV.SUPABASE_URL not ready")
// }
import { createBrowserClient } from "@supabase/ssr";
import { getRuntimeEnv } from "@/lib/ipconfig";
import { Database } from "@/supabase/types";
// 保存懒加载的 Supabase 客户端实例
// 缓存 supabase 客户端实例
let _supabase: ReturnType<typeof createBrowserClient<Database>> | null = null;
// 创建 Supabase 客户端的工厂方法
// 创建 Supabase 客户端实例的工厂方法
export async function createClient() {
// 如果已经创建过客户端,直接返回
// 如果已经初始化了客户端,则直接返回
if (_supabase) return _supabase;
// 获取动态的 SUPABASE_URL
const url = getRuntimeEnv("SUPABASE_URL") ?? "http://localhost:8000";
const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!; // 写死的 anon key
const url = await getRuntimeSupabaseUrl();
const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!; // 使用环境变量中的匿名密钥
// 创建并缓存 Supabase 客户端实例
// 初始化并缓存 Supabase 客户端实例
_supabase = createBrowserClient(url, key);
return _supabase;
}
// 返回已初始化的 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 客户端实例
const client = await createClient(); // 等待创建客户端实例
return client; // 返回已初始化的客户端实例
};