feat: misc — cooking mode, OpenAPI docs, email, storage, upload, homepage

Cooking mode step-by-step view. OpenAPI 3.1 spec auto-generated from Zod schemas.
Email lib (resend). Redis client. S3 storage helper. Photo upload endpoint.
Landing page. Short recipe URL redirect /r/[id]. API docs page.
This commit is contained in:
Arnaud
2026-07-01 08:11:31 +02:00
parent 3f96d1ea41
commit 9d9dfb46c6
26 changed files with 1427 additions and 0 deletions
+37
View File
@@ -0,0 +1,37 @@
import { NextResponse } from "next/server";
const HTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Epicure API Docs</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" />
<style>
body { margin: 0; }
.swagger-ui .topbar { background-color: #18181b; }
.swagger-ui .topbar .download-url-wrapper .select-label select { border-color: #52525b; }
</style>
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
<script>
SwaggerUIBundle({
url: "/api/v1/openapi.json",
dom_id: "#swagger-ui",
presets: [SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset],
layout: "BaseLayout",
deepLinking: true,
tryItOutEnabled: true,
persistAuthorization: true,
});
</script>
</body>
</html>`;
export async function GET() {
return new NextResponse(HTML, {
headers: { "Content-Type": "text/html; charset=utf-8" },
});
}
@@ -0,0 +1,18 @@
import { NextResponse } from "next/server";
import { db, userAiKeys, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
type Params = { params: Promise<{ provider: string }> };
export async function DELETE(_req: Request, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { provider } = await params;
await db.delete(userAiKeys).where(
and(eq(userAiKeys.userId, session!.user.id), eq(userAiKeys.provider, provider))
);
return NextResponse.json({ ok: true });
}
+56
View File
@@ -0,0 +1,56 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { db, userAiKeys, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { encrypt } from "@/lib/encrypt";
const VALID_PROVIDERS = ["openai", "anthropic", "openrouter", "ollama"] as const;
const PostSchema = z.object({
provider: z.enum(VALID_PROVIDERS),
apiKey: z.string().min(1).max(500),
});
export async function GET() {
const { session, response } = await requireSession();
if (response) return response;
const keys = await db.query.userAiKeys.findMany({
where: eq(userAiKeys.userId, session!.user.id),
columns: { provider: true, createdAt: true },
});
return NextResponse.json({ keys });
}
export async function POST(req: Request) {
const { session, response } = await requireSession();
if (response) return response;
const body = PostSchema.safeParse(await req.json());
if (!body.success) return NextResponse.json({ error: body.error.flatten() }, { status: 400 });
const { provider, apiKey } = body.data;
const userId = session!.user.id;
const existing = await db.query.userAiKeys.findFirst({
where: and(eq(userAiKeys.userId, userId), eq(userAiKeys.provider, provider)),
});
const encryptedKey = encrypt(apiKey);
if (existing) {
await db.update(userAiKeys)
.set({ encryptedKey })
.where(and(eq(userAiKeys.userId, userId), eq(userAiKeys.provider, provider)));
} else {
await db.insert(userAiKeys).values({
id: crypto.randomUUID(),
userId,
provider,
encryptedKey,
});
}
return NextResponse.json({ ok: true });
}
@@ -0,0 +1,39 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, comments, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
type Params = { params: Promise<{ id: string }> };
export async function PUT(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
const comment = await db.query.comments.findFirst({ where: eq(comments.id, id) });
if (!comment || comment.userId !== session!.user.id) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const body = await req.json() as unknown;
const parsed = z.object({ content: z.string().min(1).max(5000) }).safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
await db.update(comments).set({ content: parsed.data.content, updatedAt: new Date() }).where(eq(comments.id, id));
return NextResponse.json({ updated: true });
}
export async function DELETE(_req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
const comment = await db.query.comments.findFirst({ where: eq(comments.id, id) });
if (!comment) return NextResponse.json({ error: "Not found" }, { status: 404 });
if (comment.userId !== session!.user.id && session!.user.role === "user") {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
await db.delete(comments).where(eq(comments.id, id));
return new NextResponse(null, { status: 204 });
}
+51
View File
@@ -0,0 +1,51 @@
import { NextRequest, NextResponse } from "next/server";
import { db, recipes, users, userFollows, eq } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { desc, inArray } from "@epicure/db";
export async function GET(req: NextRequest) {
const { session, response } = await requireSession();
if (response) return response;
const { searchParams } = new URL(req.url);
const limit = Math.min(parseInt(searchParams.get("limit") ?? "20"), 50);
const offset = parseInt(searchParams.get("offset") ?? "0");
// Get IDs of users the current user follows
const followedRows = await db
.select({ followingId: userFollows.followingId })
.from(userFollows)
.where(eq(userFollows.followerId, session!.user.id));
const followedIds = followedRows.map((r) => r.followingId);
if (followedIds.length === 0) {
return NextResponse.json({ data: [], limit, offset, message: "Follow some users to see their recipes here." });
}
const feedRecipes = await db
.select({
id: recipes.id,
title: recipes.title,
description: recipes.description,
baseServings: recipes.baseServings,
prepMins: recipes.prepMins,
cookMins: recipes.cookMins,
difficulty: recipes.difficulty,
visibility: recipes.visibility,
createdAt: recipes.createdAt,
updatedAt: recipes.updatedAt,
authorId: recipes.authorId,
authorName: users.name,
authorUsername: users.username,
authorAvatarUrl: users.avatarUrl,
})
.from(recipes)
.innerJoin(users, eq(recipes.authorId, users.id))
.where((t) => inArray(t.authorId, followedIds))
.orderBy(desc(recipes.createdAt))
.limit(limit)
.offset(offset);
return NextResponse.json({ data: feedRecipes, limit, offset });
}
@@ -0,0 +1,42 @@
import { NextRequest, NextResponse } from "next/server";
import { db, recipes, users, favorites, eq, desc, sql, and, gte } from "@epicure/db";
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const limit = Math.min(parseInt(searchParams.get("limit") ?? "20"), 50);
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
const trending = await db
.select({
id: recipes.id,
title: recipes.title,
description: recipes.description,
baseServings: recipes.baseServings,
prepMins: recipes.prepMins,
cookMins: recipes.cookMins,
difficulty: recipes.difficulty,
visibility: recipes.visibility,
aiGenerated: recipes.aiGenerated,
createdAt: recipes.createdAt,
authorId: recipes.authorId,
authorName: users.name,
authorUsername: users.username,
authorAvatarUrl: users.avatarUrl,
favoriteCount: sql<number>`cast(count(${favorites.recipeId}) as int)`,
})
.from(recipes)
.innerJoin(users, eq(recipes.authorId, users.id))
.leftJoin(
favorites,
and(eq(favorites.recipeId, recipes.id), gte(favorites.createdAt, sevenDaysAgo))
)
.where(eq(recipes.visibility, "public"))
.groupBy(recipes.id, users.id)
.orderBy(desc(sql`count(${favorites.recipeId})`), desc(recipes.createdAt))
.limit(limit);
return NextResponse.json({
data: trending.map((r) => ({ ...r, createdAt: r.createdAt.toISOString() })),
});
}
@@ -0,0 +1,8 @@
import { generateOpenApiSpec } from "@/lib/openapi";
export async function GET() {
const spec = generateOpenApiSpec();
return Response.json(spec, {
headers: { "Access-Control-Allow-Origin": "*" },
});
}
@@ -0,0 +1,31 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireSession } from "@/lib/api-auth";
import { createPresignedUploadUrl } from "@/lib/storage";
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp", "image/avif"] as const;
type AllowedType = (typeof ALLOWED_TYPES)[number];
const Schema = z.object({
contentType: z.string().refine((t): t is AllowedType => (ALLOWED_TYPES as readonly string[]).includes(t), {
message: "Content type must be jpeg, png, webp, or avif",
}),
recipeId: z.string().uuid(),
});
export async function POST(req: NextRequest) {
const { session, response } = await requireSession();
if (response) return response;
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
const ext = parsed.data.contentType.split("/")[1] ?? "jpg";
const key = `recipes/${parsed.data.recipeId}/photos/${session!.user.id}-${crypto.randomUUID()}.${ext}`;
const url = await createPresignedUploadUrl(key, parsed.data.contentType);
return NextResponse.json({ url, key });
}
+15
View File
@@ -0,0 +1,15 @@
export async function GET() {
const html = `<!DOCTYPE html>
<html>
<head>
<title>Epicure API Reference</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<script id="api-reference" data-url="/api/v1/openapi.json"></script>
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
</body>
</html>`;
return new Response(html, { headers: { "Content-Type": "text/html" } });
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+5
View File
@@ -0,0 +1,5 @@
import { redirect } from "next/navigation";
export default function RootPage() {
redirect("/recipes");
}
+172
View File
@@ -0,0 +1,172 @@
import type { Metadata } from "next";
import Script from "next/script";
import { notFound } from "next/navigation";
import { headers } from "next/headers";
import Link from "next/link";
import { Clock, Users, ChefHat, Globe } from "lucide-react";
import { auth } from "@/lib/auth/server";
import { db, recipes, eq } from "@epicure/db";
import { Badge } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { ServingScaler } from "@/components/recipe/serving-scaler";
import { getPublicUrl } from "@/lib/storage";
import { cn } from "@/lib/utils";
type Params = { params: Promise<{ id: string }> };
export async function generateMetadata({ params }: Params): Promise<Metadata> {
const { id } = await params;
const recipe = await db.query.recipes.findFirst({
where: (r, { and, eq }) => and(eq(r.id, id), eq(r.visibility, "public")),
});
if (!recipe) return {};
return {
title: recipe.title,
description: recipe.description ?? undefined,
openGraph: {
title: recipe.title,
description: recipe.description ?? undefined,
type: "article",
},
};
}
const DIETARY_LABELS: Record<string, string> = {
vegan: "Vegan", vegetarian: "Vegetarian", glutenFree: "Gluten-free",
dairyFree: "Dairy-free", nutFree: "Nut-free", halal: "Halal", kosher: "Kosher",
};
export default async function PublicRecipePage({ params }: Params) {
const { id } = await params;
const session = await auth.api.getSession({ headers: await headers() }).catch(() => null);
const recipe = await db.query.recipes.findFirst({
where: (r, { and, eq, ne }) => and(eq(r.id, id), ne(r.visibility, "private")),
with: {
author: true,
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
steps: { orderBy: (t, { asc }) => asc(t.order) },
photos: { orderBy: (t, { asc }) => asc(t.order) },
},
});
if (!recipe) notFound();
const cover = recipe.photos.find((p) => p.isCover) ?? recipe.photos[0];
const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0);
const activeTags = Object.entries(recipe.dietaryTags ?? {})
.filter(([, v]) => v).map(([k]) => DIETARY_LABELS[k]).filter(Boolean);
const jsonLd = {
"@context": "https://schema.org",
"@type": "Recipe",
name: recipe.title,
description: recipe.description,
author: { "@type": "Person", name: recipe.author.name },
recipeYield: String(recipe.baseServings),
prepTime: recipe.prepMins ? `PT${recipe.prepMins}M` : undefined,
cookTime: recipe.cookMins ? `PT${recipe.cookMins}M` : undefined,
recipeIngredient: recipe.ingredients.map((i) =>
[i.quantity, i.unit, i.rawName].filter(Boolean).join(" ")
),
recipeInstructions: recipe.steps.map((s) => ({
"@type": "HowToStep",
text: s.instruction,
})),
image: cover ? [getPublicUrl(cover.storageKey)] : undefined,
};
return (
<>
<Script id="recipe-jsonld" type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />
<div className="container mx-auto max-w-3xl px-4 py-8 space-y-8">
{/* Breadcrumb-style nav */}
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Globe className="h-3.5 w-3.5" />
<span>Public recipe by</span>
<Link href={`/u/${recipe.author.username ?? recipe.author.id}`} className="hover:text-foreground font-medium">
{recipe.author.name}
</Link>
{session && (
<div className="ml-auto">
<Link href={`/recipes/${id}`} className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
View in your library
</Link>
</div>
)}
{!session && (
<div className="ml-auto flex items-center gap-2">
<Link href="/signup" className={cn(buttonVariants({ size: "sm" }))}>Sign up free</Link>
<Link href="/login" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>Log in</Link>
</div>
)}
</div>
<div className="space-y-4">
<h1 className="text-3xl font-bold tracking-tight">{recipe.title}</h1>
{recipe.description && (
<p className="text-muted-foreground leading-relaxed">{recipe.description}</p>
)}
<div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
{recipe.difficulty && <Badge>{recipe.difficulty}</Badge>}
<span className="flex items-center gap-1"><Users className="h-4 w-4" />{recipe.baseServings} servings</span>
{recipe.prepMins && <span className="flex items-center gap-1"><Clock className="h-4 w-4" />{recipe.prepMins}m prep</span>}
{recipe.cookMins && <span className="flex items-center gap-1"><ChefHat className="h-4 w-4" />{recipe.cookMins}m cook</span>}
{totalMins > 0 && recipe.prepMins && recipe.cookMins && <span>({totalMins}m total)</span>}
</div>
{activeTags.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{activeTags.map((tag) => <Badge key={tag} variant="secondary" className="text-xs">{tag}</Badge>)}
</div>
)}
</div>
{cover && (
<div className="aspect-video overflow-hidden rounded-xl bg-muted">
<img src={getPublicUrl(cover.storageKey)} alt={recipe.title} className="w-full h-full object-cover" />
</div>
)}
<Separator />
{recipe.ingredients.length > 0 && (
<div className="space-y-4">
<h2 className="text-xl font-semibold">Ingredients</h2>
<ServingScaler
baseServings={recipe.baseServings}
ingredients={recipe.ingredients.map((ing) => ({
id: ing.id, rawName: ing.rawName, quantity: ing.quantity, unit: ing.unit, note: ing.note, order: ing.order,
}))}
/>
</div>
)}
{recipe.steps.length > 0 && (
<>
<Separator />
<div className="space-y-6">
<h2 className="text-xl font-semibold">Instructions</h2>
<ol className="space-y-6">
{recipe.steps.map((step, i) => (
<li key={step.id} className="flex gap-4">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-bold">{i + 1}</div>
<p className="flex-1 pt-1 leading-relaxed">{step.instruction}</p>
</li>
))}
</ol>
</div>
</>
)}
{!session && (
<div className="rounded-xl border bg-muted/40 p-6 text-center space-y-3">
<p className="font-semibold">Want to save this recipe?</p>
<p className="text-sm text-muted-foreground">Create a free account to save recipes, scale servings, and build your own library.</p>
<Link href="/signup" className={cn(buttonVariants())}>Get started free</Link>
</div>
)}
</div>
</>
);
}