118 lines
2.6 KiB
TypeScript
118 lines
2.6 KiB
TypeScript
import { SupabaseClient } from '@supabase/supabase-js';
|
|
|
|
import { Database } from '@kit/supabase/database';
|
|
|
|
export interface AccountSubmitData {
|
|
firstName: string;
|
|
lastName: string;
|
|
personalCode: string;
|
|
email: string;
|
|
phone?: string;
|
|
city?: string;
|
|
weight: number | null;
|
|
height: number | null;
|
|
userConsent: boolean;
|
|
}
|
|
|
|
/**
|
|
* Class representing an API for interacting with user accounts.
|
|
* @constructor
|
|
* @param {SupabaseClient<Database>} client - The Supabase client instance.
|
|
*/
|
|
class AuthApi {
|
|
constructor(private readonly client: SupabaseClient<Database>) {}
|
|
|
|
/**
|
|
* @name hasUnseenMembershipConfirmation
|
|
* @description Check if given user ID has any unseen membership confirmation.
|
|
*/
|
|
async hasUnseenMembershipConfirmation() {
|
|
const {
|
|
data: { user },
|
|
} = await this.client.auth.getUser();
|
|
|
|
if (!user) {
|
|
throw new Error('User not authenticated');
|
|
}
|
|
|
|
const { data, error } = await this.client
|
|
.schema('medreport')
|
|
.rpc('has_unseen_membership_confirmation', {
|
|
p_user_id: user.id,
|
|
});
|
|
|
|
if (error) {
|
|
throw error;
|
|
}
|
|
|
|
return data;
|
|
}
|
|
|
|
/**
|
|
* @name updateAccount
|
|
* @description Update required fields for the account.
|
|
* @param data
|
|
*/
|
|
async updateAccount(data: AccountSubmitData) {
|
|
const {
|
|
data: { user },
|
|
} = await this.client.auth.getUser();
|
|
|
|
if (!user) {
|
|
throw new Error('User not authenticated');
|
|
}
|
|
|
|
const { error } = await this.client
|
|
.schema('medreport')
|
|
.rpc('update_account', {
|
|
p_name: data.firstName,
|
|
p_last_name: data.lastName,
|
|
p_personal_code: data.personalCode,
|
|
p_phone: data.phone || '',
|
|
p_city: data.city || '',
|
|
p_has_consent_personal_data: data.userConsent,
|
|
p_uid: user.id,
|
|
});
|
|
|
|
if (error) {
|
|
throw error;
|
|
}
|
|
|
|
if (data.height || data.weight) {
|
|
await this.updateAccountParams(data);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @name updateAccountParams
|
|
* @description Update account parameters.
|
|
* @param data
|
|
*/
|
|
async updateAccountParams(data: AccountSubmitData) {
|
|
const {
|
|
data: { user },
|
|
} = await this.client.auth.getUser();
|
|
|
|
if (!user) {
|
|
throw new Error('User not authenticated');
|
|
}
|
|
|
|
const response = await this.client
|
|
.schema('medreport')
|
|
.from('account_params')
|
|
.insert({
|
|
account_id: user.id,
|
|
height: data.height,
|
|
weight: data.weight,
|
|
});
|
|
|
|
if (response.error) {
|
|
throw response.error;
|
|
}
|
|
}
|
|
}
|
|
|
|
export function createAuthApi(client: SupabaseClient<Database>) {
|
|
return new AuthApi(client);
|
|
}
|