PronounsPage/server/api/sources/submit.post.ts

45 lines
1.6 KiB
TypeScript

import SQL from 'sql-template-strings';
import { ulid } from 'ulid';
import { auditLog } from '~/server/audit.ts';
import { getLocale, loadConfig } from '~/server/data.ts';
import { approveSourceEntry } from '~/server/sources.ts';
import { isAllowedToPost } from '~/server/user.ts';
import { clearKey } from '~/src/helpers.ts';
export default defineEventHandler(async (event) => {
const locale = getLocale(event);
checkIsConfigEnabledOr404(await loadConfig(locale), 'sources');
const { user, isGranted } = await useAuthentication(event);
const db = useDatabase();
if (!user || !await isAllowedToPost(db, user)) {
throw createError({
status: 401,
statusMessage: 'Unauthorised',
});
}
const body = await readBody(event);
const id = ulid();
await db.get(SQL`
INSERT INTO sources (id, locale, pronouns, type, author, title, extra, year, fragments, comment, link, key, images, spoiler, submitter_id, base_id)
VALUES (
${id}, ${locale}, ${body.pronouns.join(';')},
${body.type}, ${body.author}, ${body.title}, ${body.extra}, ${body.year},
${body.fragments.join('@').replace(/\n/g, '|')}, ${body.comment}, ${body.link},
${clearKey(body.key)}, ${body.images ? body.images.join(',') : null}, ${body.spoiler ? 1 : 0},
${user.id}, ${body.base}
)
`);
await auditLog({ user }, 'sources/submitted', body);
if (isGranted('sources')) {
await approveSourceEntry(db, id, locale);
await auditLog({ user }, 'sources/approved', { id });
}
setResponseStatus(event, 201, 'Created');
});