63 lines
1.9 KiB
TypeScript
63 lines
1.9 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { db, recipes, recipeIngredients } from "@epicure/db";
|
|
import { eq, and, or, ne } from "@epicure/db";
|
|
import { requireSession } from "@/lib/api-auth";
|
|
import { estimateNutrition } from "@/lib/ai/features/estimate-nutrition";
|
|
|
|
type Params = { params: Promise<{ id: string }> };
|
|
|
|
export async function GET(_req: NextRequest, { params }: Params) {
|
|
const { session, response } = await requireSession();
|
|
if (response) return response;
|
|
const { id } = await params;
|
|
|
|
const recipe = await db.query.recipes.findFirst({
|
|
where: and(
|
|
eq(recipes.id, id),
|
|
or(
|
|
eq(recipes.authorId, session!.user.id),
|
|
ne(recipes.visibility, "private")
|
|
)
|
|
),
|
|
});
|
|
|
|
if (!recipe) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
|
|
|
return NextResponse.json({ nutrition: recipe.nutritionData ?? null });
|
|
}
|
|
|
|
export async function POST(_req: NextRequest, { params }: Params) {
|
|
const { session, response } = await requireSession();
|
|
if (response) return response;
|
|
const { id } = await params;
|
|
|
|
const recipe = await db.query.recipes.findFirst({
|
|
where: and(
|
|
eq(recipes.id, id),
|
|
or(
|
|
eq(recipes.authorId, session!.user.id),
|
|
ne(recipes.visibility, "private")
|
|
)
|
|
),
|
|
with: {
|
|
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
|
|
},
|
|
});
|
|
|
|
if (!recipe) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
|
|
|
const result = await estimateNutrition({
|
|
title: recipe.title,
|
|
baseServings: recipe.baseServings,
|
|
ingredients: recipe.ingredients.map((i) => ({
|
|
rawName: i.rawName,
|
|
quantity: i.quantity,
|
|
unit: i.unit,
|
|
})),
|
|
});
|
|
|
|
await db.update(recipes).set({ nutritionData: result }).where(and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)));
|
|
|
|
return NextResponse.json({ nutrition: result });
|
|
}
|