'use strict'; const { Service } = require('egg'); /** 分类 code:URL 片段,只用安全字符 */ const CATEGORY_CODE = /^[a-z0-9][a-z0-9-]{0,31}$/; /** 文章 slug:URL 文件名 */ const ARTICLE_SLUG = /^[a-z0-9][a-z0-9_-]{0,63}$/; const MAX_CONTENT = 200000; function toId(value) { const id = Number(value); return Number.isInteger(id) && id > 0 ? id : 0; } /** * 文档站(简易 CMS)的增删改查 * * 层级固定两级:分类(顶部 tab)→ 栏目(侧边栏分组)→ 内容页(Markdown)。 * **每次写操作后都会整站重生成**(`service/docSite`),保证页面 / 目录 / sitemap 与库一致。 */ class DocService extends Service { get Category() { return this.app.model.DocCategory; } get Section() { return this.app.model.DocSection; } get Article() { return this.app.model.DocArticle; } /** CMS 树:分类 → 栏目 → 文章(文章不带正文,点开再取) */ async tree() { const order = [ [ 'sort', 'ASC' ], [ 'id', 'ASC' ] ]; const [ categories, sections, articles ] = await Promise.all([ this.Category.findAll({ order }), this.Section.findAll({ order }), this.Article.findAll({ order }), ]); const articlesBySection = new Map(); for (const article of articles) { const key = String(article.sectionId); if (!articlesBySection.has(key)) articlesBySection.set(key, []); articlesBySection.get(key).push(article); } const sectionsByCategory = new Map(); for (const section of sections) { const key = String(section.categoryId); if (!sectionsByCategory.has(key)) sectionsByCategory.set(key, []); sectionsByCategory.get(key).push(section); } const list = categories.map(category => { const code = category.code; const ownSections = sectionsByCategory.get(String(category.id)) || []; const groups = ownSections.map(section => ({ id: Number(section.id), categoryId: Number(section.categoryId), name: section.name, sort: Number(section.sort), status: Number(section.status), statusText: Number(section.status) === 1 ? '展示' : '隐藏', deleted: Boolean(section.deletedAt), articles: (articlesBySection.get(String(section.id)) || []).map(article => this.presentArticle(article, code)), })); return { id: Number(category.id), code, name: category.name, description: category.description || '', sort: Number(category.sort), status: Number(category.status), statusText: Number(category.status) === 1 ? '展示' : '隐藏', deleted: Boolean(category.deletedAt), sections: groups, articleCount: groups.reduce((total, group) => total + group.articles.length, 0), }; }); return { list, total: list.length }; } /** 单篇文章(含正文),给编辑表单用 */ async findArticle(id) { const articleId = toId(id); if (!articleId) this.ctx.throw(400, 'id 必须是正整数'); const row = await this.Article.findByPk(articleId, { paranoid: false }); if (!row || row.deletedAt) this.ctx.throw(404, '内容页不存在'); const category = await this.Category.findByPk(row.categoryId, { paranoid: false }); return { ...this.presentArticle(row, category ? category.code : ''), content: row.content || '', categoryId: Number(row.categoryId), sectionId: Number(row.sectionId), }; } // ---------------- 分类 ---------------- async createCategory(body = {}) { const payload = await this.normalizeCategory(body, null); if (!payload.code) payload.code = await this.uniqueCategoryCode(); const row = await this.Category.create(payload); this.app.logger.info('[doc] 新增分类:id=%s code=%s', row.id, row.code); await this.regenerate(); return this.presentCategory(row); } async updateCategory(id, body = {}) { const row = await this.findCategory(id); const payload = await this.normalizeCategory(body, row); await row.update(payload); this.app.logger.info('[doc] 修改分类:id=%s %s', row.id, JSON.stringify(payload)); await this.regenerate(); return this.presentCategory(row); } /** 删除分类:连同栏目 / 内容页一起软删(页面与 sitemap 一并清掉) */ async removeCategory(id) { const row = await this.findCategory(id); const sections = await this.Section.findAll({ where: { categoryId: row.id } }); const sectionIds = sections.map(section => section.id); if (sectionIds.length) { await this.Article.destroy({ where: { sectionId: sectionIds } }); await this.Section.destroy({ where: { id: sectionIds } }); } await row.destroy(); this.app.logger.info('[doc] 删除分类:id=%s code=%s', row.id, row.code); await this.regenerate(); return { id: Number(row.id) }; } async findCategory(id) { const categoryId = toId(id); if (!categoryId) this.ctx.throw(400, 'id 必须是正整数'); const row = await this.Category.findByPk(categoryId); if (!row) this.ctx.throw(404, '分类不存在'); return row; } // ---------------- 栏目 ---------------- async createSection(body = {}) { const payload = this.normalizeSection(body, null); payload.categoryId = await this.assertCategory(body.categoryId); const row = await this.Section.create(payload); this.app.logger.info('[doc] 新增栏目:id=%s category=%s', row.id, payload.categoryId); await this.regenerate(); return this.presentSection(row); } async updateSection(id, body = {}) { const row = await this.findSection(id); const payload = this.normalizeSection(body, row); if (body.categoryId !== undefined && Number(body.categoryId) !== Number(row.categoryId)) { payload.categoryId = await this.assertCategory(body.categoryId); // 栏目换分类时,底下的内容页跟着走(categoryId 冗余在文章上) await this.Article.update({ categoryId: payload.categoryId }, { where: { sectionId: row.id } }); } await row.update(payload); this.app.logger.info('[doc] 修改栏目:id=%s %s', row.id, JSON.stringify(payload)); await this.regenerate(); return this.presentSection(row); } /** 删除栏目:底下的内容页一起软删 */ async removeSection(id) { const row = await this.findSection(id); await this.Article.destroy({ where: { sectionId: row.id } }); await row.destroy(); this.app.logger.info('[doc] 删除栏目:id=%s', row.id); await this.regenerate(); return { id: Number(row.id) }; } async findSection(id) { const sectionId = toId(id); if (!sectionId) this.ctx.throw(400, 'id 必须是正整数'); const row = await this.Section.findByPk(sectionId); if (!row) this.ctx.throw(404, '栏目不存在'); return row; } // ---------------- 内容页 ---------------- async createArticle(body = {}) { const payload = this.normalizeArticle(body, null); const section = await this.findSection(body.sectionId); payload.sectionId = Number(section.id); payload.categoryId = Number(section.categoryId); const customSlug = payload.slug; if (customSlug) { await this.assertSlugFree(payload.categoryId, customSlug, null); } else { // slug 是非空列:先插一个临时值,拿到 id 后再改成稳定的 `a12` payload.slug = `tmp${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`; } const row = await this.Article.create(payload); if (!customSlug) { await row.update({ slug: `a${row.id}` }); } this.app.logger.info('[doc] 新增内容页:id=%s %s/%s', row.id, payload.categoryId, row.slug); await this.regenerate(); return this.findArticle(row.id); } async updateArticle(id, body = {}) { const row = await this.Article.findByPk(toId(id)); if (!row) this.ctx.throw(404, '内容页不存在'); const payload = this.normalizeArticle(body, row); if (body.sectionId !== undefined && Number(body.sectionId) !== Number(row.sectionId)) { const section = await this.findSection(body.sectionId); payload.sectionId = Number(section.id); payload.categoryId = Number(section.categoryId); } if (payload.slug && payload.slug !== row.slug) { // slug 改了旧链接就失效,所以创建后不允许改 this.ctx.throw(409, '内容页地址(slug)创建后不能修改'); } if (payload.categoryId && Number(payload.categoryId) !== Number(row.categoryId)) { // 换分类:目标分类下不能已有同名地址 await this.assertSlugFree(Number(payload.categoryId), row.slug, null); } await row.update(payload); this.app.logger.info('[doc] 修改内容页:id=%s', row.id); await this.regenerate(); return this.findArticle(row.id); } async removeArticle(id) { const row = await this.Article.findByPk(toId(id)); if (!row) this.ctx.throw(404, '内容页不存在'); await row.destroy(); this.app.logger.info('[doc] 删除内容页:id=%s', row.id); await this.regenerate(); return { id: Number(row.id) }; } // ---------------- 校验 ---------------- async normalizeCategory(body = {}, base = null) { const has = key => Object.prototype.hasOwnProperty.call(body, key); const data = {}; if (!base) { if (body.status === undefined || body.status === null) body.status = 1; if (body.sort === undefined || body.sort === null) body.sort = 0; if (body.description === undefined) body.description = null; } if (!base || has('code')) { const code = body.code === undefined || body.code === null ? '' : String(body.code).trim().toLowerCase(); if (base) { if (code && code !== String(base.code)) this.ctx.throw(409, '分类编码创建后不能修改'); } else if (code) { if (!CATEGORY_CODE.test(code)) this.ctx.throw(422, '分类编码只能用小写字母 / 数字 / 短横线(1~32 位)'); const existing = await this.Category.findOne({ where: { code }, paranoid: false }); if (existing) this.ctx.throw(409, `分类编码「${code}」已存在`); data.code = code; } } if (!base || has('name')) { const name = String(body.name === undefined || body.name === null ? '' : body.name).trim(); if (!name) this.ctx.throw(422, '请填写分类名称'); if (name.length > 64) this.ctx.throw(422, '分类名称不能超过 64 个字符'); data.name = name; } if (!base || has('description')) { const description = String(body.description === undefined || body.description === null ? '' : body.description).trim(); if (description.length > 255) this.ctx.throw(422, '分类说明不能超过 255 个字符'); data.description = description || null; } if (!base || has('sort')) data.sort = this.normalizeSort(body.sort); if (!base || has('status')) data.status = this.normalizeStatus(body.status); return data; } normalizeSection(body = {}, base = null) { const has = key => Object.prototype.hasOwnProperty.call(body, key); const data = {}; if (!base) { if (body.status === undefined || body.status === null) body.status = 1; if (body.sort === undefined || body.sort === null) body.sort = 0; } if (!base || has('name')) { const name = String(body.name === undefined || body.name === null ? '' : body.name).trim(); if (!name) this.ctx.throw(422, '请填写栏目名称'); if (name.length > 64) this.ctx.throw(422, '栏目名称不能超过 64 个字符'); data.name = name; } if (!base || has('sort')) data.sort = this.normalizeSort(body.sort); if (!base || has('status')) data.status = this.normalizeStatus(body.status); return data; } normalizeArticle(body = {}, base = null) { const has = key => Object.prototype.hasOwnProperty.call(body, key); const data = {}; if (!base) { if (body.status === undefined || body.status === null) body.status = 1; if (body.sort === undefined || body.sort === null) body.sort = 0; if (body.summary === undefined) body.summary = null; if (body.content === undefined) body.content = ''; if (body.slug === undefined) body.slug = ''; } if (!base || has('title')) { const title = String(body.title === undefined || body.title === null ? '' : body.title).trim(); if (!title) this.ctx.throw(422, '请填写标题'); if (title.length > 128) this.ctx.throw(422, '标题不能超过 128 个字符'); data.title = title; } if (!base || has('slug')) { const slug = String(body.slug === undefined || body.slug === null ? '' : body.slug).trim().toLowerCase(); if (slug) { if (!ARTICLE_SLUG.test(slug)) this.ctx.throw(422, '地址只能用小写字母 / 数字 / 下划线 / 短横线(1~64 位)'); data.slug = slug; } } if (!base || has('summary')) { const summary = String(body.summary === undefined || body.summary === null ? '' : body.summary).trim(); if (summary.length > 255) this.ctx.throw(422, '摘要不能超过 255 个字符'); data.summary = summary || null; } if (!base || has('content')) { const content = String(body.content === undefined || body.content === null ? '' : body.content); if (content.length > MAX_CONTENT) this.ctx.throw(422, `正文不能超过 ${MAX_CONTENT} 个字符`); data.content = content; } if (!base || has('sort')) data.sort = this.normalizeSort(body.sort); if (!base || has('status')) data.status = this.normalizeStatus(body.status); return data; } normalizeSort(value) { const sort = Number(value); if (!Number.isInteger(sort) || sort < 0) this.ctx.throw(422, '排序必须是非负整数'); if (sort > 9999) this.ctx.throw(422, '排序不能超过 9999'); return sort; } normalizeStatus(value) { const status = Number(value); if (status !== 0 && status !== 1) this.ctx.throw(422, '状态只能是 1(展示)或 0(隐藏)'); return status; } async assertCategory(id) { const row = await this.findCategory(id); return Number(row.id); } /** 同一分类下 slug 不能重复(含已删除的行:唯一索引还在) */ async assertSlugFree(categoryId, slug, id) { const existing = await this.Article.findOne({ where: { categoryId, slug }, paranoid: false, }); if (existing && Number(existing.id) !== Number(id)) this.ctx.throw(409, `该分类下已有地址「${slug}」`); } /** 没填 code 时生成 `cat1`、`cat2`…(和已有 code 不冲突) */ async uniqueCategoryCode() { for (let i = 1; i <= 999; i++) { const code = `cat${i}`; const existing = await this.Category.findOne({ where: { code }, paranoid: false }); if (!existing) return code; } this.ctx.throw(409, '分类过多,请手动填写分类编码'); } // ---------------- 展示 ---------------- presentCategory(row) { return { id: Number(row.id), code: row.code, name: row.name, description: row.description || '', sort: Number(row.sort), status: Number(row.status), statusText: Number(row.status) === 1 ? '展示' : '隐藏', createdAt: row.createdAt || null, updatedAt: row.updatedAt || null, }; } presentSection(row) { return { id: Number(row.id), categoryId: Number(row.categoryId), name: row.name, sort: Number(row.sort), status: Number(row.status), statusText: Number(row.status) === 1 ? '展示' : '隐藏', }; } presentArticle(row, categoryCode) { return { id: Number(row.id), categoryId: Number(row.categoryId), sectionId: Number(row.sectionId), categoryCode: categoryCode || '', title: row.title, slug: row.slug, summary: row.summary || '', sort: Number(row.sort), status: Number(row.status), statusText: Number(row.status) === 1 ? '已发布' : '草稿', deleted: Boolean(row.deletedAt), url: categoryCode && row.slug ? `/doc/${categoryCode}/${row.slug}.html` : '', updatedAt: row.updatedAt || null, }; } /** 内容变更后整站重生成(静态 HTML + sitemap) */ async regenerate() { try { await this.ctx.service.docSite.generate(this.ctx); } catch (err) { // 生成失败不该把保存操作回滚,但必须留下日志(下次访问会再试一次) this.app.logger.error('[doc] 生成文档站失败:%s', err && err.message); } } } module.exports = DocService;