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:
hsiegeln
2026-04-22 14:23:36 +02:00
parent 6f54b004ca
commit 82d4348873
2 changed files with 143 additions and 1 deletions

View 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 });
};