import { readBody, createError } from 'h3' import { requireUser } from '../utils/auth' import { getDb } from '../utils/db' import { newsBySlug } from '../../app/data/news' /** * 发表评论(需登录) */ export default defineEventHandler(async (event) => { const user = requireUser(event) const body = await readBody(event) const newsSlug = String(body?.newsSlug ?? '') const content = String(body?.content ?? '').trim() if (!newsBySlug[newsSlug]) { throw createError({ statusCode: 400, message: '未知的文章', data: { code: 'VALIDATION_ERROR' } }) } if (!content) { throw createError({ statusCode: 400, message: '评论内容不能为空', data: { code: 'VALIDATION_ERROR' } }) } if (content.length > 2000) { throw createError({ statusCode: 400, message: '评论内容过长(最多 2000 字)', data: { code: 'VALIDATION_ERROR' } }) } const info = getDb() .prepare('INSERT INTO comments (news_slug, user_id, content) VALUES (?, ?, ?)') .run(newsSlug, user.id, content) const row = getDb() .prepare('SELECT id, content, created_at AS createdAt FROM comments WHERE id = ?') .get(info.lastInsertRowid) as { id: number; content: string; createdAt: string } return { comment: { id: row.id, content: row.content, createdAt: row.createdAt, author: { username: user.username }, }, } })