feat: 后台管理系统(Admin Backend + 全量 CMS)
- 内容迁入数据库:articles/works 表(中英双语 + 内容块), server/utils/seed.ts 灌入现有 6 动态 + 6 作品,站点初始内容不变 - 前台内容 API:/api/news、/api/work(列表/详情,仅已发布), 页面/首页组件改为 useFetch 拉取并按 locale 选 zh/en 字段 - 后台管理 /admin(admin 中间件守卫): - Dashboard 统计、动态/作品增删改(块编辑器、图片上传 /api/admin/upload) - 用户管理(角色切换/删除)、评论审核、联系/订阅管理(导出 CSV) - 预置管理员:NUXT_ADMIN_INITIAL_PASSWORD 首次初始化创建 admin 账号 - 图片自托管:上传存 PVC /data/uploads,/uploads/[...] 路由服务 - sitemap 改查 DB;i18n 移除内容键(305 键对齐);删除 app/data 冗余模块 - 角色以数据库为准(后台可切换);admin 中间件 + 客户端会话恢复插件
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
import { requireAdmin } from '../../utils/auth'
|
||||
import { listArticles } from '../../utils/content'
|
||||
|
||||
/**
|
||||
* 后台动态列表(含未发布)
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
return { articles: listArticles({ publishedOnly: false }) }
|
||||
})
|
||||
@@ -0,0 +1,52 @@
|
||||
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 }) }
|
||||
})
|
||||
@@ -0,0 +1,25 @@
|
||||
import { createError, getRouterParam } from 'h3'
|
||||
import { requireAdmin } from '../../../utils/auth'
|
||||
import { getDb } from '../../../utils/db'
|
||||
|
||||
/**
|
||||
* 后台删除动态(连带删除其评论)
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
const id = Number(getRouterParam(event, 'id'))
|
||||
const db = getDb()
|
||||
|
||||
const row = db.prepare('SELECT slug FROM articles WHERE id = ?').get(id) as { slug: string } | undefined
|
||||
if (!row) {
|
||||
throw createError({ statusCode: 404, message: '动态不存在', data: { code: 'NOT_FOUND' } })
|
||||
}
|
||||
|
||||
const tx = db.transaction(() => {
|
||||
db.prepare('DELETE FROM comments WHERE news_slug = ?').run(row.slug)
|
||||
db.prepare('DELETE FROM articles WHERE id = ?').run(id)
|
||||
})
|
||||
tx()
|
||||
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -0,0 +1,82 @@
|
||||
import { readBody, createError, getRouterParam } 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 id = Number(getRouterParam(event, 'id'))
|
||||
const body = await readBody(event)
|
||||
const db = getDb()
|
||||
|
||||
const existing = db.prepare('SELECT slug FROM articles WHERE id = ?').get(id) as { slug: string } | undefined
|
||||
if (!existing) {
|
||||
throw createError({ statusCode: 404, message: '动态不存在', data: { code: 'NOT_FOUND' } })
|
||||
}
|
||||
|
||||
const sets: string[] = []
|
||||
const params: unknown[] = []
|
||||
|
||||
if (body?.slug !== undefined) {
|
||||
const slug = normalizeSlug(body.slug)
|
||||
if (!isValidSlug(slug)) {
|
||||
throw createError({ statusCode: 400, message: 'slug 需为 2-64 位小写字母/数字/中划线', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
const taken = db.prepare('SELECT id FROM articles WHERE slug = ? AND id != ?').get(slug, id)
|
||||
if (taken) {
|
||||
throw createError({ statusCode: 400, message: 'slug 已存在', data: { code: 'SLUG_TAKEN' } })
|
||||
}
|
||||
sets.push('slug = ?'); params.push(slug)
|
||||
}
|
||||
if (body?.category !== undefined) {
|
||||
if (!isValidArticleCategory(body.category)) {
|
||||
throw createError({ statusCode: 400, message: '分类不合法', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
sets.push('category = ?'); params.push(body.category)
|
||||
}
|
||||
for (const field of ['titleZh', 'titleEn', 'excerptZh', 'excerptEn', 'image', 'date', 'author'] as const) {
|
||||
if (body?.[field] !== undefined) {
|
||||
if (field === 'titleZh' || field === 'titleEn') {
|
||||
if (!String(body[field]).trim()) {
|
||||
throw createError({ statusCode: 400, message: '中英文标题不能为空', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
}
|
||||
sets.push(fieldToCol(field) + ' = ?'); params.push(String(body[field]).trim())
|
||||
}
|
||||
}
|
||||
if (body?.readTime !== undefined) {
|
||||
sets.push('read_time = ?'); params.push(Number(body.readTime) || 5)
|
||||
}
|
||||
if (body?.published !== undefined) {
|
||||
sets.push('published = ?'); params.push(body.published ? 1 : 0)
|
||||
}
|
||||
if (body?.contentZh !== undefined) {
|
||||
sets.push('content_zh = ?'); params.push(JSON.stringify(normalizeBlocks(body.contentZh)))
|
||||
}
|
||||
if (body?.contentEn !== undefined) {
|
||||
sets.push('content_en = ?'); params.push(JSON.stringify(normalizeBlocks(body.contentEn)))
|
||||
}
|
||||
|
||||
if (sets.length === 0) {
|
||||
throw createError({ statusCode: 400, message: '没有可更新的字段', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
sets.push("updated_at = datetime('now')")
|
||||
db.prepare(`UPDATE articles SET ${sets.join(', ')} WHERE id = ?`).run(...params, id)
|
||||
|
||||
const row = db.prepare('SELECT slug FROM articles WHERE id = ?').get(id) as { slug: string }
|
||||
return { ok: true, article: getArticleBySlug(row.slug, { publishedOnly: false }) }
|
||||
})
|
||||
|
||||
function fieldToCol(field: string): string {
|
||||
const map: Record<string, string> = {
|
||||
titleZh: 'title_zh', titleEn: 'title_en',
|
||||
excerptZh: 'excerpt_zh', excerptEn: 'excerpt_en',
|
||||
image: 'image', date: 'date', author: 'author',
|
||||
}
|
||||
return map[field]
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { requireAdmin } from '../../utils/auth'
|
||||
import { getDb } from '../../utils/db'
|
||||
|
||||
/**
|
||||
* 后台全站评论列表(含文章 slug 与作者)
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
const comments = getDb()
|
||||
.prepare(
|
||||
`SELECT c.id, c.news_slug AS newsSlug, c.content, c.created_at AS createdAt, u.username
|
||||
FROM comments c
|
||||
JOIN users u ON u.id = c.user_id
|
||||
ORDER BY c.created_at DESC`,
|
||||
)
|
||||
.all()
|
||||
return { comments }
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
import { createError, getRouterParam } from 'h3'
|
||||
import { requireAdmin } from '../../../utils/auth'
|
||||
import { getDb } from '../../../utils/db'
|
||||
|
||||
/**
|
||||
* 后台删除评论
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
const id = Number(getRouterParam(event, 'id'))
|
||||
const db = getDb()
|
||||
const target = db.prepare('SELECT id FROM comments WHERE id = ?').get(id)
|
||||
if (!target) {
|
||||
throw createError({ statusCode: 404, message: '评论不存在', data: { code: 'NOT_FOUND' } })
|
||||
}
|
||||
db.prepare('DELETE FROM comments WHERE id = ?').run(id)
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
import { requireAdmin } from '../../utils/auth'
|
||||
import { getDb } from '../../utils/db'
|
||||
|
||||
/**
|
||||
* 后台联系消息列表
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
const contacts = getDb()
|
||||
.prepare('SELECT id, name, email, subject, message, delivered, created_at AS createdAt FROM contacts ORDER BY created_at DESC')
|
||||
.all()
|
||||
return { contacts }
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
import { createError, getRouterParam } from 'h3'
|
||||
import { requireAdmin } from '../../../utils/auth'
|
||||
import { getDb } from '../../../utils/db'
|
||||
|
||||
/**
|
||||
* 后台删除联系消息
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
const id = Number(getRouterParam(event, 'id'))
|
||||
const db = getDb()
|
||||
const target = db.prepare('SELECT id FROM contacts WHERE id = ?').get(id)
|
||||
if (!target) {
|
||||
throw createError({ statusCode: 404, message: '消息不存在', data: { code: 'NOT_FOUND' } })
|
||||
}
|
||||
db.prepare('DELETE FROM contacts WHERE id = ?').run(id)
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
import { requireAdmin } from '../../utils/auth'
|
||||
import { getDb } from '../../utils/db'
|
||||
import { getContentStats } from '../../utils/content'
|
||||
|
||||
/**
|
||||
* 后台 Dashboard 统计
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
const db = getDb()
|
||||
const one = (sql: string) => (db.prepare(sql).get() as { c: number }).c
|
||||
return {
|
||||
...getContentStats(),
|
||||
users: one('SELECT COUNT(*) AS c FROM users'),
|
||||
comments: one('SELECT COUNT(*) AS c FROM comments'),
|
||||
contacts: one('SELECT COUNT(*) AS c FROM contacts'),
|
||||
subscribers: one('SELECT COUNT(*) AS c FROM subscribers'),
|
||||
favorites: one('SELECT COUNT(*) AS c FROM favorites'),
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
import { requireAdmin } from '../../utils/auth'
|
||||
import { getDb } from '../../utils/db'
|
||||
|
||||
/**
|
||||
* 后台订阅列表
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
const subscribers = getDb()
|
||||
.prepare('SELECT id, email, created_at AS createdAt FROM subscribers ORDER BY created_at DESC')
|
||||
.all()
|
||||
return { subscribers }
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
import { createError, getRouterParam } from 'h3'
|
||||
import { requireAdmin } from '../../../utils/auth'
|
||||
import { getDb } from '../../../utils/db'
|
||||
|
||||
/**
|
||||
* 后台删除订阅
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
const id = Number(getRouterParam(event, 'id'))
|
||||
const db = getDb()
|
||||
const target = db.prepare('SELECT id FROM subscribers WHERE id = ?').get(id)
|
||||
if (!target) {
|
||||
throw createError({ statusCode: 404, message: '订阅不存在', data: { code: 'NOT_FOUND' } })
|
||||
}
|
||||
db.prepare('DELETE FROM subscribers WHERE id = ?').run(id)
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -0,0 +1,23 @@
|
||||
import { requireAdmin } from '../../../utils/auth'
|
||||
import { getDb } from '../../../utils/db'
|
||||
|
||||
/**
|
||||
* 导出订阅 CSV(UTF-8 BOM,兼容 Excel)
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
const rows = getDb()
|
||||
.prepare('SELECT email, created_at AS createdAt FROM subscribers ORDER BY created_at DESC')
|
||||
.all() as Array<{ email: string; createdAt: string }>
|
||||
|
||||
const escape = (v: string) => `"${String(v).replace(/"/g, '""')}"`
|
||||
const lines = ['email,created_at', ...rows.map((r) => `${escape(r.email)},${escape(r.createdAt)}`)]
|
||||
const csv = '' + lines.join('\n')
|
||||
|
||||
return new Response(csv, {
|
||||
headers: {
|
||||
'Content-Type': 'text/csv; charset=utf-8',
|
||||
'Content-Disposition': `attachment; filename="subscribers-${new Date().toISOString().slice(0, 10)}.csv"`,
|
||||
},
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,46 @@
|
||||
import { readMultipartFormData, createError } from 'h3'
|
||||
import { writeFileSync, mkdirSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { requireAdmin } from '../../utils/auth'
|
||||
import { getConfig } from '../../utils/config'
|
||||
|
||||
const MAX_SIZE = 8 * 1024 * 1024 // 8MB
|
||||
const EXT_BY_TYPE: Record<string, string> = {
|
||||
'image/png': 'png',
|
||||
'image/jpeg': 'jpg',
|
||||
'image/gif': 'gif',
|
||||
'image/webp': 'webp',
|
||||
'image/svg+xml': 'svg',
|
||||
'image/avif': 'avif',
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台图片上传 -> 保存到 PVC 的 uploads 目录(/data/uploads),
|
||||
* 通过 /uploads/<name> 对外提供。
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
requireAdmin(event)
|
||||
|
||||
const parts = await readMultipartFormData(event)
|
||||
const file = parts?.find((p) => p.name === 'file' && p.data?.length)
|
||||
if (!file || !file.data) {
|
||||
throw createError({ statusCode: 400, message: '缺少文件', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
const type = file.type || 'application/octet-stream'
|
||||
const ext = EXT_BY_TYPE[type]
|
||||
if (!ext) {
|
||||
throw createError({ statusCode: 400, message: '仅支持图片(png/jpg/gif/webp/svg/avif)', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
if (file.data.length > MAX_SIZE) {
|
||||
throw createError({ statusCode: 400, message: '文件过大(上限 8MB)', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
const name = `${Date.now()}-${randomBytes(6).toString('hex')}.${ext}`
|
||||
const dir = join(dirname(getConfig().dbPath), 'uploads')
|
||||
mkdirSync(dir, { recursive: true })
|
||||
writeFileSync(join(dir, name), file.data)
|
||||
|
||||
return { ok: true, url: `/uploads/${name}` }
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
import { requireAdmin } from '../../utils/auth'
|
||||
import { getDb } from '../../utils/db'
|
||||
|
||||
/**
|
||||
* 后台用户列表
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
const users = getDb()
|
||||
.prepare('SELECT id, username, email, phone, role, created_at AS createdAt FROM users ORDER BY id DESC')
|
||||
.all()
|
||||
return { users }
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import { createError, getRouterParam } from 'h3'
|
||||
import { requireAdmin } from '../../../utils/auth'
|
||||
import { getDb } from '../../../utils/db'
|
||||
|
||||
/**
|
||||
* 后台删除用户(连带删除其会话/评论/收藏)
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
const me = requireAdmin(event)
|
||||
const id = Number(getRouterParam(event, 'id'))
|
||||
const db = getDb()
|
||||
|
||||
if (me.id === id) {
|
||||
throw createError({ statusCode: 400, message: '不能删除自己的账号', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
const target = db.prepare('SELECT id FROM users WHERE id = ?').get(id)
|
||||
if (!target) {
|
||||
throw createError({ statusCode: 404, message: '用户不存在', data: { code: 'NOT_FOUND' } })
|
||||
}
|
||||
db.prepare('DELETE FROM users WHERE id = ?').run(id) // 外键级联:sessions/comments/favorites
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -0,0 +1,28 @@
|
||||
import { readBody, createError, getRouterParam } from 'h3'
|
||||
import { requireAdmin } from '../../../utils/auth'
|
||||
import { getDb } from '../../../utils/db'
|
||||
|
||||
/**
|
||||
* 后台更新用户(角色切换)
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const me = requireAdmin(event)
|
||||
const id = Number(getRouterParam(event, 'id'))
|
||||
const body = await readBody(event)
|
||||
const db = getDb()
|
||||
|
||||
if (me.id === id) {
|
||||
throw createError({ statusCode: 400, message: '不能修改自己的角色', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
const target = db.prepare('SELECT id FROM users WHERE id = ?').get(id)
|
||||
if (!target) {
|
||||
throw createError({ statusCode: 404, message: '用户不存在', data: { code: 'NOT_FOUND' } })
|
||||
}
|
||||
if (body?.role !== undefined) {
|
||||
if (!['user', 'admin'].includes(body.role)) {
|
||||
throw createError({ statusCode: 400, message: '角色不合法', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
db.prepare('UPDATE users SET role = ? WHERE id = ?').run(body.role, id)
|
||||
}
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
import { requireAdmin } from '../../utils/auth'
|
||||
import { listWorks } from '../../utils/content'
|
||||
|
||||
/**
|
||||
* 后台作品列表(含未发布)
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
return { works: listWorks({ publishedOnly: false }) }
|
||||
})
|
||||
@@ -0,0 +1,69 @@
|
||||
import { readBody, createError } from 'h3'
|
||||
import { requireAdmin } from '../../utils/auth'
|
||||
import { getDb } from '../../utils/db'
|
||||
import { getWorkBySlug } from '../../utils/content'
|
||||
import {
|
||||
normalizeSlug,
|
||||
isValidSlug,
|
||||
isValidWorkCategory,
|
||||
normalizeTags,
|
||||
normalizeGallery,
|
||||
} 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 (!isValidWorkCategory(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 (getWorkBySlug(slug, { publishedOnly: false })) {
|
||||
throw createError({ statusCode: 400, message: 'slug 已存在', data: { code: 'SLUG_TAKEN' } })
|
||||
}
|
||||
|
||||
db.prepare(
|
||||
`INSERT INTO works
|
||||
(slug, category, title_zh, title_en, description_zh, description_en,
|
||||
overview_zh, overview_en, challenge_zh, challenge_en, solution_zh, solution_en,
|
||||
client_zh, client_en, duration_zh, duration_en, year, tags, image, gallery, url, published, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))`,
|
||||
).run(
|
||||
slug,
|
||||
body.category,
|
||||
titleZh,
|
||||
titleEn,
|
||||
String(body?.descriptionZh ?? ''),
|
||||
String(body?.descriptionEn ?? ''),
|
||||
String(body?.overviewZh ?? ''),
|
||||
String(body?.overviewEn ?? ''),
|
||||
String(body?.challengeZh ?? ''),
|
||||
String(body?.challengeEn ?? ''),
|
||||
String(body?.solutionZh ?? ''),
|
||||
String(body?.solutionEn ?? ''),
|
||||
String(body?.clientZh ?? ''),
|
||||
String(body?.clientEn ?? ''),
|
||||
String(body?.durationZh ?? ''),
|
||||
String(body?.durationEn ?? ''),
|
||||
String(body?.year ?? ''),
|
||||
JSON.stringify(normalizeTags(body?.tags)),
|
||||
body?.image ? String(body.image).trim() : null,
|
||||
JSON.stringify(normalizeGallery(body?.gallery)),
|
||||
body?.url ? String(body.url).trim() : null,
|
||||
body?.published ? 1 : 0,
|
||||
)
|
||||
|
||||
return { ok: true, work: getWorkBySlug(slug, { publishedOnly: false }) }
|
||||
})
|
||||
@@ -0,0 +1,25 @@
|
||||
import { createError, getRouterParam } from 'h3'
|
||||
import { requireAdmin } from '../../../utils/auth'
|
||||
import { getDb } from '../../../utils/db'
|
||||
|
||||
/**
|
||||
* 后台删除作品(连带清理用户收藏)
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
const id = Number(getRouterParam(event, 'id'))
|
||||
const db = getDb()
|
||||
|
||||
const row = db.prepare('SELECT slug FROM works WHERE id = ?').get(id) as { slug: string } | undefined
|
||||
if (!row) {
|
||||
throw createError({ statusCode: 404, message: '作品不存在', data: { code: 'NOT_FOUND' } })
|
||||
}
|
||||
|
||||
const tx = db.transaction(() => {
|
||||
db.prepare('DELETE FROM favorites WHERE work_slug = ?').run(row.slug)
|
||||
db.prepare('DELETE FROM works WHERE id = ?').run(id)
|
||||
})
|
||||
tx()
|
||||
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -0,0 +1,95 @@
|
||||
import { readBody, createError, getRouterParam } from 'h3'
|
||||
import { requireAdmin } from '../../../utils/auth'
|
||||
import { getDb } from '../../../utils/db'
|
||||
import { getWorkBySlug } from '../../../utils/content'
|
||||
import {
|
||||
normalizeSlug,
|
||||
isValidSlug,
|
||||
isValidWorkCategory,
|
||||
normalizeTags,
|
||||
normalizeGallery,
|
||||
} from '../../../utils/validateContent'
|
||||
|
||||
/**
|
||||
* 后台更新作品(部分字段)
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
requireAdmin(event)
|
||||
const id = Number(getRouterParam(event, 'id'))
|
||||
const body = await readBody(event)
|
||||
const db = getDb()
|
||||
|
||||
const existing = db.prepare('SELECT slug FROM works WHERE id = ?').get(id) as { slug: string } | undefined
|
||||
if (!existing) {
|
||||
throw createError({ statusCode: 404, message: '作品不存在', data: { code: 'NOT_FOUND' } })
|
||||
}
|
||||
|
||||
const sets: string[] = []
|
||||
const params: unknown[] = []
|
||||
|
||||
if (body?.slug !== undefined) {
|
||||
const slug = normalizeSlug(body.slug)
|
||||
if (!isValidSlug(slug)) {
|
||||
throw createError({ statusCode: 400, message: 'slug 需为 2-64 位小写字母/数字/中划线', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
const taken = db.prepare('SELECT id FROM works WHERE slug = ? AND id != ?').get(slug, id)
|
||||
if (taken) {
|
||||
throw createError({ statusCode: 400, message: 'slug 已存在', data: { code: 'SLUG_TAKEN' } })
|
||||
}
|
||||
sets.push('slug = ?'); params.push(slug)
|
||||
}
|
||||
if (body?.category !== undefined) {
|
||||
if (!isValidWorkCategory(body.category)) {
|
||||
throw createError({ statusCode: 400, message: '分类不合法', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
sets.push('category = ?'); params.push(body.category)
|
||||
}
|
||||
for (const field of [
|
||||
'titleZh', 'titleEn', 'descriptionZh', 'descriptionEn',
|
||||
'overviewZh', 'overviewEn', 'challengeZh', 'challengeEn',
|
||||
'solutionZh', 'solutionEn', 'clientZh', 'clientEn',
|
||||
'durationZh', 'durationEn', 'year', 'image', 'url',
|
||||
] as const) {
|
||||
if (body?.[field] !== undefined) {
|
||||
if (field === 'titleZh' || field === 'titleEn') {
|
||||
if (!String(body[field]).trim()) {
|
||||
throw createError({ statusCode: 400, message: '中英文标题不能为空', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
}
|
||||
sets.push(fieldToCol(field) + ' = ?'); params.push(String(body[field]).trim())
|
||||
}
|
||||
}
|
||||
if (body?.tags !== undefined) {
|
||||
sets.push('tags = ?'); params.push(JSON.stringify(normalizeTags(body.tags)))
|
||||
}
|
||||
if (body?.gallery !== undefined) {
|
||||
sets.push('gallery = ?'); params.push(JSON.stringify(normalizeGallery(body.gallery)))
|
||||
}
|
||||
if (body?.published !== undefined) {
|
||||
sets.push('published = ?'); params.push(body.published ? 1 : 0)
|
||||
}
|
||||
|
||||
if (sets.length === 0) {
|
||||
throw createError({ statusCode: 400, message: '没有可更新的字段', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
sets.push("updated_at = datetime('now')")
|
||||
db.prepare(`UPDATE works SET ${sets.join(', ')} WHERE id = ?`).run(...params, id)
|
||||
|
||||
const row = db.prepare('SELECT slug FROM works WHERE id = ?').get(id) as { slug: string }
|
||||
return { ok: true, work: getWorkBySlug(row.slug, { publishedOnly: false }) }
|
||||
})
|
||||
|
||||
function fieldToCol(field: string): string {
|
||||
const map: Record<string, string> = {
|
||||
titleZh: 'title_zh', titleEn: 'title_en',
|
||||
descriptionZh: 'description_zh', descriptionEn: 'description_en',
|
||||
overviewZh: 'overview_zh', overviewEn: 'overview_en',
|
||||
challengeZh: 'challenge_zh', challengeEn: 'challenge_en',
|
||||
solutionZh: 'solution_zh', solutionEn: 'solution_en',
|
||||
clientZh: 'client_zh', clientEn: 'client_en',
|
||||
durationZh: 'duration_zh', durationEn: 'duration_en',
|
||||
year: 'year', image: 'image', url: 'url',
|
||||
}
|
||||
return map[field]
|
||||
}
|
||||
Reference in New Issue
Block a user