fix: return clean errors and refund quota on AI provider failures
AI routes had no consistent error handling — a provider failure (e.g. OpenRouter returning a degraded-model error) crashed the route as an uncaught 500 and, worse, still charged the user's monthly aiCall quota for a request that never succeeded. Adds withAiQuota()/aiErrorResponse() (lib/ai/ai-error.ts) and applies them across all 12 AI generation routes: charges the quota, runs the AI call, refunds the credit and returns a clean user-facing message if it throws. Frontend needs no changes — existing dialogs already toast whatever `error` string comes back. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
import { and, eq } from "@epicure/db";
|
||||
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { checkAndIncrementTierLimit } from "@/lib/tiers";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { adaptRecipe } from "@/lib/ai/features/adapt-recipe";
|
||||
import { withUserKey } from "@/lib/ai/resolve-user-key";
|
||||
import { getUserPrivateBio } from "@/lib/ai/user-bio";
|
||||
@@ -43,27 +43,30 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
return NextResponse.json({ error: "Provide at least one constraint" }, { status: 400 });
|
||||
}
|
||||
|
||||
await checkAndIncrementTierLimit(userId, session!.user.tier as "free" | "pro", "aiCall");
|
||||
|
||||
const [aiConfig, privateBio] = await Promise.all([
|
||||
withUserKey(userId, { provider: parsed.data.provider, model: parsed.data.model }),
|
||||
getUserPrivateBio(userId),
|
||||
]);
|
||||
const adapted = await adaptRecipe(
|
||||
{
|
||||
title: recipe.title,
|
||||
description: recipe.description,
|
||||
baseServings: recipe.baseServings,
|
||||
ingredients: recipe.ingredients,
|
||||
steps: recipe.steps,
|
||||
},
|
||||
{
|
||||
excludeIngredients: parsed.data.excludeIngredients,
|
||||
extraConstraints: parsed.data.extraConstraints,
|
||||
},
|
||||
{ ...aiConfig, userContext: privateBio ?? undefined },
|
||||
(session!.user as { locale?: string }).locale ?? "en"
|
||||
|
||||
const result = await withAiQuota(userId, session!.user.tier as "free" | "pro", () =>
|
||||
adaptRecipe(
|
||||
{
|
||||
title: recipe.title,
|
||||
description: recipe.description,
|
||||
baseServings: recipe.baseServings,
|
||||
ingredients: recipe.ingredients,
|
||||
steps: recipe.steps,
|
||||
},
|
||||
{
|
||||
excludeIngredients: parsed.data.excludeIngredients,
|
||||
extraConstraints: parsed.data.extraConstraints,
|
||||
},
|
||||
{ ...aiConfig, userContext: privateBio ?? undefined },
|
||||
(session!.user as { locale?: string }).locale ?? "en"
|
||||
)
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
const adapted = result.data;
|
||||
|
||||
const newId = crypto.randomUUID();
|
||||
const now = new Date();
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
import { and, eq } from "@epicure/db";
|
||||
import { db, recipes } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { checkAndIncrementTierLimit } from "@/lib/tiers";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { suggestDrinks } from "@/lib/ai/features/suggest-drinks";
|
||||
import { withUserKey } from "@/lib/ai/resolve-user-key";
|
||||
import { getUserPrivateBio } from "@/lib/ai/user-bio";
|
||||
@@ -34,24 +34,26 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
const parsed = Schema.safeParse(body ?? {});
|
||||
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
|
||||
|
||||
await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
|
||||
|
||||
const [aiConfig, privateBio] = await Promise.all([
|
||||
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model }),
|
||||
getUserPrivateBio(session!.user.id),
|
||||
]);
|
||||
const drinks = await suggestDrinks(
|
||||
{
|
||||
title: recipe.title,
|
||||
description: recipe.description,
|
||||
difficulty: recipe.difficulty,
|
||||
dietaryTags: recipe.dietaryTags as Record<string, boolean> | null,
|
||||
ingredients: recipe.ingredients,
|
||||
},
|
||||
parsed.data.count,
|
||||
{ ...aiConfig, userContext: privateBio ?? undefined },
|
||||
(session!.user as { locale?: string }).locale ?? "en"
|
||||
);
|
||||
|
||||
return NextResponse.json({ drinks });
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
suggestDrinks(
|
||||
{
|
||||
title: recipe.title,
|
||||
description: recipe.description,
|
||||
difficulty: recipe.difficulty,
|
||||
dietaryTags: recipe.dietaryTags as Record<string, boolean> | null,
|
||||
ingredients: recipe.ingredients,
|
||||
},
|
||||
parsed.data.count,
|
||||
{ ...aiConfig, userContext: privateBio ?? undefined },
|
||||
(session!.user as { locale?: string }).locale ?? "en"
|
||||
)
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
|
||||
return NextResponse.json({ drinks: result.data });
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { checkAndIncrementTierLimit } from "@/lib/tiers";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { generateRecipe } from "@/lib/ai/features/generate-recipe";
|
||||
import { getUserPrivateBio } from "@/lib/ai/user-bio";
|
||||
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
|
||||
@@ -29,17 +29,19 @@ export async function POST(req: NextRequest) {
|
||||
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
|
||||
if (limited) return limited;
|
||||
|
||||
await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
|
||||
|
||||
const privateBio = await getUserPrivateBio(session!.user.id);
|
||||
const locale = (session!.user as { locale?: string }).locale ?? "en";
|
||||
|
||||
const recipe = await generateRecipe(parsed.data.title, {
|
||||
provider: parsed.data.provider,
|
||||
model: parsed.data.model,
|
||||
userContext: privateBio ?? undefined,
|
||||
language: LANG[locale] ?? "English",
|
||||
});
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
generateRecipe(parsed.data.title, {
|
||||
provider: parsed.data.provider,
|
||||
model: parsed.data.model,
|
||||
userContext: privateBio ?? undefined,
|
||||
language: LANG[locale] ?? "English",
|
||||
})
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
const recipe = result.data;
|
||||
|
||||
const recipeId = crypto.randomUUID();
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { checkAndIncrementTierLimit } from "@/lib/tiers";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { generateRecipe } from "@/lib/ai/features/generate-recipe";
|
||||
import { getUserPrivateBio } from "@/lib/ai/user-bio";
|
||||
|
||||
@@ -27,17 +27,18 @@ export async function POST(req: NextRequest) {
|
||||
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
|
||||
if (limited) return limited;
|
||||
|
||||
await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
|
||||
|
||||
const privateBio = await getUserPrivateBio(session!.user.id);
|
||||
|
||||
const recipe = await generateRecipe(parsed.data.prompt, {
|
||||
provider: parsed.data.provider,
|
||||
model: parsed.data.model,
|
||||
language: parsed.data.language,
|
||||
difficulty: parsed.data.difficulty,
|
||||
userContext: privateBio ?? undefined,
|
||||
});
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
generateRecipe(parsed.data.prompt, {
|
||||
provider: parsed.data.provider,
|
||||
model: parsed.data.model,
|
||||
language: parsed.data.language,
|
||||
difficulty: parsed.data.difficulty,
|
||||
userContext: privateBio ?? undefined,
|
||||
})
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
|
||||
return NextResponse.json(recipe);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { importFromPhoto } from "@/lib/ai/features/import-photo";
|
||||
import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
|
||||
|
||||
@@ -28,15 +28,6 @@ export async function POST(req: NextRequest) {
|
||||
const userId = session!.user.id;
|
||||
const locale = (session!.user as { locale?: string }).locale ?? "en";
|
||||
|
||||
try {
|
||||
await checkAndIncrementTierLimit(userId, session!.user.tier as "free" | "pro", "aiCall");
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof TierLimitError) {
|
||||
return NextResponse.json({ error: "AI call limit reached for your tier" }, { status: 403 });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const aiConfig = await getModelConfigForUseCase(userId, "vision");
|
||||
|
||||
// Fall back to vision-capable defaults if no explicit model configured
|
||||
@@ -45,13 +36,11 @@ export async function POST(req: NextRequest) {
|
||||
else if (aiConfig.provider === "anthropic") aiConfig.model = "claude-sonnet-4-6";
|
||||
}
|
||||
|
||||
let recipe;
|
||||
try {
|
||||
recipe = await importFromPhoto(parsed.data.imageBase64, parsed.data.mimeType, aiConfig, locale);
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : "AI analysis failed";
|
||||
return NextResponse.json({ error: msg }, { status: 502 });
|
||||
}
|
||||
const result = await withAiQuota(userId, session!.user.tier as "free" | "pro", () =>
|
||||
importFromPhoto(parsed.data.imageBase64, parsed.data.mimeType, aiConfig, locale)
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
const recipe = result.data;
|
||||
|
||||
const newRecipeId = crypto.randomUUID();
|
||||
const now = new Date();
|
||||
|
||||
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { checkAndIncrementTierLimit } from "@/lib/tiers";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { importFromUrl } from "@/lib/ai/features/import-url";
|
||||
import { validateWebhookUrl } from "@/lib/validate-webhook-url";
|
||||
|
||||
@@ -30,12 +30,13 @@ export async function POST(req: NextRequest) {
|
||||
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
|
||||
if (limited) return limited;
|
||||
|
||||
await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
importFromUrl(parsed.data.url, {
|
||||
provider: parsed.data.provider,
|
||||
model: parsed.data.model,
|
||||
})
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
|
||||
const recipe = await importFromUrl(parsed.data.url, {
|
||||
provider: parsed.data.provider,
|
||||
model: parsed.data.model,
|
||||
});
|
||||
|
||||
return NextResponse.json(recipe);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { db, recipes, recipeIngredients, recipeSteps, mealPlans, mealPlanEntries
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
|
||||
import { aiErrorResponse } from "@/lib/ai/ai-error";
|
||||
import { generateMealPlan } from "@/lib/ai/features/generate-meal-plan";
|
||||
import { getUserPrivateBio } from "@/lib/ai/user-bio";
|
||||
|
||||
@@ -52,18 +53,23 @@ export async function POST(req: NextRequest) {
|
||||
pantryItemNames = pantry.map((p) => p.rawName);
|
||||
}
|
||||
|
||||
const plan = await generateMealPlan(
|
||||
{
|
||||
dietaryPrefs: parsed.data.dietaryPrefs,
|
||||
servings: parsed.data.servings,
|
||||
pantryItems: pantryItemNames,
|
||||
days: parsed.data.days,
|
||||
pantryMode: parsed.data.pantryMode,
|
||||
difficulty: parsed.data.difficulty,
|
||||
},
|
||||
{ ...config, userContext: privateBio ?? undefined },
|
||||
locale
|
||||
);
|
||||
let plan;
|
||||
try {
|
||||
plan = await generateMealPlan(
|
||||
{
|
||||
dietaryPrefs: parsed.data.dietaryPrefs,
|
||||
servings: parsed.data.servings,
|
||||
pantryItems: pantryItemNames,
|
||||
days: parsed.data.days,
|
||||
pantryMode: parsed.data.pantryMode,
|
||||
difficulty: parsed.data.difficulty,
|
||||
},
|
||||
{ ...config, userContext: privateBio ?? undefined },
|
||||
locale
|
||||
);
|
||||
} catch (err) {
|
||||
return aiErrorResponse(err);
|
||||
}
|
||||
|
||||
// Ensure meal plan row exists for the week
|
||||
let mealPlan = await db.query.mealPlans.findFirst({
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
import { and, eq } from "@epicure/db";
|
||||
import { db, recipes } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { checkAndIncrementTierLimit } from "@/lib/tiers";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { suggestPairings } from "@/lib/ai/features/suggest-pairings";
|
||||
import { withUserKey } from "@/lib/ai/resolve-user-key";
|
||||
import { getUserPrivateBio } from "@/lib/ai/user-bio";
|
||||
@@ -35,24 +35,26 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
const parsed = Schema.safeParse(body ?? {});
|
||||
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
|
||||
|
||||
await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
|
||||
|
||||
const [aiConfig, privateBio] = await Promise.all([
|
||||
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model }),
|
||||
getUserPrivateBio(session!.user.id),
|
||||
]);
|
||||
const pairings = await suggestPairings(
|
||||
{
|
||||
title: recipe.title,
|
||||
description: recipe.description,
|
||||
difficulty: recipe.difficulty,
|
||||
dietaryTags: recipe.dietaryTags as Record<string, boolean> | null,
|
||||
ingredients: recipe.ingredients,
|
||||
},
|
||||
parsed.data.count,
|
||||
{ ...aiConfig, userContext: privateBio ?? undefined },
|
||||
(session!.user as { locale?: string }).locale ?? "en"
|
||||
);
|
||||
|
||||
return NextResponse.json({ pairings });
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
suggestPairings(
|
||||
{
|
||||
title: recipe.title,
|
||||
description: recipe.description,
|
||||
difficulty: recipe.difficulty,
|
||||
dietaryTags: recipe.dietaryTags as Record<string, boolean> | null,
|
||||
ingredients: recipe.ingredients,
|
||||
},
|
||||
parsed.data.count,
|
||||
{ ...aiConfig, userContext: privateBio ?? undefined },
|
||||
(session!.user as { locale?: string }).locale ?? "en"
|
||||
)
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
|
||||
return NextResponse.json({ pairings: result.data });
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { db, recipes, eq, and, or } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
|
||||
import { checkAndIncrementTierLimit } from "@/lib/tiers";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { scaleRecipe } from "@/lib/ai/features/scale-recipe";
|
||||
|
||||
const Schema = z.object({
|
||||
@@ -40,21 +40,22 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
|
||||
|
||||
const aiConfig = await getDefaultProviderWithKey(session!.user.id);
|
||||
|
||||
const scaledIngredients = await scaleRecipe(
|
||||
{
|
||||
title: recipe.title,
|
||||
baseServings: recipe.baseServings,
|
||||
ingredients: recipe.ingredients,
|
||||
},
|
||||
targetServings,
|
||||
recipe.baseServings,
|
||||
aiConfig,
|
||||
(session!.user as { locale?: string }).locale ?? "en"
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
scaleRecipe(
|
||||
{
|
||||
title: recipe.title,
|
||||
baseServings: recipe.baseServings,
|
||||
ingredients: recipe.ingredients,
|
||||
},
|
||||
targetServings,
|
||||
recipe.baseServings,
|
||||
aiConfig,
|
||||
(session!.user as { locale?: string }).locale ?? "en"
|
||||
)
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
|
||||
return NextResponse.json({ ingredients: scaledIngredients });
|
||||
return NextResponse.json({ ingredients: result.data });
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
|
||||
import { substituteIngredient } from "@/lib/ai/features/substitute-ingredient";
|
||||
@@ -24,15 +24,6 @@ export async function POST(req: NextRequest) {
|
||||
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";
|
||||
@@ -43,12 +34,10 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
const locale = (session!.user as { locale?: string }).locale ?? "en";
|
||||
|
||||
const substitutions = await substituteIngredient(
|
||||
parsed.data.ingredient,
|
||||
context,
|
||||
aiConfig,
|
||||
locale
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
substituteIngredient(parsed.data.ingredient, context, aiConfig, locale)
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
|
||||
return NextResponse.json({ substitutions });
|
||||
return NextResponse.json({ substitutions: result.data });
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
import { and, eq } from "@epicure/db";
|
||||
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { checkAndIncrementTierLimit } from "@/lib/tiers";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { translateRecipe } from "@/lib/ai/features/translate-recipe";
|
||||
|
||||
const Schema = z.object({
|
||||
@@ -35,18 +35,20 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
|
||||
|
||||
const translation = await translateRecipe(
|
||||
{
|
||||
title: recipe.title,
|
||||
description: recipe.description,
|
||||
ingredients: recipe.ingredients,
|
||||
steps: recipe.steps,
|
||||
},
|
||||
parsed.data.targetLanguage,
|
||||
{ provider: parsed.data.provider, model: parsed.data.model }
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
translateRecipe(
|
||||
{
|
||||
title: recipe.title,
|
||||
description: recipe.description,
|
||||
ingredients: recipe.ingredients,
|
||||
steps: recipe.steps,
|
||||
},
|
||||
parsed.data.targetLanguage,
|
||||
{ provider: parsed.data.provider, model: parsed.data.model }
|
||||
)
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
const translation = result.data;
|
||||
|
||||
// Save as new draft recipe
|
||||
const newId = crypto.randomUUID();
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
import { and, eq } from "@epicure/db";
|
||||
import { db, recipes } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { checkAndIncrementTierLimit } from "@/lib/tiers";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { suggestVariations } from "@/lib/ai/features/suggest-variations";
|
||||
import { withUserKey } from "@/lib/ai/resolve-user-key";
|
||||
import { getUserPrivateBio } from "@/lib/ai/user-bio";
|
||||
@@ -38,24 +38,26 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
|
||||
|
||||
const [aiConfig, privateBio] = await Promise.all([
|
||||
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model }),
|
||||
getUserPrivateBio(session!.user.id),
|
||||
]);
|
||||
const variations = await suggestVariations(
|
||||
{
|
||||
title: recipe.title,
|
||||
description: recipe.description,
|
||||
ingredients: recipe.ingredients,
|
||||
steps: recipe.steps,
|
||||
},
|
||||
parsed.data.count,
|
||||
{ ...aiConfig, userContext: privateBio ?? undefined },
|
||||
parsed.data.directions,
|
||||
(session!.user as { locale?: string }).locale ?? "en"
|
||||
);
|
||||
|
||||
return NextResponse.json({ variations });
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
suggestVariations(
|
||||
{
|
||||
title: recipe.title,
|
||||
description: recipe.description,
|
||||
ingredients: recipe.ingredients,
|
||||
steps: recipe.steps,
|
||||
},
|
||||
parsed.data.count,
|
||||
{ ...aiConfig, userContext: privateBio ?? undefined },
|
||||
parsed.data.directions,
|
||||
(session!.user as { locale?: string }).locale ?? "en"
|
||||
)
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
|
||||
return NextResponse.json({ variations: result.data });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user