Files
egret-app-template/packages/server/scripts/clean-swagger.js

72 lines
2.0 KiB
JavaScript
Raw Normal View History

import fs from "fs";
const filePath = "./build/swagger.json";
const swagger = JSON.parse(fs.readFileSync(filePath, "utf8"));
// ==============================
// ① 删除不希望公开的接口路径
// ==============================
const pathsToRemove = ["/api/test", "/api/user/info", "/api/group/members"];
for (const path of pathsToRemove) {
if (swagger.paths?.[path]) {
delete swagger.paths[path];
console.log(`🧹 Removed path: ${path}`);
}
}
// ==============================
// ② 收集引用的 schema 名称(递归)
// ==============================
const referenced = new Set();
function collectRefs(obj) {
if (!obj || typeof obj !== "object") return;
for (const key in obj) {
const value = obj[key];
if (key === "$ref" && typeof value === "string" && value.startsWith("#/components/schemas/")) {
const name = value.split("/").pop();
if (!referenced.has(name)) {
referenced.add(name);
// 递归收集该 schema 内的引用
const schema = swagger.components?.schemas?.[name];
if (schema) collectRefs(schema);
}
} else {
collectRefs(value);
}
}
}
// 先从 paths 开始收集
collectRefs(swagger.paths);
// 然后递归收集 schemas 内部互相引用的部分
let prevCount = 0;
do {
prevCount = referenced.size;
for (const name of Array.from(referenced)) {
const schema = swagger.components?.schemas?.[name];
if (schema) collectRefs(schema);
}
} while (referenced.size > prevCount);
// ==============================
// ③ 删除未被引用的 schema
// ==============================
if (swagger.components?.schemas) {
const allSchemas = Object.keys(swagger.components.schemas);
const unused = allSchemas.filter((name) => !referenced.has(name));
for (const name of unused) {
delete swagger.components.schemas[name];
}
console.log(`🧩 Removed ${unused.length} unused schemas`);
}
// ==============================
// ④ 保存结果
// ==============================
fs.writeFileSync(filePath, JSON.stringify(swagger, null, 2));
console.log("✅ Swagger cleanup complete!");