feat(评论管理): 添加编辑评论功能

在评论管理页面添加编辑功能,允许管理员修改评论的昵称、邮箱、网址、内容和状态
This commit is contained in:
anghunk
2026-01-21 17:25:49 +08:00
parent ce7c306acb
commit 27afa2db4f
4 changed files with 338 additions and 0 deletions

View File

@@ -0,0 +1,94 @@
import { Context } from 'hono';
import { Bindings } from '../../bindings';
import { checkContent } from '../public/postComment';
import { marked } from 'marked';
import xss from 'xss';
export const updateComment = async (c: Context<{ Bindings: Bindings }>) => {
let body: any;
try {
body = await c.req.json();
} catch {
return c.json({ message: 'Invalid JSON body' }, 400);
}
const rawId = body?.id;
const id =
typeof rawId === 'number'
? rawId
: typeof rawId === 'string' && rawId.trim()
? Number.parseInt(rawId.trim(), 10)
: NaN;
if (!Number.isFinite(id) || id <= 0) {
return c.json({ message: 'Missing or invalid id' }, 400);
}
const existing = await c.env.CWD_DB.prepare(
'SELECT id, status FROM Comment WHERE id = ?'
)
.bind(id)
.first<{ id: number; status: string }>();
if (!existing) {
return c.json({ message: 'Comment not found' }, 404);
}
const rawName = typeof body.name === 'string' ? body.name : '';
const rawEmail = typeof body.email === 'string' ? body.email : '';
const rawUrl = typeof body.url === 'string' ? body.url : '';
const rawStatus = typeof body.status === 'string' ? body.status : existing.status;
const contentSource =
typeof body.content === 'string'
? body.content
: typeof body.contentText === 'string'
? body.contentText
: '';
const name = rawName.trim();
const email = rawEmail.trim();
const url = rawUrl.trim() || null;
const status = rawStatus.trim();
if (!name) {
return c.json({ message: '昵称不能为空' }, 400);
}
if (!email) {
return c.json({ message: '邮箱不能为空' }, 400);
}
const cleanedContent = checkContent(contentSource);
const contentText = cleanedContent;
if (!contentText) {
return c.json({ message: '评论内容不能为空' }, 400);
}
const html = await marked.parse(cleanedContent, { async: true });
const contentHtml = xss(html, {
whiteList: {
...xss.whiteList,
code: ['class'],
span: ['class', 'style'],
pre: ['class'],
div: ['class', 'style'],
img: ['src', 'alt', 'title', 'width', 'height', 'style']
}
});
const { success } = await c.env.CWD_DB.prepare(
'UPDATE Comment SET name = ?, email = ?, url = ?, content_text = ?, content_html = ?, status = ? WHERE id = ?'
)
.bind(name, email, url, contentText, contentHtml, status, id)
.run();
if (!success) {
return c.json({ message: 'Update failed' }, 500);
}
return c.json({
message: `Comment updated, id: ${id}.`
});
};