From b4f85935ec813f7c168703487ca6e2c9f662ccef Mon Sep 17 00:00:00 2001 From: arthur Date: Fri, 18 Oct 2024 19:20:55 +0200 Subject: [PATCH] fix: postNewDay service Signed-off-by: Arthur Broudoux --- src/routes/api/days/+server.ts | 24 +++++++++++++++--------- src/utils/days.ts | 6 +++++- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/src/routes/api/days/+server.ts b/src/routes/api/days/+server.ts index 3ab6e5d..5bed516 100644 --- a/src/routes/api/days/+server.ts +++ b/src/routes/api/days/+server.ts @@ -31,29 +31,35 @@ export const POST: RequestHandler = async ({ request }: RequestEvent) => { try { const now = getDate(); const id = uuidv4().toString(); - // TODO => replace userId with the actual user id - const userId = "2e3ae305-0bae-4fc0-9b8b-890770cbbaf0"; const habits: Habit[] = (await request.json()).habits; const habitsLength: number = habits.length; const habitsCompleted: number = habits.filter((habit) => habit.isCompleted).length; - const percentage: number = (habitsCompleted / habitsLength) * 100; + const percentage: number = Math.round((habitsCompleted / habitsLength) * 100); + const newDay: Day = { id: id, - userId: userId, date: now, habits: habits, habitsCompleted: habitsCompleted, - percentage: percentage + percentage: percentage, + habitsNum: habits.length }; + //! DEBUG + if (process.env.NODE_ENV === "development") console.log("newDay from POST days:", newDay); + const dayCreated = await db.insert(daysTable).values(newDay).execute(); //! DEBUG - console.log("dayCreated from POST days:", dayCreated); + if (process.env.NODE_ENV === "development") + console.log("dayCreated from POST days:", dayCreated); return json({ day: dayCreated, message: "Day successfully created" }, { status: 201 }); - } catch (error: any) { - console.error("Error creating day:", error.message); - return json({ message: "Internal Server Error" }, { status: 500 }); + } catch (error: unknown) { + console.error("Error creating day:", error instanceof Error ? error.message : error); + return json( + { message: "Internal Server Error", error: error instanceof Error ? error.message : error }, + { status: 500 } + ); } }; diff --git a/src/utils/days.ts b/src/utils/days.ts index 2a429e8..596b9fc 100644 --- a/src/utils/days.ts +++ b/src/utils/days.ts @@ -8,6 +8,10 @@ export function getDate() { export async function manageDay() { const response = await isNewDay(fetch); + + //! DEBUG + if (process.env.NODE_ENV === "developement") console.log("Response {days.ts}", response); + const habits: Habit[] = await getAllHabits(fetch); if (response.isNewDay) { @@ -21,7 +25,7 @@ export async function manageDay() { } else if (response.dayId) { const dayUpdated: Day = await putDay(fetch, response.dayId, habits); - console.log(dayUpdated); + console.log("Day updated:", dayUpdated); return dayUpdated; }