Files
Epicure/apps/web/app/api/v1/search/route.ts
T
Arnaud 9c545a5bb3 feat: private accounts, explore/people merge, meal-plan fixes, i18n and theme cleanup
- Private accounts: users.isPrivate hides a user from search and their
  recipes from search/trending/for-you discovery surfaces (follow-aware
  where the route already has session context, blanket exclusion where it
  doesn't); existing followers and direct links are unaffected, no
  follow-request approval flow was built (explicit scope limit)
- Merged /people into the Explore tab (tab=people query param); the old
  standalone route now redirects there
- "Get Ideas" vs "Surprise Me" were doing the same empty-prompt call;
  Surprise Me now injects a real random constraint (5-ingredient, one-pot,
  etc.), matching the existing pattern in the AI recipe-generate dialog
- Meal-plan day cells now link to their recipe (was dead text) and gained
  a one-click "mark as cooked" action
- Theme toggle is now a real three-way light/dark/system control instead
  of a binary flip
- Nutrition goals form had zero i18n wiring; fully localized now

New migration 0027 (users.is_private) generated, left unapplied like the
others. Verified with typecheck, lint, and a clean --no-cache docker build.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-10 09:26:03 +02:00

130 lines
3.5 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import {
db,
recipes,
users,
eq,
and,
or,
ilike,
sql,
desc,
} from "@epicure/db";
const VALID_DIETARY = ["vegan", "vegetarian", "glutenFree", "dairyFree"] as const;
type DietaryTag = (typeof VALID_DIETARY)[number];
export async function GET(req: NextRequest) {
const { searchParams } = req.nextUrl;
// --- Parse & validate required param ---
const q = (searchParams.get("q") ?? "").trim().slice(0, 200);
if (!q) {
return NextResponse.json(
{ error: "Query parameter 'q' is required and must not be empty." },
{ status: 400 }
);
}
// --- Optional params ---
const difficultyParam = searchParams.get("difficulty");
const difficulty =
difficultyParam === "easy" ||
difficultyParam === "medium" ||
difficultyParam === "hard"
? (difficultyParam as "easy" | "medium" | "hard")
: undefined;
const maxMinsRaw = searchParams.get("maxMins");
const maxMins =
maxMinsRaw !== null && !Number.isNaN(Number(maxMinsRaw))
? Number(maxMinsRaw)
: undefined;
const limitRaw = searchParams.get("limit");
const limit = Math.min(
limitRaw !== null && !Number.isNaN(Number(limitRaw))
? Math.max(1, Number(limitRaw))
: 20,
50
);
const offsetRaw = searchParams.get("offset");
const offset =
offsetRaw !== null && !Number.isNaN(Number(offsetRaw))
? Math.max(0, Number(offsetRaw))
: 0;
const dietaryRaw = searchParams.get("dietary");
const dietaryTags: DietaryTag[] = dietaryRaw
? (dietaryRaw
.split(",")
.map((s) => s.trim())
.filter((s): s is DietaryTag =>
(VALID_DIETARY as readonly string[]).includes(s)
))
: [];
// --- Build WHERE conditions ---
// Escape ilike wildcard chars (% and _) so user input like "100%" is matched literally.
const escapedQ = q.replace(/[\\%_]/g, (c) => `\\${c}`);
const conditions = [
eq(recipes.visibility, "public"),
eq(users.isPrivate, false),
or(
ilike(recipes.title, `%${escapedQ}%`),
ilike(recipes.description, `%${escapedQ}%`)
)!,
];
if (difficulty) {
conditions.push(eq(recipes.difficulty, difficulty));
}
if (maxMins !== undefined) {
conditions.push(
sql`(${recipes.prepMins} + ${recipes.cookMins}) <= ${maxMins}`
);
}
for (const tag of dietaryTags) {
// Containment (@>) instead of ->> text extraction so the GIN index on dietaryTags is actually used.
conditions.push(sql`${recipes.dietaryTags} @> ${JSON.stringify({ [tag]: true })}::jsonb`);
}
const where = and(...conditions);
// --- Main data query ---
const rows = await db
.select({
id: recipes.id,
title: recipes.title,
description: recipes.description,
difficulty: recipes.difficulty,
baseServings: recipes.baseServings,
prepMins: recipes.prepMins,
cookMins: recipes.cookMins,
authorId: recipes.authorId,
authorName: users.name,
createdAt: recipes.createdAt,
})
.from(recipes)
.innerJoin(users, eq(recipes.authorId, users.id))
.where(where)
.orderBy(desc(recipes.createdAt))
.limit(limit)
.offset(offset);
// --- Count query ---
const countResult = await db
.select({ total: sql<number>`count(*)::int` })
.from(recipes)
.innerJoin(users, eq(recipes.authorId, users.id))
.where(where);
const total = countResult[0]?.total ?? 0;
return NextResponse.json({ data: rows, total, limit, offset });
}