'use strict'; const fs = require('fs'); const { Controller } = require('egg'); /** * 文档站(公开,静态 HTML) * * 后端**不参与渲染**:`service/docSite` 在内容保存时把页面生成到 `run/doc-site`, * 这里只做「路径 → 文件」的映射与缓存头控制。文件被人删了 / 刚部署上来时按需重新生成。 * * - `GET /doc` → 301 到 `/doc/` * - `GET /doc/…` → 生成好的 HTML(栏目首页 `index.html` / 内容页 `.html`) * - `GET /sitemap.txt` → 全站 URL(页面顺序稳定,新增的追加在末尾) */ class WebDocController extends Controller { /** GET /doc(`/doc/` 会被 koa-router 的 strict:false 归到同一条路由,这里区分处理) */ async redirect() { const { ctx } = this; if (ctx.path === '/doc') { ctx.redirect('/doc/'); return; } await this.page(); } /** GET /doc/** */ async page() { const { ctx } = this; await ctx.service.docSite.ensureSite(ctx); const file = ctx.service.docSite.resolveFile(this.relativePath(ctx.path)); if (!file || !this.isfile(file)) { // 页面已经下架 / 改名,文件被清掉了:整站重生成一次再试 await ctx.service.docSite.generate(ctx); if (!file || !this.isfile(file)) ctx.throw(404, '文档页面不存在'); } ctx.set('Cache-Control', 'no-cache'); ctx.type = 'html'; ctx.body = fs.createReadStream(file); } /** GET /sitemap.txt */ async sitemap() { const { ctx } = this; await ctx.service.docSite.ensureSite(ctx); const file = ctx.service.docSite.sitemapPath; if (!this.isfile(file)) await ctx.service.docSite.generate(ctx); ctx.set('Cache-Control', 'no-cache'); ctx.type = 'text/plain; charset=utf-8'; ctx.body = fs.createReadStream(file); } /** `/doc/guide/welcome.html` → `guide/welcome.html`;`/doc/guide/` → `guide/index.html` */ relativePath(pathname) { const clean = String(pathname || '').replace(/^\/doc\/?/, ''); if (!clean) return 'index.html'; return clean.endsWith('/') ? `${clean}index.html` : clean; } isfile(file) { try { return fs.statSync(file).isFile(); } catch { return false; } } } module.exports = WebDocController;