import { useSession } from 'h3'; // DTO to shape the output interface HabitCompletionDto { date: Date; } interface HabitDto { id: number; name: string; daysOfWeek: number[]; completions: HabitCompletionDto[]; } /** * A helper function to safely get the authenticated user's ID from the session. */ async function getUserIdFromSession(event: any): Promise { const session = await useSession(event, { password: process.env.SESSION_PASSWORD, }); const userId = session.data?.user?.id; if (!userId) { throw createError({ statusCode: 401, statusMessage: 'Unauthorized' }); } return userId; } export default defineEventHandler(async (event): Promise => { const userId = await getUserIdFromSession(event); const habits = await prisma.habit.findMany({ where: { userId: userId, }, include: { completions: { orderBy: { date: 'desc', }, take: 30, // Limit completions to the last 30 for performance }, }, }); // Map to DTOs return habits.map((habit: any) => ({ id: habit.id, name: habit.name, daysOfWeek: habit.daysOfWeek, // Assuming daysOfWeek is already in the correct format completions: habit.completions.map((comp: any) => ({ date: comp.date, })), })); });