Add: Fetching posts by Token

This commit is contained in:
Donatas Kirda 2024-05-20 22:54:23 +03:00
parent e16429cdd9
commit 9fa4655632
Signed by: bloodwiing
GPG Key ID: 63020D8D3F4A164F
2 changed files with 22 additions and 7 deletions

View File

@ -118,29 +118,34 @@ export async function getPosts(opts = {}) {
/**
*
* @param {number} post_id
* @param {string | null} token
* @param {{
* withMetrics?: boolean
* }} opts
* @returns {Promise<Post | import('$types/status').Error>}
*/
export async function getPost(post_id, opts = {}) {
export async function getPost(post_id, token = null, opts = {}) {
const {
withMetrics = false
} = opts;
const metrics = withMetrics ? sql`, comment_count, user_count, latest_activity, engagement, age, relevancy` : sql``;
const allowOwn = token ? sql`OR author_id = (${ sqlUserFromToken(token) })` : sql``;
const query = sql`
SELECT id, author_id, name, category_id, latest_content, edit_count, created_date, likes, dislikes ${ metrics }
SELECT id, author_id, name, category_id, latest_content, reviewed, edit_count, created_date, likes, dislikes ${ metrics }
FROM doki8902.message_post
WHERE id = ${ post_id };`;
WHERE id = ${ post_id } AND (reviewed ${ allowOwn });`;
const post = (await query).at(0);
if (!post) {
return {
error: true,
msg: `Could not find Post of ID ${ post_id }`
title: 'No Post',
msg: `Could not find Post of ID ${ post_id }`,
expected: true,
};
}
@ -160,7 +165,9 @@ export async function getPost(post_id, opts = {}) {
if (Object.hasOwn(category_guess, 'error')) {
return {
error: true,
msg: `Post of ID ${ post_id } has an invalid Category ID ${ post['category_id'] }`
title: 'Category invalid',
msg: `Post of ID ${ post_id } has an invalid Category ID ${ post['category_id'] }`,
expected: false,
};
}

View File

@ -1,17 +1,25 @@
import { getCommentsForPost } from "$lib/server/db/comment";
import { getPost } from "$lib/server/db/post";
import { getError } from "$lib/status";
import { getIdFromName } from "$lib/util";
import { error } from "@sveltejs/kit";
/** @type {import("@sveltejs/kit").ServerLoad} */
export async function load({ params }) {
export async function load({ params, cookies }) {
const post_id = getIdFromName(params.name);
if (post_id === null) {
error(404, `No Post of ID ${params.name}`);
}
const post = await getPost(post_id);
const token = cookies.get('token')?.toString() ?? null;
const post = await getPost(post_id, token);
const postError = getError(post);
if (postError) {
error(404, postError.msg);
}
const comments = await getCommentsForPost(post_id);