Files
zellyy-finance/src/lib/supabase/client.ts
gpt-engineer-app[bot] 6de30b681a Refactor SupabaseSettings component
The SupabaseSettings component was refactored into smaller, more manageable components to improve code organization and maintainability. The UI and functionality remain unchanged.
2025-03-15 12:24:40 +00:00

142 lines
4.9 KiB
TypeScript

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 구현
fetch: (...args) => {
// 첫 번째 인자는 URL 또는 Request 객체
const urlOrRequest = args[0];
// URL 로깅 및 디버깅
let url = typeof urlOrRequest === 'string' ? urlOrRequest : urlOrRequest.url;
console.log('Supabase fetch 요청:', url);
// 기본 fetch 호출
return fetch(urlOrRequest, args[1])
.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 };