From ba0f8f898ea67dba10a931bd2ec69e68d97a7812 Mon Sep 17 00:00:00 2001 From: Altay Date: Mon, 11 Dec 2023 14:02:59 +0300 Subject: [PATCH] feat: use `currentUser` in the account service --- lib/services/account.ts | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/lib/services/account.ts b/lib/services/account.ts index 0de44db..3dad352 100644 --- a/lib/services/account.ts +++ b/lib/services/account.ts @@ -1,18 +1,26 @@ -import type { Tables } from '@/types/supabase/database'; - import { cookies } from 'next/headers'; import { createSupabaseServerClient } from './supabase/server'; -export const fetchAccountAICredits = async ( - accountId: Tables<'account'>['id'], -) => { +const getUserId = async () => { + const supabase = createSupabaseServerClient(cookies()); + + const userQuery = await supabase.auth.getUser(); + + if (userQuery.error) { + throw new Error(userQuery.error.message); + } + + return userQuery.data.user.id; +}; + +export const fetchAccountAICredits = async () => { const supabase = createSupabaseServerClient(cookies()); const accountQuery = await supabase .from('account') .select('ai_credit') - .eq('id', accountId) + .eq('user_id', await getUserId()) .single(); if (accountQuery.error) { @@ -22,10 +30,8 @@ export const fetchAccountAICredits = async ( return accountQuery.data.ai_credit || 0; }; -export const validateAccountAICredits = async ( - accountId: Tables<'account'>['id'], -) => { - const aiCredits = await fetchAccountAICredits(accountId); +export const validateAccountAICredits = async () => { + const aiCredits = await fetchAccountAICredits(); if (aiCredits <= 0) { throw new Error('User does not have any AI credits'); @@ -34,16 +40,13 @@ export const validateAccountAICredits = async ( return aiCredits; }; -export const updateAccountAICredits = async ( - accountId: Tables<'account'>['id'], - amount: number, -) => { +export const updateAccountAICredits = async (amount: number) => { const supabase = createSupabaseServerClient(cookies()); const accountQuery = await supabase .from('account') .update({ ai_credit: amount }) - .eq('id', accountId) + .eq('user_id', await getUserId()) .select('ai_credit') .single();