habits.andr33v.ru/server/api/habits/index.get.ts

43 lines
973 B
TypeScript

import { getUserIdFromSession } from '../../utils/auth';
import { Habit } from '@prisma/client';
// DTO to shape the output
interface HabitCompletionDto {
date: Date;
}
interface HabitDto {
id: number;
name: string;
daysOfWeek: number[];
completions: HabitCompletionDto[];
}
export default defineEventHandler(async (event): Promise<HabitDto[]> => {
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,
})),
}));
});