const {
Controller,
} = require('egg');
const fs = require('fs').promises;
const path = require('path');
function escapeHtml(value) {
return String(value || '')
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function toArray(value) {
return Array.isArray(value) ? value : [];
}
function slugify(value) {
return String(value || '')
.toLowerCase()
.replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
.replace(/(^-|-$)/g, '');
}
function isValidDocName(docName) {
return /^[a-zA-Z0-9_-]+$/.test(docName || '');
}
function getDocFilePath(app, docName) {
return path.join(app.baseDir, 'methods', `${docName}.json`);
}
function getDocChangesFilePath(app, docName) {
return path.join(app.baseDir, 'methods', 'changes', `${docName}.json`);
}
function normalizeGroups(docData) {
if (docData && docData.methods && Array.isArray(docData.methods.groups)) {
return docData.methods.groups.map(group => ({
groupName: group.groupName || group.module || 'Default',
module: group.module || '',
list: toArray(group.list),
}));
}
if (docData && Array.isArray(docData.endpoints)) {
return [{
groupName: 'Endpoints',
module: docData.module || '',
list: docData.endpoints,
}];
}
return [];
}
function renderKeyValueRows(items, keyMap) {
if (!items.length) {
return '
| 暂无数据 |
';
}
return items.map(item => {
return `
| ${escapeHtml(item[keyMap.name] || '')} |
${escapeHtml(item[keyMap.type] || '')} |
${item[keyMap.required] ? '是' : '否'} |
${escapeHtml(item[keyMap.description] || '')} |
`;
}).join('');
}
function renderGlobalHeadersControls(globalHeaders) {
const headers = toArray(globalHeaders);
if (!headers.length) {
return '当前文档未定义额外全局 Header
';
}
return ``;
}
function renderMethodCard(item, entryPath, moduleName) {
const headers = toArray(item.headers);
const params = toArray(item.params);
const response = toArray(item.response);
const errors = toArray(item.errors);
const methodName = item.method || item.name || 'unknown';
const description = item.description || '';
const isQimen = moduleName === 'qimen';
const queryHint = isQimen
? 'app_key=xxx&method=...&v=2.0&format=json&sign_method=md5&sign=xxx×tamp=1700000000'
: `method=${methodName}&v=1.0×tamp=1700000000`;
return `
Headers (${headers.length})
| 名称 | 类型 | 必填 | 说明 |
${renderKeyValueRows(headers, {
name: 'name',
type: 'type',
required: 'required',
description: 'description',
})}
Params (${params.length})
| 名称 | 类型 | 必填 | 说明 |
${renderKeyValueRows(params, {
name: 'name',
type: 'type',
required: 'required',
description: 'description',
})}
Response (${response.length})
| 名称 | 类型 | 必填 | 说明 |
${renderKeyValueRows(response, {
name: 'name',
type: 'type',
required: 'required',
description: 'description',
})}
Errors (${errors.length})
| 名称 | 类型 | 必填 | 说明 |
${renderKeyValueRows(errors, {
name: 'code',
type: 'type',
required: 'required',
description: 'message',
})}
在线调试
`;
}
function renderHtmlPage({
docName,
docData,
groups,
docs,
entryPath,
}) {
const methodsCount = groups.reduce((sum, group) => sum + toArray(group.list).length, 0);
const globalHeaders = toArray(docData.headers);
const globalHeadersControls = renderGlobalHeadersControls(globalHeaders);
const rawUrl = `/api/docs/${encodeURIComponent(docName)}/raw`;
const changesUrl = `/api/docs/${encodeURIComponent(docName)}/changes`;
const navHtml = docs.map(name => {
const activeClass = name === docName ? 'active' : '';
return `${escapeHtml(name)}`;
}).join('');
const sidebarHtml = groups.map((group, index) => {
const list = toArray(group.list);
const groupKey = slugify(group.module || group.groupName || `group-${index}`) || `group-${index}`;
const methodsHtml = list.map(item => {
const methodName = item.method || item.name || 'unknown';
const desc = item.description || '';
return `
${escapeHtml(methodName)}
`;
}).join('');
return `
${escapeHtml(group.groupName)} ${list.length}
`;
}).join('');
const groupHtml = groups.map(group => {
const list = toArray(group.list);
const groupKey = slugify(group.module || group.groupName) || 'group';
const cards = list.map(item => renderMethodCard(item, entryPath, docData.module)).join('');
return `
${escapeHtml(group.groupName)} ${escapeHtml(group.module || '')}
${cards || '该分组暂无方法定义
'}
`;
}).join('');
return `
${escapeHtml(docName)} API 文档
${escapeHtml(docData.module || docName)} API 文档
说明: ${escapeHtml(docData.description || '无')}
版本: ${escapeHtml(docData.version || 'N/A')}
更新: ${escapeHtml(docData.updatedAt || 'N/A')}
方法数: ${methodsCount}
统一入口: ${escapeHtml(entryPath)}
全局 Authorization
设置后会自动注入所有“在线调试”请求头,保存在浏览器本地。
全局业务 Header
${globalHeadersControls}
来自 JSON 的 headers 定义;带 * 的字段为必填,支持下拉 list 选择。
${groupHtml || '暂无可展示的方法定义
'}
`;
}
class DocsController extends Controller {
async list() {
const { ctx } = this;
try {
const docs = await this.getDocNames();
if (!docs.length) {
ctx.status = 404;
ctx.body = {
code: 404,
message: 'methods 目录下没有可用的 JSON 文档',
};
return;
}
const fallback = docs.includes('system') ? 'system' : docs[0];
await this.renderDoc(fallback);
} catch (error) {
ctx.status = 500;
ctx.body = {
code: 500,
message: '读取文档失败',
error: error.message,
};
}
}
async api() {
await this.list();
}
async detail() {
const { ctx } = this;
const docName = ctx.params.docName;
await this.renderDoc(docName);
}
async raw() {
const { ctx } = this;
const docName = ctx.params.docName;
if (!isValidDocName(docName)) {
ctx.status = 400;
ctx.body = { code: 400, message: '无效文档名' };
return;
}
const filePath = getDocFilePath(this.app, docName);
try {
const content = await fs.readFile(filePath, 'utf8');
ctx.type = 'application/json; charset=utf-8';
ctx.body = content;
} catch (error) {
ctx.status = 404;
ctx.body = {
code: 404,
message: `未找到文档: ${docName}`,
};
}
}
async changes() {
const { ctx } = this;
const docName = ctx.params.docName;
if (!isValidDocName(docName)) {
ctx.status = 400;
ctx.body = { code: 400, message: '无效文档名' };
return;
}
const filePath = getDocChangesFilePath(this.app, docName);
try {
const content = await fs.readFile(filePath, 'utf8');
ctx.type = 'application/json; charset=utf-8';
ctx.body = toArray(JSON.parse(content));
} catch (error) {
if (error.code === 'ENOENT') {
ctx.type = 'application/json; charset=utf-8';
ctx.body = [];
return;
}
ctx.status = 500;
ctx.body = {
code: 500,
message: `读取变更记录失败: ${docName}`,
error: error.message,
};
}
}
async getDocNames() {
const docsDir = path.join(this.app.baseDir, 'methods');
const entries = await fs.readdir(docsDir, { withFileTypes: true });
return entries
.filter(entry => entry.isFile() && entry.name.endsWith('.json'))
.map(entry => entry.name.replace(/\.json$/i, ''))
.sort();
}
async renderDoc(docName) {
const { ctx, app } = this;
if (!isValidDocName(docName)) {
ctx.status = 400;
ctx.body = { code: 400, message: '无效文档名' };
return;
}
const filePath = getDocFilePath(app, docName);
try {
const [ content, docs ] = await Promise.all([
fs.readFile(filePath, 'utf8'),
this.getDocNames(),
]);
const docData = JSON.parse(content);
const groups = normalizeGroups(docData);
const entryPath = docData.module === 'qimen'
? '/qimen'
: (docData.module === 'gateway' ? '/internal/v1/gateway' : '/system');
const html = renderHtmlPage({
docName,
docData,
groups,
docs,
entryPath,
});
ctx.type = 'text/html; charset=utf-8';
ctx.body = html;
} catch (error) {
ctx.status = 404;
ctx.body = {
code: 404,
message: `未找到文档或 JSON 格式错误: ${docName}`,
error: error.message,
};
}
}
}
module.exports = DocsController;