PronounsPage/server/api/blog/[slug]/reactions.post.ts
Valentyne Stigloher 10180aa6a3 (refactor) use #shared alias instead of ~~/shared
the #shared alias used by Nuxt cannot be easily disabled and to prevent breackage with jiti, we make use of it
2025-08-17 18:56:02 +02:00

47 lines
1.5 KiB
TypeScript

import SQL from 'sql-template-strings';
import { ulid } from 'ulid';
import { reactionOptions } from '#shared/blog/reactions.ts';
import { getPostReactions } from '~~/server/blog.ts';
import { getLocale, loadConfig } from '~~/server/data.ts';
import useAuthentication from '~~/server/utils/useAuthentication.ts';
export default defineEventHandler(async (event) => {
const config = await loadConfig(getLocale(event));
if (!config.links.enabled || !config.links.blog) {
throw createError({
status: 404,
statusMessage: 'Not Found',
});
}
const { user } = await useAuthentication(event);
if (!user) {
throw createError({
status: 401,
statusMessage: 'Unauthorised',
});
}
const locale = getLocale(event);
const body = await readBody(event);
const emoji = body.emoji;
if (!reactionOptions.includes(emoji)) {
throw createError({
status: 400,
statusMessage: 'Bad Request',
message: 'Invalid emoji',
});
}
const slug = getRouterParam(event, 'slug')!;
const db = useDatabase();
await db.get(SQL`DELETE FROM blog_reactions
WHERE locale = ${locale} AND slug = ${slug} AND user_id = ${user.id} AND emoji = ${emoji}`);
if (body.reaction) {
await db.get(SQL`INSERT INTO blog_reactions (id, locale, slug, emoji, user_id)
VALUES (${ulid()}, ${locale}, ${slug}, ${emoji}, ${user.id})`);
}
return await getPostReactions(db, locale, slug, user.id);
});