Files
kochwas/src/routes/api/recipes/[id]/comments/+server.ts

32 lines
1.2 KiB
TypeScript
Raw Normal View History

import type { RequestHandler } from './$types';
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({
profile_id: z.number().int().positive(),
text: z.string().min(1).max(2000)
});
const DeleteSchema = z.object({ comment_id: z.number().int().positive() });
export const GET: RequestHandler = async ({ params }) => {
const id = parsePositiveIntParam(params.id, 'id');
return json(listComments(getDb(), id));
};
export const POST: RequestHandler = async ({ params, request }) => {
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 data = validateBody(await request.json().catch(() => null), DeleteSchema);
deleteComment(getDb(), data.comment_id);
return json({ ok: true });
};