334 lines
12 KiB
JavaScript
334 lines
12 KiB
JavaScript
'use strict';
|
||
|
||
const { Service } = require('egg');
|
||
|
||
/** 栏目 code:URL 片段,只用安全字符 */
|
||
const SECTION_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 Section() {
|
||
return this.app.model.DocSection;
|
||
}
|
||
|
||
get Article() {
|
||
return this.app.model.DocArticle;
|
||
}
|
||
|
||
/** CMS 树:栏目 → 文章(文章不带正文,点开再取) */
|
||
async tree() {
|
||
const order = [ [ 'sort', 'ASC' ], [ 'id', 'ASC' ] ];
|
||
const [ sections, articles ] = await Promise.all([
|
||
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 list = sections.map(section => {
|
||
const own = articlesBySection.get(String(section.id)) || [];
|
||
return {
|
||
...this.presentSection(section),
|
||
deleted: Boolean(section.deletedAt),
|
||
articles: own.map(article => this.presentArticle(article, section.code)),
|
||
articleCount: own.length,
|
||
};
|
||
});
|
||
|
||
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 section = await this.Section.findByPk(row.sectionId, { paranoid: false });
|
||
return {
|
||
...this.presentArticle(row, section ? section.code : ''),
|
||
content: row.content || '',
|
||
sectionId: Number(row.sectionId),
|
||
};
|
||
}
|
||
|
||
// ---------------- 栏目 ----------------
|
||
async createSection(body = {}) {
|
||
const payload = await this.normalizeSection(body, null);
|
||
if (!payload.code) payload.code = await this.uniqueSectionCode();
|
||
|
||
const row = await this.Section.create(payload);
|
||
this.app.logger.info('[doc] 新增栏目:id=%s code=%s', row.id, row.code);
|
||
await this.regenerate();
|
||
return this.presentSection(row);
|
||
}
|
||
|
||
async updateSection(id, body = {}) {
|
||
const row = await this.findSection(id);
|
||
const payload = await this.normalizeSection(body, row);
|
||
await row.update(payload);
|
||
this.app.logger.info('[doc] 修改栏目:id=%s %s', row.id, JSON.stringify(payload));
|
||
await this.regenerate();
|
||
return this.presentSection(row);
|
||
}
|
||
|
||
/** 删除栏目:底下的内容页一起软删(页面与 sitemap 一并清掉) */
|
||
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 code=%s', row.id, row.code);
|
||
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);
|
||
|
||
const customSlug = payload.slug;
|
||
if (customSlug) {
|
||
await this.assertSlugFree(payload.sectionId, 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 slug=%s', row.id, payload.sectionId, 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);
|
||
}
|
||
|
||
if (payload.slug && payload.slug !== row.slug) {
|
||
// slug 改了旧链接就失效,所以创建后不允许改
|
||
this.ctx.throw(409, '内容页地址(slug)创建后不能修改');
|
||
}
|
||
if (payload.sectionId && Number(payload.sectionId) !== Number(row.sectionId)) {
|
||
// 换栏目:目标栏目下不能已有同名地址
|
||
await this.assertSlugFree(Number(payload.sectionId), 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 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 (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 (!SECTION_CODE.test(code)) this.ctx.throw(422, '栏目编码只能用小写字母 / 数字 / 短横线(1~32 位)');
|
||
const existing = await this.Section.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;
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
/** 同一栏目下 slug 不能重复 */
|
||
async assertSlugFree(sectionId, slug, id) {
|
||
const existing = await this.Article.findOne({
|
||
where: { sectionId, slug },
|
||
paranoid: false,
|
||
});
|
||
if (existing && Number(existing.id) !== Number(id)) this.ctx.throw(409, `该栏目下已有地址「${slug}」`);
|
||
}
|
||
|
||
/** 没填 code 时生成 `sec1`、`sec2`…(和已有 code 不冲突) */
|
||
async uniqueSectionCode() {
|
||
for (let i = 1; i <= 999; i++) {
|
||
const code = `sec${i}`;
|
||
const existing = await this.Section.findOne({ where: { code }, paranoid: false });
|
||
if (!existing) return code;
|
||
}
|
||
this.ctx.throw(409, '栏目过多,请手动填写栏目编码');
|
||
}
|
||
|
||
// ---------------- 展示 ----------------
|
||
presentSection(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,
|
||
};
|
||
}
|
||
|
||
presentArticle(row, sectionCode) {
|
||
return {
|
||
id: Number(row.id),
|
||
sectionId: Number(row.sectionId),
|
||
sectionCode: sectionCode || '',
|
||
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: sectionCode && row.slug ? `/doc/${sectionCode}/${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;
|