62 lines
1.5 KiB
JavaScript
62 lines
1.5 KiB
JavaScript
import { getCategories, getCategoriesCached } from '$lib/server/db/category.js';
|
|
import { createPost } from '$lib/server/db/post.js';
|
|
import { getUserIDOfSession } from '$lib/server/db/user.js';
|
|
import { parseIntNull } from '$lib/util.js';
|
|
import { error, 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 }) {
|
|
if (request.method !== 'POST') {
|
|
return;
|
|
}
|
|
|
|
const userToken = cookies.get('token');
|
|
|
|
if (!userToken) {
|
|
error(401, 'Need to be logged in!');
|
|
}
|
|
|
|
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) {
|
|
error(400, `Invalid category ID ${categoryId}`);
|
|
}
|
|
|
|
if (!name || !content) {
|
|
error(400, `Not all fields have been filled out`);
|
|
}
|
|
|
|
const category = (await getCategoriesCached([categoryId])).get(categoryId);
|
|
|
|
if (!category) {
|
|
error(400, `Invalid category ID ${categoryId}`);
|
|
}
|
|
|
|
const result = await createPost(userToken, category, name, content);
|
|
|
|
if ('error' in result) {
|
|
|
|
} else {
|
|
redirect(303, `/posts/${result.result}`);
|
|
}
|
|
}
|
|
|
|
export const actions = {
|
|
default: POST,
|
|
};
|