Files
shorturl-analytics/app/utils/supabase.ts
2025-04-23 20:04:37 +08:00

99 lines
2.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { createClient, SupabaseClient } from "@supabase/supabase-js";
import type { Database } from "@/types/supabase";
let supabase: SupabaseClient<Database> | null = null;
// 增强的存储适配器使用localStorage并添加更多错误处理
const storageAdapter = {
getItem: async (key: string) => {
try {
const item = localStorage.getItem(key);
console.log(`Storage get for key [${key}]: ${item ? "found" : "not found"}`);
return item;
} catch (error) {
console.error("Storage get error:", error);
return null;
}
},
setItem: async (key: string, value: string) => {
try {
localStorage.setItem(key, value);
console.log(`Storage set for key [${key}] successful`);
} catch (error) {
console.error("Storage set error:", error);
}
},
removeItem: async (key: string) => {
try {
localStorage.removeItem(key);
console.log(`Storage remove for key [${key}] successful`);
} catch (error) {
console.error("Storage remove error:", error);
}
},
};
// 添加一个函数来检查Supabase连接状态
export const checkSupabaseConnection = async (): Promise<boolean> => {
try {
const client = getSupabaseClient();
const { error } = await client.from('_health').select('*').limit(1);
if (error) {
console.error('Supabase connection check failed:', error);
return false;
}
console.log('Supabase connection check successful');
return true;
} catch (error) {
console.error('Supabase connection check exception:', error);
return false;
}
};
export const getSupabaseClient = (): SupabaseClient<Database> => {
if (!supabase) {
if (!process.env.NEXT_PUBLIC_SUPABASE_URL || !process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY) {
console.error('Missing Supabase environment variables');
throw new Error('Missing Supabase environment variables');
}
console.log('Creating new Supabase client with URL:', process.env.NEXT_PUBLIC_SUPABASE_URL);
// 使用as断言来避免类型错误
supabase = createClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
{
db: { schema: "limq" },
auth: {
storage: storageAdapter,
persistSession: true,
autoRefreshToken: true,
detectSessionInUrl: true,
},
}
) as SupabaseClient<Database>;
// 立即检查客户端创建后的会话状态
void supabase.auth.getSession().then(({ data: { session } }) => {
console.log('Initial session check:', session ? 'Session exists' : 'No session');
}).catch(err => {
console.error('Error checking initial session:', err);
});
}
if (!supabase) {
throw new Error('Failed to create Supabase client');
}
return supabase;
};
export const clearSupabaseInstance = () => {
console.log('Clearing Supabase instance');
supabase = null;
};