feat(api): POST /api/recipes/[id]/view fuer View-Beacon
Body { profile_id } via zod validiert. FK-Violation (unbekanntes
Profil oder Rezept) wird zu 404 normalisiert. Erfolg liefert 204
ohne Body — fire-and-forget vom Client.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
30
src/routes/api/recipes/[id]/view/+server.ts
Normal file
30
src/routes/api/recipes/[id]/view/+server.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import type { RequestHandler } from './$types';
|
||||
import { z } from 'zod';
|
||||
import { error } from '@sveltejs/kit';
|
||||
import { getDb } from '$lib/server/db';
|
||||
import { validateBody } from '$lib/server/api-helpers';
|
||||
import { recordView } from '$lib/server/recipes/views';
|
||||
|
||||
const Schema = z.object({
|
||||
profile_id: z.number().int().positive()
|
||||
});
|
||||
|
||||
export const POST: RequestHandler = async ({ params, request }) => {
|
||||
const recipeId = Number(params.id);
|
||||
if (!Number.isInteger(recipeId) || recipeId <= 0) {
|
||||
error(400, { message: 'Invalid recipe id' });
|
||||
}
|
||||
const body = validateBody(await request.json().catch(() => null), Schema);
|
||||
|
||||
try {
|
||||
recordView(getDb(), body.profile_id, recipeId);
|
||||
} catch (e) {
|
||||
// FK violation (unknown profile or recipe) → 404
|
||||
if (e instanceof Error && /FOREIGN KEY constraint failed/i.test(e.message)) {
|
||||
error(404, { message: 'Recipe or profile not found' });
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
return new Response(null, { status: 204 });
|
||||
};
|
||||
Reference in New Issue
Block a user