feat: 添加过滤内部接口的脚本
This commit is contained in:
@@ -4,7 +4,7 @@
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"build": "tsoa -c tsoaConfig.json spec-and-routes && tsc && tsc-alias",
|
||||
"build": "tsoa -c tsoaConfig.json spec-and-routes && node scripts/clean-swagger.js && tsc && tsc-alias",
|
||||
"serve": "yarn build && node ./build/index.js",
|
||||
"start": "nodemon"
|
||||
},
|
||||
|
||||
71
packages/server/scripts/clean-swagger.js
Normal file
71
packages/server/scripts/clean-swagger.js
Normal file
@@ -0,0 +1,71 @@
|
||||
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!");
|
||||
Reference in New Issue
Block a user