feat(recipes): full recipe CRUD with photos, print, version history

List, detail, new, edit pages. Server-side pagination, dietary tags, difficulty.
Photo upload to S3-compatible storage. Version history. Multi-select grid with
bulk delete/visibility. Print view. Delete confirmation dialog.
This commit is contained in:
Arnaud
2026-07-01 08:10:11 +02:00
parent fa2d797918
commit 84d6cfeb07
45 changed files with 5300 additions and 0 deletions
@@ -0,0 +1,102 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, comments, commentReactions, eq, and, count } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
const ReactionSchema = z.object({
type: z.enum(["like", "love", "laugh", "wow", "sad", "fire"]),
});
type Params = { params: Promise<{ id: string; commentId: string }> };
export async function GET(req: NextRequest, { params }: Params) {
const { commentId } = await params;
// Verify comment exists
const comment = await db.query.comments.findFirst({ where: eq(comments.id, commentId) });
if (!comment) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
// Get reaction counts grouped by type
const rows = await db
.select({ type: commentReactions.type, cnt: count() })
.from(commentReactions)
.where(eq(commentReactions.commentId, commentId))
.groupBy(commentReactions.type);
const counts: Record<string, number> = {};
for (const row of rows) {
counts[row.type] = row.cnt;
}
// Check for session to return user's reactions
const { session } = await requireSession();
let userReactions: string[] = [];
if (session) {
const userRows = await db
.select({ type: commentReactions.type })
.from(commentReactions)
.where(and(eq(commentReactions.commentId, commentId), eq(commentReactions.userId, session.user.id)));
userReactions = userRows.map((r) => r.type);
}
return NextResponse.json({ counts, userReactions });
}
export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { commentId } = await params;
// Verify comment exists
const comment = await db.query.comments.findFirst({ where: eq(comments.id, commentId) });
if (!comment) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const body = await req.json() as unknown;
const parsed = ReactionSchema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
const { type } = parsed.data;
const userId = session!.user.id;
// Toggle: check if reaction exists
const existing = await db.query.commentReactions.findFirst({
where: and(
eq(commentReactions.commentId, commentId),
eq(commentReactions.userId, userId),
eq(commentReactions.type, type),
),
});
let added: boolean;
if (existing) {
await db.delete(commentReactions).where(eq(commentReactions.id, existing.id));
added = false;
} else {
await db.insert(commentReactions).values({
id: crypto.randomUUID(),
commentId,
userId,
type,
});
added = true;
}
// Return updated counts
const rows = await db
.select({ type: commentReactions.type, cnt: count() })
.from(commentReactions)
.where(eq(commentReactions.commentId, commentId))
.groupBy(commentReactions.type);
const counts: Record<string, number> = {};
for (const row of rows) {
counts[row.type] = row.cnt;
}
return NextResponse.json({ counts, added });
}
@@ -0,0 +1,82 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, recipes, comments, users, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { dispatchWebhook } from "@/lib/webhooks";
import { sendPushNotification } from "@/lib/push";
const Schema = z.object({
content: z.string().min(1).max(5000),
parentId: z.string().optional(),
});
type Params = { params: Promise<{ id: string }> };
export async function GET(_req: NextRequest, { params }: Params) {
const { id } = await params;
const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
if (!recipe || recipe.visibility === "private") {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const rows = await db
.select({
id: comments.id,
content: comments.content,
parentId: comments.parentId,
createdAt: comments.createdAt,
updatedAt: comments.updatedAt,
userId: comments.userId,
userName: users.name,
userUsername: users.username,
userAvatarUrl: users.avatarUrl,
})
.from(comments)
.innerJoin(users, eq(comments.userId, users.id))
.where(eq(comments.recipeId, id))
.orderBy(comments.createdAt);
return NextResponse.json(rows);
}
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: eq(recipes.id, id) });
if (!recipe || (recipe.visibility === "private" && recipe.authorId !== session!.user.id)) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
if (parsed.data.parentId) {
const parent = await db.query.comments.findFirst({
where: and(eq(comments.id, parsed.data.parentId), eq(comments.recipeId, id)),
});
if (!parent) return NextResponse.json({ error: "Parent comment not found" }, { status: 404 });
}
const commentId = crypto.randomUUID();
await db.insert(comments).values({
id: commentId,
recipeId: id,
userId: session!.user.id,
parentId: parsed.data.parentId,
content: parsed.data.content,
});
// Dispatch to recipe author's webhooks (not to the commenter themselves)
if (recipe.authorId !== session!.user.id) {
void dispatchWebhook(recipe.authorId, "comment.added", { commentId, recipeId: id, recipeTitle: recipe.title });
void sendPushNotification(recipe.authorId, {
title: "New comment on your recipe",
body: `${session!.user.name} commented on "${recipe.title}"`,
url: `/recipes/${id}`,
});
}
return NextResponse.json({ id: commentId }, { status: 201 });
}
@@ -0,0 +1,74 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, recipes, cookingHistory, pantryItems, recipeIngredients, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
type Params = { params: Promise<{ id: string }> };
const Schema = z.object({
servings: z.number().int().min(1).optional(),
notes: z.string().max(2000).optional(),
deductFromPantry: z.boolean().default(true),
});
export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
const userId = session!.user.id;
const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
if (!recipe || (recipe.visibility === "private" && recipe.authorId !== userId)) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const body = await req.json().catch(() => ({})) as unknown;
const parsed = Schema.safeParse(body);
const data = parsed.success ? parsed.data : { deductFromPantry: true };
await db.insert(cookingHistory).values({
id: crypto.randomUUID(),
userId,
recipeId: id,
servings: data.servings,
notes: data.notes,
cookedAt: new Date(),
});
if (data.deductFromPantry) {
const ings = await db.query.recipeIngredients.findMany({
where: eq(recipeIngredients.recipeId, id),
});
const scale = data.servings ? data.servings / recipe.baseServings : 1;
const userPantry = await db.query.pantryItems.findMany({
where: eq(pantryItems.userId, userId),
});
for (const ing of ings) {
const key = ing.rawName.toLowerCase();
const pantryItem = userPantry.find(
(p) => p.rawName.toLowerCase() === key && (p.unit ?? "") === (ing.unit ?? "")
);
if (!pantryItem) continue;
const pantryQty = pantryItem.quantity ? parseFloat(pantryItem.quantity) : null;
const ingQty = ing.quantity ? parseFloat(ing.quantity) * scale : null;
if (pantryQty !== null && ingQty !== null && !isNaN(pantryQty) && !isNaN(ingQty)) {
const remaining = pantryQty - ingQty;
if (remaining <= 0) {
await db.delete(pantryItems).where(eq(pantryItems.id, pantryItem.id));
} else {
await db.update(pantryItems)
.set({ quantity: String(Math.round(remaining * 10000) / 10000) })
.where(eq(pantryItems.id, pantryItem.id));
}
} else {
// no numeric quantity to deduct — remove the item entirely
await db.delete(pantryItems).where(eq(pantryItems.id, pantryItem.id));
}
}
}
return NextResponse.json({ logged: true }, { status: 201 });
}
@@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from "next/server";
import { db, recipes, favorites, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
type Params = { params: Promise<{ id: string }> };
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: eq(recipes.id, id) });
if (!recipe || recipe.visibility === "private" && recipe.authorId !== session!.user.id) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
await db.insert(favorites).values({ userId: session!.user.id, recipeId: id }).onConflictDoNothing();
return NextResponse.json({ favorited: true });
}
export async function DELETE(_req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
await db.delete(favorites).where(and(eq(favorites.userId, session!.user.id), eq(favorites.recipeId, id)));
return NextResponse.json({ favorited: false });
}
@@ -0,0 +1,62 @@
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(eq(recipes.id, id));
return NextResponse.json({ nutrition: result });
}
@@ -0,0 +1,49 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, recipes, ratings, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
const Schema = z.object({
score: z.number().int().min(1).max(5),
reviewText: z.string().max(2000).optional(),
});
type Params = { params: Promise<{ id: string }> };
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: eq(recipes.id, id) });
if (!recipe || (recipe.visibility === "private" && recipe.authorId !== session!.user.id)) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
if (recipe.authorId === session!.user.id) {
return NextResponse.json({ error: "Cannot rate your own recipe" }, { status: 400 });
}
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
const existing = await db.query.ratings.findFirst({
where: and(eq(ratings.recipeId, id), eq(ratings.userId, session!.user.id)),
});
if (existing) {
await db.update(ratings)
.set({ score: parsed.data.score, reviewText: parsed.data.reviewText, updatedAt: new Date() })
.where(eq(ratings.id, existing.id));
return NextResponse.json({ updated: true });
}
await db.insert(ratings).values({
id: crypto.randomUUID(),
recipeId: id,
userId: session!.user.id,
score: parsed.data.score,
reviewText: parsed.data.reviewText,
});
return NextResponse.json({ created: true }, { status: 201 });
}
+177
View File
@@ -0,0 +1,177 @@
import { NextRequest, NextResponse } from "next/server";
import { db, recipes, recipeIngredients, recipeSteps, recipeSnapshots } from "@epicure/db";
import { eq, and, max } from "@epicure/db";
import { z } from "zod";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { dispatchWebhook } from "@/lib/webhooks";
const UpdateRecipeSchema = z.object({
title: z.string().min(1).max(200).optional(),
description: z.string().optional(),
baseServings: z.number().int().min(1).max(100).optional(),
visibility: z.enum(["private", "unlisted", "public"]).optional(),
difficulty: z.enum(["easy", "medium", "hard"]).nullable().optional(),
prepMins: z.number().int().min(0).nullable().optional(),
cookMins: z.number().int().min(0).nullable().optional(),
dietaryTags: z.object({
vegan: z.boolean().optional(),
vegetarian: z.boolean().optional(),
glutenFree: z.boolean().optional(),
dairyFree: z.boolean().optional(),
nutFree: z.boolean().optional(),
halal: z.boolean().optional(),
kosher: z.boolean().optional(),
}).optional(),
ingredients: z.array(z.object({
rawName: z.string().min(1),
quantity: z.string().optional(),
unit: z.string().optional(),
note: z.string().optional(),
order: z.number().int().default(0),
})).optional(),
steps: z.array(z.object({
instruction: z.string().min(1),
timerSeconds: z.number().int().optional(),
order: z.number().int(),
})).optional(),
});
type Params = { params: Promise<{ id: string }> };
async function getOwnedRecipe(recipeId: string, userId: string) {
return db.query.recipes.findFirst({
where: and(eq(recipes.id, recipeId), eq(recipes.authorId, userId)),
with: { ingredients: { orderBy: (t, { asc }) => asc(t.order) }, steps: { orderBy: (t, { asc }) => asc(t.order) }, photos: true },
});
}
export async function GET(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req, { rateLimit: { limit: 60, windowSeconds: 60 } });
if (response) return response;
const { id } = await params;
const recipe = await getOwnedRecipe(id, session!.user.id);
if (!recipe) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json(recipe);
}
export async function PUT(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req, { rateLimit: { limit: 60, windowSeconds: 60 } });
if (response) return response;
const { id } = await params;
const existing = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)),
with: { ingredients: { orderBy: (t, { asc }) => asc(t.order) }, steps: { orderBy: (t, { asc }) => asc(t.order) } },
});
if (!existing) return NextResponse.json({ error: "Not found" }, { status: 404 });
// Create a snapshot of the current state before updating
const [maxVersionRow] = await db
.select({ v: max(recipeSnapshots.version) })
.from(recipeSnapshots)
.where(eq(recipeSnapshots.recipeId, id));
const nextVersion = (maxVersionRow?.v ?? 0) + 1;
await db.insert(recipeSnapshots).values({
id: crypto.randomUUID(),
recipeId: id,
authorId: session!.user.id,
version: nextVersion,
title: existing.title,
snapshotData: {
title: existing.title,
description: existing.description,
baseServings: existing.baseServings,
difficulty: existing.difficulty,
prepMins: existing.prepMins,
cookMins: existing.cookMins,
dietaryTags: existing.dietaryTags ?? {},
ingredients: existing.ingredients.map((i) => ({
rawName: i.rawName,
quantity: i.quantity,
unit: i.unit,
note: i.note,
order: i.order,
})),
steps: existing.steps.map((s) => ({
instruction: s.instruction,
timerSeconds: s.timerSeconds,
order: s.order,
})),
},
});
const body = await req.json() as unknown;
const parsed = UpdateRecipeSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
const data = parsed.data;
await db.transaction(async (tx) => {
const updates: Partial<typeof recipes.$inferInsert> = { updatedAt: new Date() };
if (data.title !== undefined) updates.title = data.title;
if (data.description !== undefined) updates.description = data.description;
if (data.baseServings !== undefined) updates.baseServings = data.baseServings;
if (data.visibility !== undefined) updates.visibility = data.visibility;
if (data.difficulty !== undefined) updates.difficulty = data.difficulty ?? undefined;
if (data.prepMins !== undefined) updates.prepMins = data.prepMins ?? undefined;
if (data.cookMins !== undefined) updates.cookMins = data.cookMins ?? undefined;
if (data.dietaryTags !== undefined) updates.dietaryTags = data.dietaryTags;
await tx.update(recipes).set(updates).where(eq(recipes.id, id));
if (data.ingredients !== undefined) {
await tx.delete(recipeIngredients).where(eq(recipeIngredients.recipeId, id));
if (data.ingredients.length > 0) {
await tx.insert(recipeIngredients).values(
data.ingredients.map((ing, i) => ({
id: crypto.randomUUID(),
recipeId: id,
rawName: ing.rawName,
quantity: ing.quantity,
unit: ing.unit,
note: ing.note,
order: ing.order ?? i,
}))
);
}
}
if (data.steps !== undefined) {
await tx.delete(recipeSteps).where(eq(recipeSteps.recipeId, id));
if (data.steps.length > 0) {
await tx.insert(recipeSteps).values(
data.steps.map((step, i) => ({
id: crypto.randomUUID(),
recipeId: id,
instruction: step.instruction,
timerSeconds: step.timerSeconds,
order: step.order ?? i,
}))
);
}
}
});
const updated = await getOwnedRecipe(id, session!.user.id);
void dispatchWebhook(session!.user.id, "recipe.updated", { id, title: updated?.title });
return NextResponse.json(updated);
}
export async function DELETE(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req, { rateLimit: { limit: 60, windowSeconds: 60 } });
if (response) return response;
const { id } = await params;
const existing = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)),
});
if (!existing) return NextResponse.json({ error: "Not found" }, { status: 404 });
await db.delete(recipes).where(eq(recipes.id, id));
void dispatchWebhook(session!.user.id, "recipe.deleted", { id });
return new NextResponse(null, { status: 204 });
}
@@ -0,0 +1,148 @@
import { NextRequest, NextResponse } from "next/server";
import { db, recipes, recipeIngredients, recipeSteps, recipeSnapshots } from "@epicure/db";
import { eq, and, max, desc } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
type Params = { params: Promise<{ id: string; versionId: string }> };
export async function GET(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req, { rateLimit: { limit: 60, windowSeconds: 60 } });
if (response) return response;
const { id, versionId } = await params;
// Verify ownership
const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)),
});
if (!recipe) return NextResponse.json({ error: "Not found" }, { status: 404 });
const snapshot = await db.query.recipeSnapshots.findFirst({
where: and(
eq(recipeSnapshots.id, versionId),
eq(recipeSnapshots.recipeId, id),
eq(recipeSnapshots.authorId, session!.user.id)
),
});
if (!snapshot) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json(snapshot);
}
export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req, { rateLimit: { limit: 60, windowSeconds: 60 } });
if (response) return response;
const { id, versionId } = await params;
const body = await req.json() as { action?: string };
if (body.action !== "restore") {
return NextResponse.json({ error: "Invalid action" }, { status: 400 });
}
// Verify ownership and get current recipe with relations
const currentRecipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)),
with: { ingredients: { orderBy: (t, { asc }) => asc(t.order) }, steps: { orderBy: (t, { asc }) => asc(t.order) } },
});
if (!currentRecipe) return NextResponse.json({ error: "Not found" }, { status: 404 });
// Get the snapshot to restore
const snapshot = await db.query.recipeSnapshots.findFirst({
where: and(
eq(recipeSnapshots.id, versionId),
eq(recipeSnapshots.recipeId, id),
eq(recipeSnapshots.authorId, session!.user.id)
),
});
if (!snapshot) return NextResponse.json({ error: "Snapshot not found" }, { status: 404 });
// Create a snapshot of the current state before restoring
const [maxVersionRow] = await db
.select({ v: max(recipeSnapshots.version) })
.from(recipeSnapshots)
.where(eq(recipeSnapshots.recipeId, id));
const nextVersion = (maxVersionRow?.v ?? 0) + 1;
await db.insert(recipeSnapshots).values({
id: crypto.randomUUID(),
recipeId: id,
authorId: session!.user.id,
version: nextVersion,
title: currentRecipe.title,
snapshotData: {
title: currentRecipe.title,
description: currentRecipe.description,
baseServings: currentRecipe.baseServings,
difficulty: currentRecipe.difficulty,
prepMins: currentRecipe.prepMins,
cookMins: currentRecipe.cookMins,
dietaryTags: currentRecipe.dietaryTags ?? {},
ingredients: currentRecipe.ingredients.map((i) => ({
rawName: i.rawName,
quantity: i.quantity,
unit: i.unit,
note: i.note,
order: i.order,
})),
steps: currentRecipe.steps.map((s) => ({
instruction: s.instruction,
timerSeconds: s.timerSeconds,
order: s.order,
})),
},
});
// Restore the recipe from the snapshot
const data = snapshot.snapshotData as {
title: string;
description?: string | null;
baseServings: number;
difficulty?: string | null;
prepMins?: number | null;
cookMins?: number | null;
dietaryTags?: Record<string, boolean>;
ingredients: Array<{ rawName: string; quantity?: string | null; unit?: string | null; note?: string | null; order: number }>;
steps: Array<{ instruction: string; timerSeconds?: number | null; order: number }>;
};
await db.transaction(async (tx) => {
await tx.update(recipes).set({
title: data.title,
description: data.description ?? null,
baseServings: data.baseServings,
difficulty: (data.difficulty as "easy" | "medium" | "hard" | null) ?? null,
prepMins: data.prepMins ?? null,
cookMins: data.cookMins ?? null,
dietaryTags: data.dietaryTags ?? {},
updatedAt: new Date(),
}).where(eq(recipes.id, id));
await tx.delete(recipeIngredients).where(eq(recipeIngredients.recipeId, id));
if (data.ingredients.length > 0) {
await tx.insert(recipeIngredients).values(
data.ingredients.map((ing) => ({
id: crypto.randomUUID(),
recipeId: id,
rawName: ing.rawName,
quantity: ing.quantity ?? undefined,
unit: ing.unit ?? undefined,
note: ing.note ?? undefined,
order: ing.order,
}))
);
}
await tx.delete(recipeSteps).where(eq(recipeSteps.recipeId, id));
if (data.steps.length > 0) {
await tx.insert(recipeSteps).values(
data.steps.map((step) => ({
id: crypto.randomUUID(),
recipeId: id,
instruction: step.instruction,
timerSeconds: step.timerSeconds ?? undefined,
order: step.order,
}))
);
}
});
return NextResponse.json({ ok: true });
}
@@ -0,0 +1,32 @@
import { NextRequest, NextResponse } from "next/server";
import { db, recipes, recipeSnapshots } from "@epicure/db";
import { eq, and, desc } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
type Params = { params: Promise<{ id: string }> };
export async function GET(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req, { rateLimit: { limit: 60, windowSeconds: 60 } });
if (response) return response;
const { id } = await params;
// Verify ownership
const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)),
});
if (!recipe) return NextResponse.json({ error: "Not found" }, { status: 404 });
const versions = await db
.select({
id: recipeSnapshots.id,
version: recipeSnapshots.version,
title: recipeSnapshots.title,
createdAt: recipeSnapshots.createdAt,
})
.from(recipeSnapshots)
.where(and(eq(recipeSnapshots.recipeId, id), eq(recipeSnapshots.authorId, session!.user.id)))
.orderBy(desc(recipeSnapshots.version))
.limit(20);
return NextResponse.json(versions);
}
+45
View File
@@ -0,0 +1,45 @@
import { type NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireSession } from "@/lib/api-auth";
import { db, recipes, eq, and, inArray } from "@epicure/db";
const BulkDeleteSchema = z.object({
ids: z.array(z.string()).min(1).max(100),
});
const BulkUpdateSchema = z.object({
ids: z.array(z.string()).min(1).max(100),
visibility: z.enum(["private", "unlisted", "public"]).optional(),
});
export async function DELETE(req: NextRequest) {
const session = await requireSession();
if (session instanceof NextResponse) return session;
const body = BulkDeleteSchema.safeParse(await req.json());
if (!body.success) return NextResponse.json({ error: "Invalid request" }, { status: 400 });
await db
.delete(recipes)
.where(and(inArray(recipes.id, body.data.ids), eq(recipes.authorId, session.user.id)));
return NextResponse.json({ ok: true });
}
export async function PATCH(req: NextRequest) {
const session = await requireSession();
if (session instanceof NextResponse) return session;
const body = BulkUpdateSchema.safeParse(await req.json());
if (!body.success) return NextResponse.json({ error: "Invalid request" }, { status: 400 });
const { ids, visibility } = body.data;
if (!visibility) return NextResponse.json({ error: "Nothing to update" }, { status: 400 });
await db
.update(recipes)
.set({ visibility, updatedAt: new Date() })
.where(and(inArray(recipes.id, ids), eq(recipes.authorId, session.user.id)));
return NextResponse.json({ ok: true });
}
+167
View File
@@ -0,0 +1,167 @@
import { NextRequest, NextResponse } from "next/server";
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
import { eq, desc, and } from "@epicure/db";
import { z } from "zod";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { checkTierLimit, incrementUsage } from "@/lib/tiers";
import { dispatchWebhook } from "@/lib/webhooks";
const UNICODE_FRACTIONS: Record<string, number> = {
"½": 0.5, "⅓": 1/3, "⅔": 2/3, "¼": 0.25, "¾": 0.75,
"⅕": 0.2, "⅖": 0.4, "⅗": 0.6, "⅘": 0.8,
"⅙": 1/6, "⅚": 5/6, "⅛": 0.125, "⅜": 0.375, "⅝": 0.625, "⅞": 0.875,
};
function parseQuantity(v: string | number | undefined): string | undefined {
if (v === undefined || v === "") return undefined;
const s = String(v).trim();
if (!s) return undefined;
if (UNICODE_FRACTIONS[s] !== undefined) return String(UNICODE_FRACTIONS[s]);
for (const [frac, val] of Object.entries(UNICODE_FRACTIONS)) {
if (s.endsWith(frac)) {
const whole = s.slice(0, -frac.length).trim();
if (!whole) return String(val);
const w = parseFloat(whole);
if (!isNaN(w)) return String(w + val);
}
}
const mixed = s.match(/^(\d+)\s+(\d+)\s*\/\s*(\d+)$/);
if (mixed) {
const den = parseInt(mixed[3]!);
if (den !== 0) return String(parseInt(mixed[1]!) + parseInt(mixed[2]!) / den);
}
const slash = s.match(/^(\d+)\s*\/\s*(\d+)$/);
if (slash) {
const den = parseInt(slash[2]!);
if (den !== 0) return String(parseInt(slash[1]!) / den);
}
const n = parseFloat(s);
return isNaN(n) ? undefined : String(n);
}
const CreateRecipeSchema = z.object({
title: z.string().min(1).max(200),
description: z.string().optional(),
baseServings: z.number().int().min(1).max(100).default(4),
visibility: z.enum(["private", "unlisted", "public"]).default("private"),
difficulty: z.enum(["easy", "medium", "hard"]).optional(),
prepMins: z.number().int().min(0).optional(),
cookMins: z.number().int().min(0).optional(),
aiGenerated: z.boolean().optional(),
dietaryTags: z.object({
vegan: z.boolean().optional(),
vegetarian: z.boolean().optional(),
glutenFree: z.boolean().optional(),
dairyFree: z.boolean().optional(),
nutFree: z.boolean().optional(),
halal: z.boolean().optional(),
kosher: z.boolean().optional(),
}).optional(),
ingredients: z.array(z.object({
rawName: z.string().min(1),
quantity: z.union([z.number(), z.string()]).optional().transform(parseQuantity),
unit: z.string().optional(),
note: z.string().optional(),
order: z.number().int().default(0),
})).default([]),
steps: z.array(z.object({
instruction: z.string().min(1),
timerSeconds: z.number().int().optional(),
order: z.number().int().optional(),
})).default([]),
});
export async function GET(req: NextRequest) {
const { session, response } = await requireSessionOrApiKey(req, { rateLimit: { limit: 60, windowSeconds: 60 } });
if (response) return response;
const { searchParams } = new URL(req.url);
const limit = Math.min(parseInt(searchParams.get("limit") ?? "20"), 100);
const offset = parseInt(searchParams.get("offset") ?? "0");
const visibility = searchParams.get("visibility") as "private" | "unlisted" | "public" | null;
const conditions = [eq(recipes.authorId, session!.user.id)];
if (visibility) conditions.push(eq(recipes.visibility, visibility));
const rows = await db
.select()
.from(recipes)
.where(and(...conditions))
.orderBy(desc(recipes.updatedAt))
.limit(limit)
.offset(offset);
return NextResponse.json({ data: rows, limit, offset });
}
export async function POST(req: NextRequest) {
const { session, response } = await requireSessionOrApiKey(req, { rateLimit: { limit: 60, windowSeconds: 60 } });
if (response) return response;
const body = await req.json() as unknown;
const parsed = CreateRecipeSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
await checkTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "recipe");
const id = crypto.randomUUID();
const now = new Date();
const data = parsed.data;
await db.transaction(async (tx) => {
await tx.insert(recipes).values({
id,
authorId: session!.user.id,
title: data.title,
description: data.description,
baseServings: data.baseServings,
visibility: data.visibility,
difficulty: data.difficulty,
prepMins: data.prepMins,
cookMins: data.cookMins,
dietaryTags: data.dietaryTags ?? {},
aiGenerated: data.aiGenerated ?? false,
createdAt: now,
updatedAt: now,
});
if (data.ingredients.length > 0) {
await tx.insert(recipeIngredients).values(
data.ingredients.map((ing, i) => ({
id: crypto.randomUUID(),
recipeId: id,
rawName: ing.rawName,
quantity: ing.quantity,
unit: ing.unit,
note: ing.note,
order: ing.order ?? i,
}))
);
}
if (data.steps.length > 0) {
await tx.insert(recipeSteps).values(
data.steps.map((step, i) => ({
id: crypto.randomUUID(),
recipeId: id,
instruction: step.instruction,
timerSeconds: step.timerSeconds,
order: step.order ?? i,
}))
);
}
});
await incrementUsage(session!.user.id, "recipe");
const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
void dispatchWebhook(session!.user.id, "recipe.created", { id, title: data.title });
return NextResponse.json(recipe, { status: 201 });
}