80 lines
1.9 KiB
TypeScript
80 lines
1.9 KiB
TypeScript
'use client';
|
|
|
|
import { createClient, type Profile } from '@/utils/supabase';
|
|
import { getUser } from '@/lib/hooks';
|
|
import type { Result } from '.';
|
|
|
|
export const getProfile = async (): Promise<Result<Profile>> => {
|
|
try {
|
|
const user = await getUser();
|
|
if (!user.success || user.data === undefined)
|
|
throw new Error('User not found');
|
|
const supabase = createClient();
|
|
const { data, error } = await supabase
|
|
.from('profiles')
|
|
.select('*')
|
|
.eq('id', user.data.id)
|
|
.single();
|
|
if (error) throw error;
|
|
return { success: true, data: data as Profile };
|
|
} catch (error) {
|
|
return {
|
|
success: false,
|
|
error:
|
|
error instanceof Error
|
|
? error.message
|
|
: 'Unknown error getting profile',
|
|
};
|
|
}
|
|
};
|
|
|
|
type updateProfileProps = {
|
|
full_name?: string;
|
|
email?: string;
|
|
avatar_url?: string;
|
|
};
|
|
|
|
export const updateProfile = async ({
|
|
full_name,
|
|
email,
|
|
avatar_url,
|
|
}: updateProfileProps): Promise<Result<Profile>> => {
|
|
try {
|
|
if (
|
|
full_name === undefined &&
|
|
email === undefined &&
|
|
avatar_url === undefined
|
|
)
|
|
throw new Error('No profile data provided');
|
|
|
|
const userResponse = await getUser();
|
|
if (!userResponse.success || userResponse.data === undefined)
|
|
throw new Error('User not found');
|
|
|
|
const supabase = createClient();
|
|
const { data, error } = await supabase
|
|
.from('profiles')
|
|
.update({
|
|
...(full_name !== undefined && { full_name }),
|
|
...(email !== undefined && { email }),
|
|
...(avatar_url !== undefined && { avatar_url }),
|
|
})
|
|
.eq('id', userResponse.data.id)
|
|
.select()
|
|
.single();
|
|
if (error) throw error;
|
|
return {
|
|
success: true,
|
|
data: data as Profile,
|
|
};
|
|
} catch (error) {
|
|
return {
|
|
success: false,
|
|
error:
|
|
error instanceof Error
|
|
? error.message
|
|
: 'Unknown error updating profile',
|
|
};
|
|
}
|
|
};
|