Files
proof-of-work/workout-planner/lib/prisma.ts
T
2026-02-28 09:27:26 -06:00

48 lines
1.5 KiB
TypeScript

import { PrismaClient } from "@prisma/client";
declare global {
var prisma: PrismaClient | undefined;
}
export const prisma =
global.prisma ||
new PrismaClient({
log: process.env.NODE_ENV === "development" ? ["error", "warn"] : ["error"],
});
if (process.env.NODE_ENV !== "production") global.prisma = prisma;
/**
* caloriesBurned is in the DB schema but NOT in the generated Prisma client.
* These helpers use raw SQL to read/write it until Prisma client can be regenerated.
*/
export async function getCaloriesBurned(workoutId: string): Promise<number | null> {
const rows = await prisma.$queryRawUnsafe<Array<{ caloriesBurned: number | null }>>(
`SELECT caloriesBurned FROM Workout WHERE id = ?`,
workoutId
);
return rows[0]?.caloriesBurned ?? null;
}
export async function setCaloriesBurned(workoutId: string, calories: number | null): Promise<void> {
await prisma.$executeRawUnsafe(
`UPDATE Workout SET caloriesBurned = ? WHERE id = ?`,
calories,
workoutId
);
}
export async function getCaloriesBurnedBulk(workoutIds: string[]): Promise<Record<string, number | null>> {
if (workoutIds.length === 0) return {};
const placeholders = workoutIds.map(() => "?").join(",");
const rows = await prisma.$queryRawUnsafe<Array<{ id: string; caloriesBurned: number | null }>>(
`SELECT id, caloriesBurned FROM Workout WHERE id IN (${placeholders})`,
...workoutIds
);
const map: Record<string, number | null> = {};
for (const r of rows) {
map[r.id] = r.caloriesBurned;
}
return map;
}