Files
medreport_mrb2b/app/home/(user)/_lib/server/load-life-style.ts
2025-10-21 16:04:01 +03:00

50 lines
1.3 KiB
TypeScript

import { cache } from 'react';
import { AccountWithParams } from '@/packages/features/accounts/src/types/accounts';
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
import { ILifeStyleResponse, PROMPT_NAME } from '../../_components/ai/types';
import { updateLifeStyle } from './ai-actions';
const failedResponse = {
lifestyle: [],
summary: null,
};
async function lifeStyleLoader(
account: AccountWithParams,
): Promise<ILifeStyleResponse> {
if (!account?.personal_code) {
return failedResponse;
}
const lifeStylePromptId = process.env.PROMPT_ID_LIFE_STYLE;
if (!lifeStylePromptId) {
return failedResponse;
}
const supabaseClient = getSupabaseServerClient();
const { data, error } = await supabaseClient
.schema('medreport')
.from('ai_responses')
.select('response')
.eq('account_id', account.id)
.eq('prompt_name', PROMPT_NAME.LIFE_STYLE)
.order('latest_data_change', { ascending: false, nullsFirst: false })
.limit(1)
.maybeSingle();
if (error) {
console.error('Error fetching AI response from DB: ', error);
return failedResponse;
}
if (data?.response) {
return JSON.parse(data.response as string);
} else {
return await updateLifeStyle({ account });
}
}
export const loadLifeStyle = cache(lifeStyleLoader);