refactor(api): alle handler auf api-helpers umstellen
13 +server.ts handler nutzen jetzt parsePositiveIntParam und
validateBody statt jeweils lokaler parseId/safeParse-Bloecke.
Konsequenzen:
- 9 lokale parseId/parsePositiveInt Definitionen geloescht
- 11 safeParse + manueller error()-Throws ersetzt
- domains/[id], domains, profiles: catch-Block reicht jetzt HttpError
durch (isHttpError) — vorher wurde ein 404 vom updateDomain als 409
re-emittiert
- recipes/[id]/image: kein function-clutter mehr neben den FormData-Pfaden
- Konsistente Error-Bodies: validateBody schickt {message, issues},
parsePositiveIntParam {message: 'Missing X' / 'Invalid X'}
Findings aus REVIEW-2026-04-18.md (Refactor A) und redundancy.md
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
import type { RequestHandler } from './$types';
|
||||
import { json, error } from '@sveltejs/kit';
|
||||
import { json } from '@sveltejs/kit';
|
||||
import { z } from 'zod';
|
||||
import { getDb } from '$lib/server/db';
|
||||
import { parsePositiveIntParam, validateBody } from '$lib/server/api-helpers';
|
||||
import { addComment, deleteComment, listComments } from '$lib/server/recipes/actions';
|
||||
|
||||
const Schema = z.object({
|
||||
@@ -11,30 +12,20 @@ const Schema = z.object({
|
||||
|
||||
const DeleteSchema = z.object({ comment_id: z.number().int().positive() });
|
||||
|
||||
function parseId(raw: string): number {
|
||||
const id = Number(raw);
|
||||
if (!Number.isInteger(id) || id <= 0) error(400, { message: 'Invalid id' });
|
||||
return id;
|
||||
}
|
||||
|
||||
export const GET: RequestHandler = async ({ params }) => {
|
||||
const id = parseId(params.id!);
|
||||
const id = parsePositiveIntParam(params.id, 'id');
|
||||
return json(listComments(getDb(), id));
|
||||
};
|
||||
|
||||
export const POST: RequestHandler = async ({ params, request }) => {
|
||||
const id = parseId(params.id!);
|
||||
const body = await request.json().catch(() => null);
|
||||
const parsed = Schema.safeParse(body);
|
||||
if (!parsed.success) error(400, { message: 'Invalid body' });
|
||||
const cid = addComment(getDb(), id, parsed.data.profile_id, parsed.data.text);
|
||||
const id = parsePositiveIntParam(params.id, 'id');
|
||||
const data = validateBody(await request.json().catch(() => null), Schema);
|
||||
const cid = addComment(getDb(), id, data.profile_id, data.text);
|
||||
return json({ id: cid }, { status: 201 });
|
||||
};
|
||||
|
||||
export const DELETE: RequestHandler = async ({ request }) => {
|
||||
const body = await request.json().catch(() => null);
|
||||
const parsed = DeleteSchema.safeParse(body);
|
||||
if (!parsed.success) error(400, { message: 'Invalid body' });
|
||||
deleteComment(getDb(), parsed.data.comment_id);
|
||||
const data = validateBody(await request.json().catch(() => null), DeleteSchema);
|
||||
deleteComment(getDb(), data.comment_id);
|
||||
return json({ ok: true });
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user