Skip to content

Commit

Permalink
feat: use currentUser in the account service
Browse files Browse the repository at this point in the history
  • Loading branch information
altaywtf committed Dec 11, 2023
1 parent 2d63a4e commit ba0f8f8
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions lib/services/account.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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');
Expand All @@ -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();

Expand Down

0 comments on commit ba0f8f8

Please sign in to comment.