remix-demo

react router (remix) demo

git clone https://9o.is/git/remix-demo.git

report.server.ts

(1074B)


      1 import { json } from "@remix-run/server-runtime";
      2 import { getCaloriesReport } from "~/models/foodEntry.server";
      3 import { getUserThreshold } from "~/models/user.server";
      4 import { requireUserId } from "~/session.server";
      5 import { formatDateWithoutTime } from "~/utils/date";
      6 
      7 export async function generateReport(request: Request) {
      8   const userId = await requireUserId(request);
      9 
     10   try {
     11     const foodEntries = await getCaloriesReport(userId);
     12     const history: { [date: string]: number } = {};
     13 
     14     const thresholdQuery = await getUserThreshold(userId);
     15     if (!thresholdQuery) throw Error("User threshold is missing in DB");
     16 
     17     const threshold = thresholdQuery.threshold;
     18 
     19     for (const { consumed, calories } of foodEntries) {
     20       const date = formatDateWithoutTime(consumed);
     21       if (!date) continue;
     22       history[date] = (history[date] || 0) + calories;
     23     }
     24 
     25     return json({ threshold, history });
     26   } catch (error) {
     27     console.error("Failed to generate report:", error);
     28     return json({ error: "Failed to generate report" }, { status: 500 });
     29   }
     30 }