사주 풀이 고도화, NAS 배포 자동화
This commit is contained in:
43
lib/ensure-profile.ts
Normal file
43
lib/ensure-profile.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* 유저의 profiles 행이 존재하는지 확인하고, 없으면 생성한다.
|
||||
* handle_new_user 트리거가 실패했거나 트리거 설정 전에 가입한 유저를 위한 안전장치.
|
||||
*/
|
||||
export async function ensureProfile(supabase: any, user: any): Promise<number> {
|
||||
// 1. 프로필 조회
|
||||
const { data: profile, error: selectError } = await supabase
|
||||
.from('profiles')
|
||||
.select('credits')
|
||||
.eq('id', user.id)
|
||||
.single();
|
||||
|
||||
if (profile) {
|
||||
return profile.credits || 0;
|
||||
}
|
||||
|
||||
// 2. 프로필이 없으면 생성
|
||||
console.log('프로필이 없어서 자동 생성합니다:', user.id);
|
||||
const { error: insertError } = await supabase
|
||||
.from('profiles')
|
||||
.insert({
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
full_name: user.user_metadata?.full_name || null,
|
||||
avatar_url: user.user_metadata?.avatar_url || null,
|
||||
credits: 0,
|
||||
});
|
||||
|
||||
if (insertError) {
|
||||
// 동시 생성 경쟁 시 중복 에러 무시하고 다시 조회
|
||||
if (insertError.code === '23505') {
|
||||
const { data: retryProfile } = await supabase
|
||||
.from('profiles')
|
||||
.select('credits')
|
||||
.eq('id', user.id)
|
||||
.single();
|
||||
return retryProfile?.credits || 0;
|
||||
}
|
||||
console.error('프로필 생성 실패:', insertError);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user