${title}
${description}。文档结构参考 Swagger 的阅读方式,按分组浏览接口,展开后可以直接查看路径、方法和请求参数规则。
// 接口文档服务
import {
FireDocumentBodyInterFace,
FireDocumentHeadInterFace,
FireDocumentInterFace,
FireDocumentStoreInterFace,
InterceptorType
} from "../types";
import {FireCatRouter} from "../router/router";
import {fixedEndPath} from "../utils/common";
export class FireDocument {
static documents: FireDocumentStoreInterFace[] = [];
static appendDocument(path: string, routes: FireDocumentStoreInterFace['routes']) {
FireDocument.documents.push({
path,
routes
});
}
static createDocumentPayload(router: FireCatRouter, config: FireDocumentHeadInterFace): FireDocumentInterFace {
const body: FireDocumentBodyInterFace[] = [];
router.getDocumentStore().forEach(item => {
item.routes.forEach(route => {
const mission: FireDocumentBodyInterFace = {
path: fixedEndPath(route.path || item.path),
methods: route.method,
rule: [],
description: route.description,
};
route.middlewares.forEach(intItem => {
if (intItem.type == InterceptorType.RULE) {
mission.rule.push(intItem.data);
}
});
body.push(mission);
});
});
body.sort((prev, next) => prev.path.localeCompare(next.path));
return {
title: config.title,
description: config.description,
date: config.date,
version: config.version,
body,
};
}
static server(router: FireCatRouter, path: string, config: FireDocumentHeadInterFace) {
const normalizedPath = fixedEndPath(path);
const jsonPath = fixedEndPath(`${normalizedPath}/json`);
router.router.get(normalizedPath, (ctx)=> {
const doc = FireDocument.createDocumentPayload(router, config);
if (ctx.query.format === 'json') {
ctx.body = doc;
return;
}
ctx.type = 'text/html; charset=utf-8';
ctx.body = FireDocument.renderDocumentPage(doc, jsonPath);
});
router.router.get(jsonPath, (ctx)=> {
ctx.body = FireDocument.createDocumentPayload(router, config);
});
}
static renderDocumentPage(doc: FireDocumentInterFace, jsonPath: string) {
const title = escapeHtml(doc.title || 'API Document');
const description = escapeHtml(doc.description || 'FireCat document service');
const version = escapeHtml(String(doc.version || '1.0.0'));
const date = escapeHtml(formatDocDate(doc.date));
const routeCount = doc.body.length;
const sections = createSections(doc.body);
const navHtml = sections.map(section => {
const children = section.items.map(item => {
return ``;
}).join('');
return `
`;
}).join('');
const contentHtml = sections.map(section => {
const itemsHtml = section.items.map(item => renderEndpointCard(item)).join('');
return `
${section.items.length} endpoint${section.items.length > 1 ? 's' : ''}${escapeHtml(section.title)}
${description}。文档结构参考 Swagger 的阅读方式,按分组浏览接口,展开后可以直接查看路径、方法和请求参数规则。
${escapeHtml(item.path)}
${description}
${escapeHtml(type)}${escapeHtml(required)}| name | type | required | description | constraints |
|---|