import { unlink } from 'node:fs/promises' import { join } from 'node:path' import { eq } from 'drizzle-orm' import { commentAttachments, comments, uploads } from '../../db/schema' export default defineEventHandler(async (event) => { await requirePermission(event, 'upload.delete') const id = getRouterParam(event, 'id') ?? '' if (!/^[A-Za-z0-9]{1,16}$/.test(id)) { throw createError({ statusCode: 400, statusMessage: 'Ungültige ID' }) } const db = useDb() const [upload] = await db .select({ fileName: uploads.fileName }) .from(uploads) .where(eq(uploads.id, id)) .limit(1) if (!upload) { throw createError({ statusCode: 404, statusMessage: 'Upload nicht gefunden' }) } const attachmentFiles = await db .select({ fileName: commentAttachments.fileName, cover: commentAttachments.cover }) .from(commentAttachments) .innerJoin(comments, eq(commentAttachments.commentId, comments.id)) .where(eq(comments.uploadId, id)) await db.delete(uploads).where(eq(uploads.id, id)) if (upload.fileName) { await unlink(join(uploadDir(), upload.fileName)).catch(() => {}) } for (const f of attachmentFiles) { await unlink(join(uploadDir(), 'attachments', f.fileName)).catch(() => {}) if (f.cover) { await unlink(join(process.cwd(), 'public', f.cover)).catch(() => {}) } } return { ok: true } })