47 lines
1.6 KiB
TypeScript
47 lines
1.6 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { z } from "zod";
|
|
import { requireSession } from "@/lib/api-auth";
|
|
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
|
|
import { applyRateLimit } from "@/lib/rate-limit";
|
|
import { substituteIngredient } from "@/lib/ai/features/substitute-ingredient";
|
|
|
|
const Schema = z.object({
|
|
ingredient: z.string().min(1).max(200),
|
|
recipeTitle: z.string().max(200).optional(),
|
|
provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]).optional(),
|
|
model: z.string().optional(),
|
|
});
|
|
|
|
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" }, { status: 400 });
|
|
|
|
const rateLimitRes = await applyRateLimit(`ai:substitute:${session!.user.id}`, 10, 60);
|
|
if (rateLimitRes) return rateLimitRes;
|
|
|
|
try {
|
|
await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
|
|
} catch (err) {
|
|
if (err instanceof TierLimitError) {
|
|
return NextResponse.json({ error: "AI call limit reached for your tier" }, { status: 403 });
|
|
}
|
|
throw err;
|
|
}
|
|
|
|
const context = parsed.data.recipeTitle
|
|
? `recipe "${parsed.data.recipeTitle}"`
|
|
: "a general recipe";
|
|
|
|
const substitutions = await substituteIngredient(
|
|
parsed.data.ingredient,
|
|
context,
|
|
{ provider: parsed.data.provider, model: parsed.data.model }
|
|
);
|
|
|
|
return NextResponse.json({ substitutions });
|
|
}
|