import { readBody, createError } from 'h3' import { requireAdmin } from '../../utils/auth' import { getDb } from '../../utils/db' import { getArticleBySlug } from '../../utils/content' import { normalizeSlug, isValidSlug, isValidArticleCategory, normalizeBlocks } from '../../utils/validateContent' /** * 后台新增动态 */ export default defineEventHandler(async (event) => { requireAdmin(event) const body = await readBody(event) const db = getDb() const slug = normalizeSlug(body?.slug) if (!isValidSlug(slug)) { throw createError({ statusCode: 400, message: 'slug 需为 2-64 位小写字母/数字/中划线', data: { code: 'VALIDATION_ERROR' } }) } if (!isValidArticleCategory(body?.category)) { throw createError({ statusCode: 400, message: '分类不合法', data: { code: 'VALIDATION_ERROR' } }) } const titleZh = String(body?.titleZh ?? '').trim() const titleEn = String(body?.titleEn ?? '').trim() if (!titleZh || !titleEn) { throw createError({ statusCode: 400, message: '中英文标题不能为空', data: { code: 'VALIDATION_ERROR' } }) } if (getArticleBySlug(slug, { publishedOnly: false })) { throw createError({ statusCode: 400, message: 'slug 已存在', data: { code: 'SLUG_TAKEN' } }) } db.prepare( `INSERT INTO articles (slug, category, title_zh, title_en, excerpt_zh, excerpt_en, content_zh, content_en, image, date, read_time, author, published, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))`, ).run( slug, body.category, titleZh, titleEn, String(body?.excerptZh ?? ''), String(body?.excerptEn ?? ''), JSON.stringify(normalizeBlocks(body?.contentZh)), JSON.stringify(normalizeBlocks(body?.contentEn)), body?.image ? String(body.image).trim() : null, body?.date ? String(body.date).trim() : null, Number(body?.readTime) || 5, String(body?.author ?? 'ArcticNewOne').trim() || 'ArcticNewOne', body?.published ? 1 : 0, ) return { ok: true, article: getArticleBySlug(slug, { publishedOnly: false }) } })