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
+106
View File
@@ -0,0 +1,106 @@
import nodemailer from "nodemailer";
function getTransport() {
const host = process.env["SMTP_HOST"];
if (!host) return null;
return nodemailer.createTransport({
host,
port: parseInt(process.env["SMTP_PORT"] ?? "587"),
secure: process.env["SMTP_SECURE"] === "true",
auth: {
user: process.env["SMTP_USER"],
pass: process.env["SMTP_PASS"],
},
});
}
const FROM = process.env["SMTP_FROM"] ?? "Epicure <noreply@epicure.app>";
export async function sendEmail({
to,
subject,
html,
}: {
to: string;
subject: string;
html: string;
}) {
const transport = getTransport();
if (!transport) {
console.log(`[email:dev] No SMTP_HOST — logging email instead.\n Subject: ${subject}\n To: ${to}\n Body: ${html.replace(/<[^>]+>/g, "").slice(0, 200)}`);
return;
}
try {
const info = await transport.sendMail({ from: FROM, to, subject, html });
console.log(`[email:sent] "${subject}" → ${to} | id:${info.messageId} | response:${info.response}`);
} catch (err) {
console.error(`[email:error] "${subject}" → ${to} |`, err);
throw err;
}
}
// ── Templates ─────────────────────────────────────────────────────────────────
function layout(title: string, body: string) {
return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>${title}</title>
</head>
<body style="margin:0;padding:0;background:#fafaf9;font-family:Georgia,serif;color:#1c1917;">
<table width="100%" cellpadding="0" cellspacing="0" style="padding:40px 20px;">
<tr><td align="center">
<table width="560" cellpadding="0" cellspacing="0" style="background:#fff;border-radius:12px;overflow:hidden;border:1px solid #e7e5e4;">
<tr><td style="padding:32px 40px;border-bottom:1px solid #e7e5e4;">
<span style="font-size:22px;font-weight:bold;letter-spacing:-0.5px;">🍴 Epicure</span>
</td></tr>
<tr><td style="padding:40px;">
${body}
</td></tr>
<tr><td style="padding:24px 40px;background:#fafaf9;border-top:1px solid #e7e5e4;">
<p style="margin:0;font-size:12px;color:#78716c;">You received this email from Epicure. If you didn't request it, ignore this email.</p>
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>`;
}
function btn(href: string, label: string) {
return `<a href="${href}" style="display:inline-block;background:#1c1917;color:#fff;padding:12px 24px;border-radius:8px;text-decoration:none;font-size:15px;font-weight:600;margin:24px 0;">${label}</a>`;
}
export function verifyEmailHtml(url: string) {
return layout(
"Verify your email — Epicure",
`<h1 style="margin:0 0 8px;font-size:24px;">Verify your email</h1>
<p style="margin:0 0 4px;color:#57534e;line-height:1.6;">Click the button below to verify your email address and activate your Epicure account.</p>
${btn(url, "Verify email")}
<p style="margin:16px 0 0;font-size:13px;color:#a8a29e;">Link expires in 24 hours. Or paste this URL into your browser:<br/>
<a href="${url}" style="color:#78716c;font-size:12px;word-break:break-all;">${url}</a></p>`
);
}
export function resetPasswordHtml(url: string) {
return layout(
"Reset your password — Epicure",
`<h1 style="margin:0 0 8px;font-size:24px;">Reset your password</h1>
<p style="margin:0 0 4px;color:#57534e;line-height:1.6;">We received a request to reset the password for your Epicure account.</p>
${btn(url, "Reset password")}
<p style="margin:16px 0 0;font-size:13px;color:#a8a29e;">Link expires in 1 hour. If you didn't request a reset, you can safely ignore this email.</p>`
);
}
export function welcomeHtml(name: string) {
return layout(
"Welcome to Epicure",
`<h1 style="margin:0 0 8px;font-size:24px;">Welcome, ${name}!</h1>
<p style="margin:0 0 16px;color:#57534e;line-height:1.6;">Your account is ready. Start by creating your first recipe, importing from a URL, or letting AI generate one for you.</p>
${btn(process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000", "Go to Epicure")}
<p style="margin:16px 0 0;font-size:13px;color:#a8a29e;">Questions? Just reply to this email.</p>`
);
}
+45
View File
@@ -0,0 +1,45 @@
const FRACTIONS: [number, string][] = [
[1 / 8, "⅛"],
[1 / 4, "¼"],
[1 / 3, "⅓"],
[3 / 8, "⅜"],
[1 / 2, "½"],
[5 / 8, "⅝"],
[2 / 3, "⅔"],
[3 / 4, "¾"],
[7 / 8, "⅞"],
];
export function formatQuantity(value: number): string {
if (value === 0) return "0";
const whole = Math.floor(value);
const decimal = value - whole;
if (decimal < 0.05) return whole === 0 ? "0" : String(whole);
if (decimal > 0.95) return String(whole + 1);
let bestFraction = "";
let bestDiff = Infinity;
for (const [frac, symbol] of FRACTIONS) {
const diff = Math.abs(decimal - frac);
if (diff < bestDiff) {
bestDiff = diff;
bestFraction = symbol;
}
}
if (bestDiff > 0.06) {
return value.toFixed(1);
}
return whole === 0 ? bestFraction : `${whole} ${bestFraction}`;
}
export function scaleQuantity(baseQuantity: string | null, base: number, desired: number): string {
if (!baseQuantity) return "";
const raw = parseFloat(baseQuantity);
if (isNaN(raw)) return baseQuantity;
const scale = base === 0 ? 1 : desired / base;
return formatQuantity(raw * scale);
}
+141
View File
@@ -0,0 +1,141 @@
import {
OpenApiGeneratorV31,
OpenAPIRegistry,
extendZodWithOpenApi,
} from "@asteasolutions/zod-to-openapi";
import { z } from "zod";
// Nothing at module level — Next.js evaluates route modules at build time to
// determine static vs dynamic, which would run registry.register() before
// extendZodWithOpenApi patches the Zod prototype. Wrap everything lazily.
let cachedSpec: object | null = null;
export function generateOpenApiSpec(): object {
if (cachedSpec) return cachedSpec;
extendZodWithOpenApi(z);
const registry = new OpenAPIRegistry();
const security: Array<Record<string, string[]>> = [{ SessionCookie: [] }, { BearerApiKey: [] }];
registry.registerComponent("securitySchemes", "SessionCookie", { type: "apiKey", in: "cookie", name: "better-auth.session_token" });
registry.registerComponent("securitySchemes", "BearerApiKey", { type: "http", scheme: "bearer", bearerFormat: "ek_..." });
const DietaryTagsRef = registry.register("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(),
}));
const RecipeIngredientRef = registry.register("RecipeIngredient", z.object({
id: z.string(), rawName: z.string(), quantity: z.number().nullable(),
unit: z.string().nullable(), note: z.string().nullable(), order: z.number().int(),
}));
const RecipeStepRef = registry.register("RecipeStep", z.object({
id: z.string(), order: z.number().int(), instruction: z.string(), timerSeconds: z.number().int().nullable(),
}));
const RecipeRef = registry.register("Recipe", z.object({
id: z.string(), authorId: z.string(), title: z.string(), description: z.string().nullable(),
baseServings: z.number().int(), visibility: z.enum(["private", "unlisted", "public"]),
difficulty: z.enum(["easy", "medium", "hard"]).nullable(),
prepMins: z.number().int().nullable(), cookMins: z.number().int().nullable(),
dietaryTags: DietaryTagsRef, aiGenerated: z.boolean(),
ingredients: z.array(RecipeIngredientRef), steps: z.array(RecipeStepRef),
createdAt: z.string().datetime(), updatedAt: z.string().datetime(),
}));
const CreateRecipeRef = registry.register("CreateRecipe", z.object({
title: z.string().min(1).max(200), description: z.string().optional(),
baseServings: z.number().int().positive(), visibility: z.enum(["private", "unlisted", "public"]),
difficulty: z.enum(["easy", "medium", "hard"]).optional(),
prepMins: z.number().int().positive().optional(), cookMins: z.number().int().positive().optional(),
dietaryTags: DietaryTagsRef.optional(),
ingredients: z.array(z.object({ rawName: z.string(), quantity: z.number().nullable(), unit: z.string().nullable(), note: z.string().nullable(), order: z.number().int() })),
steps: z.array(z.object({ order: z.number().int(), instruction: z.string(), timerSeconds: z.number().int().nullable() })),
}));
const ApiErrorRef = registry.register("ApiError", z.object({ error: z.string() }));
const Pagination = z.object({ page: z.coerce.number().default(1), limit: z.coerce.number().default(20) });
const CommentRef = registry.register("Comment", z.object({
id: z.string(), recipeId: z.string(), userId: z.string(),
body: z.string(), parentId: z.string().nullable(), createdAt: z.string().datetime(),
}));
const CollectionRef = registry.register("Collection", z.object({
id: z.string(), userId: z.string(), name: z.string(),
description: z.string().nullable(), isPublic: z.boolean(), createdAt: z.string().datetime(),
}));
const MealPlanRef = registry.register("MealPlan", z.object({
weekStart: z.string(),
entries: z.array(z.object({ id: z.string(), dayOfWeek: z.number(), mealType: z.string(), recipeId: z.string(), servings: z.number() })),
}));
const PantryItemRef = registry.register("PantryItem", z.object({
id: z.string(), rawName: z.string(), quantity: z.string().nullable(),
unit: z.string().nullable(), expiresAt: z.string().datetime().nullable(),
}));
const ShoppingListRef = registry.register("ShoppingList", z.object({
id: z.string(), name: z.string(), generatedAt: z.string().datetime().nullable(), createdAt: z.string().datetime(),
items: z.array(z.object({ id: z.string(), rawName: z.string(), quantity: z.string().nullable(), unit: z.string().nullable(), aisle: z.string().nullable(), checked: z.boolean() })),
}));
const ApiKeyRef = registry.register("ApiKey", z.object({
id: z.string(), name: z.string(), lastUsedAt: z.string().datetime().nullable(), createdAt: z.string().datetime(),
}));
const CreateApiKeyResponseRef = registry.register("CreateApiKeyResponse", z.object({
id: z.string(), name: z.string(), key: z.string().describe("Full key — shown once"), createdAt: z.string().datetime(),
}));
const AiGeneratedRef = registry.register("AiGeneratedRecipe", z.object({
title: z.string(), description: z.string(), baseServings: z.number(),
difficulty: z.enum(["easy", "medium", "hard"]),
prepMins: z.number().nullable(), cookMins: z.number().nullable(),
dietaryTags: DietaryTagsRef,
ingredients: z.array(z.object({ rawName: z.string(), quantity: z.number().nullable(), unit: z.string().nullable(), note: z.string().nullable() })),
steps: z.array(z.object({ instruction: z.string(), timerSeconds: z.number().nullable() })),
}));
const PaginatedRecipes = z.object({
data: z.array(RecipeRef),
pagination: z.object({ page: z.number(), limit: z.number(), total: z.number(), pages: z.number() }),
});
const idParam = z.object({ id: z.string() });
registry.registerPath({ method: "get", path: "/api/v1/recipes", summary: "List recipes", security, request: { query: z.object({ page: z.coerce.number().default(1), limit: z.coerce.number().default(20), visibility: z.enum(["private", "unlisted", "public"]).optional(), q: z.string().optional(), difficulty: z.enum(["easy", "medium", "hard"]).optional() }) }, responses: { 200: { description: "Paginated", content: { "application/json": { schema: PaginatedRecipes } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/recipes", summary: "Create recipe", security, request: { body: { content: { "application/json": { schema: CreateRecipeRef } }, required: true } }, responses: { 201: { description: "Created", content: { "application/json": { schema: RecipeRef } } }, 400: { description: "Bad request", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/recipes/{id}", summary: "Get recipe", security, request: { params: idParam }, responses: { 200: { description: "Recipe", content: { "application/json": { schema: RecipeRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "put", path: "/api/v1/recipes/{id}", summary: "Update recipe", security, request: { params: idParam, body: { content: { "application/json": { schema: CreateRecipeRef } }, required: true } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: RecipeRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "delete", path: "/api/v1/recipes/{id}", summary: "Delete recipe", security, request: { params: idParam }, responses: { 204: { description: "Deleted" }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/recipes/{id}/favorite", summary: "Toggle favorite", security, request: { params: idParam }, responses: { 200: { description: "Favorited", content: { "application/json": { schema: z.object({ favorited: z.boolean() }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/recipes/{id}/rate", summary: "Rate recipe (15)", security, request: { params: idParam, body: { content: { "application/json": { schema: z.object({ score: z.number().int().min(1).max(5) }) } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ score: z.number() }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/recipes/{id}/comments", summary: "List comments", security, request: { params: idParam, query: Pagination }, responses: { 200: { description: "Comments", content: { "application/json": { schema: z.array(CommentRef) } } } } });
registry.registerPath({ method: "post", path: "/api/v1/recipes/{id}/comments", summary: "Post comment", security, request: { params: idParam, body: { content: { "application/json": { schema: z.object({ body: z.string().min(1), parentId: z.string().optional() }) } }, required: true } }, responses: { 201: { description: "Created", content: { "application/json": { schema: CommentRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/ai/generate", summary: "Generate recipe from prompt", description: "Rate-limited: 10 req/min.", security, request: { body: { content: { "application/json": { schema: z.object({ prompt: z.string().min(1) }) } }, required: true } }, responses: { 200: { description: "Generated", content: { "application/json": { schema: AiGeneratedRef } } }, 429: { description: "Rate limited", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/ai/import-url", summary: "Import recipe from URL", description: "Rate-limited: 10 req/min.", security, request: { body: { content: { "application/json": { schema: z.object({ url: z.string().url() }) } }, required: true } }, responses: { 200: { description: "Imported", content: { "application/json": { schema: AiGeneratedRef } } }, 429: { description: "Rate limited", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/feed", summary: "Activity feed (pull-based)", security, request: { query: Pagination }, responses: { 200: { description: "Feed", content: { "application/json": { schema: z.array(RecipeRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/collections", summary: "List collections", security, request: { query: Pagination }, responses: { 200: { description: "Collections", content: { "application/json": { schema: z.array(CollectionRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/meal-plans/{weekStart}", summary: "Get meal plan for week", security, request: { params: z.object({ weekStart: z.string().describe("ISO date YYYY-MM-DD (Monday)") }) }, responses: { 200: { description: "Meal plan", content: { "application/json": { schema: MealPlanRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/pantry", summary: "List pantry items", security, request: { query: Pagination }, responses: { 200: { description: "Items", content: { "application/json": { schema: z.array(PantryItemRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/shopping-lists", summary: "List shopping lists", security, request: { query: Pagination }, responses: { 200: { description: "Lists", content: { "application/json": { schema: z.array(ShoppingListRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/shopping-lists", summary: "Create shopping list", security, request: { body: { content: { "application/json": { schema: z.object({ name: z.string().min(1), fromMealPlanWeek: z.string().optional() }) } }, required: true } }, responses: { 201: { description: "Created", content: { "application/json": { schema: ShoppingListRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/api-keys", summary: "List API keys", security, responses: { 200: { description: "Keys (hash never returned)", content: { "application/json": { schema: z.array(ApiKeyRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/api-keys", summary: "Create API key", security, request: { body: { content: { "application/json": { schema: z.object({ name: z.string().min(1).max(100) }) } }, required: true } }, responses: { 201: { description: "Key created — shown once", content: { "application/json": { schema: CreateApiKeyResponseRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "delete", path: "/api/v1/api-keys/{id}", summary: "Revoke API key", security, request: { params: idParam }, responses: { 204: { description: "Revoked" }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
const generator = new OpenApiGeneratorV31(registry.definitions);
cachedSpec = generator.generateDocument({
openapi: "3.1.0",
info: { title: "Epicure API", version: "1.0.0", description: "Auth: session cookie or Bearer API key (`ek_...`)." },
servers: [{ url: process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000" }],
});
return cachedSpec;
}
+16
View File
@@ -0,0 +1,16 @@
import Redis from "ioredis";
declare global {
// eslint-disable-next-line no-var
var __redis: Redis | undefined;
}
export function getRedis(): Redis {
if (!globalThis.__redis) {
globalThis.__redis = new Redis(
process.env["REDIS_URL"] ?? "redis://localhost:6379",
{ lazyConnect: false, maxRetriesPerRequest: 3 }
);
}
return globalThis.__redis;
}
+29
View File
@@ -0,0 +1,29 @@
import { S3Client, PutObjectCommand, DeleteObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
const bucket = process.env["STORAGE_BUCKET"] ?? "epicure-uploads";
const endpoint = process.env["STORAGE_ENDPOINT"] ?? "http://localhost:9000";
const publicUrl = process.env["STORAGE_PUBLIC_URL"] ?? "http://localhost:9000";
const s3 = new S3Client({
region: process.env["STORAGE_REGION"] ?? "us-east-1",
endpoint,
forcePathStyle: true,
credentials: {
accessKeyId: process.env["STORAGE_ACCESS_KEY"] ?? "minioadmin",
secretAccessKey: process.env["STORAGE_SECRET_KEY"] ?? "minioadmin",
},
});
export async function createPresignedUploadUrl(key: string, contentType: string): Promise<string> {
const command = new PutObjectCommand({ Bucket: bucket, Key: key, ContentType: contentType });
return getSignedUrl(s3, command, { expiresIn: 300 });
}
export async function deleteObject(key: string): Promise<void> {
await s3.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }));
}
export function getPublicUrl(key: string): string {
return `${publicUrl}/${bucket}/${key}`;
}