import { getCategories, getCategoriesCached } from '$lib/server/db/category.js'; import { createPost } from '$lib/server/db/post.js'; import { runIfError, runIfSuccess } from '$lib/status.js'; import { errorToFail } from '$lib/status.server.js'; import { parseIntNull } from '$lib/util.js'; import { fail, redirect } from '@sveltejs/kit'; export async function load({ cookies }) { if (!cookies.get('token')) { redirect(302, '/register'); } const categories = await getCategories(); return { categories: Array(...categories.values()) }; } /** @type {import('@sveltejs/kit').Action} */ async function POST({ request, cookies }) { const userToken = cookies.get('token'); if (!userToken) { return fail(401, { error: true, title: 'Invalid session', msg: 'Need to be logged in to perform this operation', }); } const data = await request.formData(); const categoryId = parseIntNull(data.get('category')?.toString()); const name = data.get('name')?.toString(); const content = data.get('content')?.toString(); if (!categoryId) { return fail(400, { error: true, title: 'Bad data', msg: `Invalid category ID ${categoryId}`, }); } if (!name || !content) { return fail(400, { error: true, title: 'Bad data', msg: 'Name and Content must have content', }); } const category = (await getCategoriesCached([categoryId])).get(categoryId); if (!category) { return fail(400, { error: true, title: 'Bad data', msg: `Invalid category ID ${categoryId}`, }); } const result = await createPost(userToken, category, name, content); runIfSuccess(result, (success) => { redirect(303, `/posts/${success.result}`); }); return runIfError(result, (error) => { return errorToFail(error); }); } export const actions = { default: POST, };