Refactor supabase.ts into modules

Refactor the supabase.ts file into smaller modules, separating test functionalities and default client configurations while preserving all code functionalities.
This commit is contained in:
gpt-engineer-app[bot]
2025-03-15 12:12:07 +00:00
parent 3a14914482
commit 2493f958de
5 changed files with 291 additions and 267 deletions

132
src/lib/supabase/client.ts Normal file
View File

@@ -0,0 +1,132 @@
import { createClient } from '@supabase/supabase-js';
import { getSupabaseUrl, getSupabaseKey } from './config';
const supabaseUrl = getSupabaseUrl();
const supabaseAnonKey = getSupabaseKey();
// 유효한 URL이 설정되었는지 확인
const isValidUrl = supabaseUrl && supabaseAnonKey &&
!supabaseUrl.includes('your-onpremise-supabase-url') &&
!supabaseAnonKey.includes('your-onpremise-anon-key');
let supabaseClient;
try {
console.log(`Supabase 클라이언트 생성 시도: ${supabaseUrl}`);
// Supabase 클라이언트 생성
supabaseClient = createClient(supabaseUrl, supabaseAnonKey, {
auth: {
autoRefreshToken: true,
persistSession: true,
// 온프레미스 설치를 위한 추가 설정
flowType: 'implicit',
},
global: {
fetch: (url, options) => {
// CORS 디버깅을 위한 사용자 정의 fetch
console.log('Supabase fetch 요청:', url);
return fetch(url, options).then(response => {
console.log('Supabase 응답 상태:', response.status);
return response;
}).catch(err => {
console.error('Supabase fetch 오류:', err);
throw err;
});
}
}
});
// CORS 문제 확인을 위한 기본 헤더 테스트
(async () => {
try {
// 기본 서버 상태 확인 (CORS 테스트)
console.log('Supabase 서버 상태 확인 중...');
const response = await fetch(`${supabaseUrl}/rest/v1/`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'apikey': supabaseAnonKey,
},
});
if (response.ok) {
console.log('Supabase REST API 연결 성공:', response.status);
} else {
console.warn('Supabase REST API 연결 실패:', response.status, response.statusText);
// 응답 세부 정보 로깅
try {
const errorText = await response.text();
console.warn('Supabase REST API 오류 응답:', errorText);
} catch (e) {
console.error('응답 내용 읽기 실패:', e);
}
}
} catch (err) {
console.error('Supabase 서버 상태 확인 중 오류 (CORS 문제 가능성):', err);
}
})();
// Supabase 연결 테스트
(async () => {
try {
console.log('Supabase 인증 테스트 시도 중...');
const { data, error } = await supabaseClient.auth.getSession();
if (error) {
console.warn('Supabase 연결 테스트 실패:', error.message);
} else {
console.log('Supabase 연결 성공!', data);
}
// 추가 테스트: 공개 데이터 조회 시도
try {
console.log('Supabase 데이터베이스 공개 테이블 조회 시도...');
const { data: tableData, error: tableError } = await supabaseClient
.from('transactions')
.select('*')
.limit(1);
if (tableError) {
console.warn('Supabase 데이터베이스 테스트 실패:', tableError.message);
} else {
console.log('Supabase 데이터베이스 테스트 성공:', tableData);
}
} catch (dbErr) {
console.error('Supabase 데이터베이스 테스트 중 예외 발생:', dbErr);
}
} catch (err) {
console.error('Supabase 연결 확인 중 오류:', err);
}
})();
// Supabase 연결 로그
console.log('Supabase 클라이언트가 생성되었습니다.');
// 유효성 검사 로그
if (!isValidUrl) {
console.warn('경고: 기본 Supabase URL 또는 Anon Key가 감지되었습니다. Supabase 설정 페이지에서 온프레미스 설정을 구성하세요.');
}
} catch (error) {
console.error('Supabase 클라이언트 생성 오류:', error);
// 더미 클라이언트 생성 (앱이 완전히 실패하지 않도록)
supabaseClient = {
auth: {
getUser: () => Promise.resolve({ data: { user: null } }),
getSession: () => Promise.resolve({ data: { session: null } }),
signInWithPassword: () => Promise.reject(new Error('Supabase 설정이 필요합니다')),
signUp: () => Promise.reject(new Error('Supabase 설정이 필요합니다')),
signOut: () => Promise.resolve({ error: null }),
onAuthStateChange: () => ({ data: { subscription: { unsubscribe: () => {} } } }),
},
from: () => ({
select: () => ({ eq: () => ({ data: null, error: new Error('Supabase 설정이 필요합니다') }) }),
insert: () => ({ error: new Error('Supabase 설정이 필요합니다') }),
delete: () => ({ eq: () => ({ error: new Error('Supabase 설정이 필요합니다') }) }),
}),
};
}
export const supabase = supabaseClient;
export { isValidUrl };