swaggerInspect.js
11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
const fs = require("fs");
const http = require("http");
const https = require("https");
const path = require("path");
const MAX_DEPTH = 4;
const DEFAULT_SWAGGER_SNAPSHOT = path.join(__dirname, "__snapshots__/smartcarlife.swagger.json");
const ROUTER_PREFIX = "/router/";
const ROUTER_SUFFIX = "/1.0.0";
function fetchText(url) {
return new Promise((resolve, reject) => {
const lib = url.startsWith("https") ? https : http;
lib.get(url, (res) => {
let raw = "";
res.on("data", (chunk) => { raw += chunk; });
res.on("end", () => resolve(raw));
}).on("error", reject);
});
}
/**
* 加载 Swagger JSON(URL 或本地路径)
*/
async function loadSwagger(source) {
let raw;
if (/^https?:\/\//i.test(source)) {
raw = await fetchText(source);
} else {
raw = fs.readFileSync(source, "utf8");
}
return JSON.parse(raw);
}
/**
* 按 method 名查找 ROP 接口定义
*/
function findMethod(swagger, methodName) {
const route = `/router/${methodName}/1.0.0`;
const op = swagger.paths?.[route]?.post;
if (!op) {
throw new Error(`Method not found in swagger: ${methodName}`);
}
return { route, operation: op };
}
function resolveRef(swagger, ref, depth = 0) {
if (!ref || depth > MAX_DEPTH) {
return null;
}
if (!ref.startsWith("#/definitions/")) {
return { $ref: ref };
}
const key = ref.slice("#/definitions/".length);
return swagger.definitions?.[key] || null;
}
function normalizeType(schema = {}) {
if (schema.$ref) {
return schema.$ref.split("/").pop();
}
if (schema.type === "array" && schema.items) {
const item = normalizeType(schema.items);
return `array<${item}>`;
}
const parts = [schema.type || "object"];
if (schema.format) {
parts.push(schema.format);
}
return parts.join(":");
}
function flattenProperties(swagger, schema, depth = 0, prefix = "") {
if (!schema || depth > MAX_DEPTH) {
return [];
}
if (schema.$ref) {
const resolved = resolveRef(swagger, schema.$ref, depth);
return flattenProperties(swagger, resolved, depth + 1, prefix);
}
if (schema.type === "array" && schema.items) {
return flattenProperties(swagger, schema.items, depth + 1, prefix ? `${prefix}[]` : "item");
}
const fields = [];
if (schema.properties) {
Object.keys(schema.properties).forEach((key) => {
const prop = schema.properties[key];
const path = prefix ? `${prefix}.${key}` : key;
if (prop.$ref || (prop.type === "object" && prop.properties) || (prop.type === "array" && prop.items?.$ref)) {
fields.push({
name: path,
type: normalizeType(prop),
description: prop.description || "",
required: false,
});
fields.push(...flattenProperties(swagger, prop, depth + 1, path));
} else {
fields.push({
name: path,
type: normalizeType(prop),
description: prop.description || "",
required: false,
});
}
});
}
return fields;
}
/**
* 解析请求契约(ROP 多为 query 参数)
*/
function extractRequestContract(operation = {}) {
const params = (operation.parameters || []).map((item) => ({
name: item.name,
in: item.in,
type: item.type || normalizeType(item.schema || {}),
required: !!item.required,
description: item.description || "",
}));
return { parameters: params };
}
/**
* 解析 200 响应契约
*/
function extractResponseContract(swagger, operation = {}) {
const schema = operation.responses?.["200"]?.schema;
if (!schema) {
return { fields: [], pagination: null, rootType: null };
}
const rootType = schema.$ref ? schema.$ref.split("/").pop() : normalizeType(schema);
const pagination = detectPagination(swagger, rootType);
const fields = flattenProperties(swagger, schema);
return { fields, pagination, rootType };
}
/**
* 识别 RpcPagination 结构
*/
function detectPagination(swagger, typeName) {
if (!typeName || !swagger.definitions) {
return null;
}
const def = swagger.definitions[typeName];
if (!def?.$ref && !def?.properties) {
return null;
}
let dataDef = def;
if (def.$ref) {
dataDef = resolveRef(swagger, def.$ref);
}
const dataProp = dataDef?.properties?.data;
if (!dataProp?.$ref) {
return null;
}
const dataTypeName = dataProp.$ref.split("/").pop();
if (!dataTypeName.includes("RpcPagination")) {
return null;
}
const pageDef = resolveRef(swagger, dataProp.$ref);
return {
wrapper: typeName,
type: dataTypeName,
fields: ["pageNum", "pageSize", "total", "list"].filter((k) => pageDef?.properties?.[k]),
};
}
function buildContract(swagger, methodName) {
const { route, operation } = findMethod(swagger, methodName);
const request = extractRequestContract(operation);
const response = extractResponseContract(swagger, operation);
return {
method: methodName,
route,
summary: operation.summary || "",
request,
response,
};
}
function formatContractMarkdown(contract) {
const lines = [
`# ${contract.method}`,
"",
contract.summary ? `> ${contract.summary}` : "",
"",
"## Request",
"",
"| 参数 | 位置 | 类型 | 必填 | 说明 |",
"|------|------|------|------|------|",
];
contract.request.parameters.forEach((p) => {
lines.push(`| ${p.name} | ${p.in} | ${p.type} | ${p.required ? "是" : "否"} | ${p.description} |`);
});
lines.push("", "## Response", "");
if (contract.response.pagination) {
lines.push(`分页: \`${contract.response.pagination.type}\` (${contract.response.pagination.fields.join(", ")})`, "");
}
lines.push("| 字段 | 类型 | 说明 |", "|------|------|------|");
contract.response.fields.forEach((f) => {
lines.push(`| ${f.name} | ${f.type} | ${f.description} |`);
});
return lines.filter((line, index, arr) => !(line === "" && arr[index - 1] === "")).join("\n");
}
function methodSuffixToPascal(methodName) {
const parts = methodName.split(".");
const tail = parts.length >= 2 ? parts.slice(-2) : parts.slice(-1);
return tail.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
}
function toJsdocType(swaggerType = "string") {
const normalized = String(swaggerType).toLowerCase();
if (normalized.includes("int") || normalized === "number" || normalized === "long") {
return "number";
}
if (normalized.includes("bool")) {
return "boolean";
}
if (normalized.startsWith("array<")) {
return `${swaggerType}`;
}
return "string";
}
/**
* 从 contract 生成 JSDoc typedef
*/
function buildJsdocTypedefs(contract) {
const pascal = methodSuffixToPascal(contract.method);
const paramsName = `${pascal}Params`;
const rowName = `${pascal}Row`;
const pageName = `${pascal}PageResponse`;
const requestParams = contract.request.parameters
.filter((p) => p.in === "query" && p.name !== "sessionId");
const paramLines = requestParams.map((p) => {
const optional = p.required ? "" : " [optional]";
return ` * @property {${toJsdocType(p.type)}} ${p.name}${optional}${p.description ? ` - ${p.description}` : ""}`;
});
const rowFields = contract.response.fields
.filter((f) => !f.name.includes(".") && f.name !== "code" && f.name !== "message")
.slice(0, 20);
const rowLines = rowFields.map((f) => (
` * @property {${toJsdocType(f.type)}} ${f.name.split(".").pop()}${f.description ? ` - ${f.description}` : ""}`
));
const lines = [
`/**`,
` * @typedef {Object} ${paramsName}`,
...paramLines.length ? paramLines : [" * @property {*} [field]"],
` */`,
``,
`/**`,
` * @typedef {Object} ${rowName}`,
...rowLines.length ? rowLines : [" * @property {*} [field]"],
` */`,
];
if (contract.response.pagination) {
lines.push(
``,
`/**`,
` * @typedef {Object} ${pageName}`,
` * @property {number} [pageNum]`,
` * @property {number} [pageSize]`,
` * @property {number} [total]`,
` * @property {${rowName}[]} [list]`,
` */`,
);
}
return lines.join("\n");
}
function buildParamsTemplate(contract) {
const pascal = methodSuffixToPascal(contract.method);
const typedefs = buildJsdocTypedefs(contract);
const paramLines = contract.request.parameters
.filter((p) => p.in === "query" && p.name !== "sessionId")
.map((p) => `\tif (params.${p.name} != null && params.${p.name} !== "") {\n\t\tpayload.${p.name} = params.${p.name};\n\t}`)
.join("\n");
return `${typedefs}
/**
* UI/表格参数 → ${contract.method} 请求体
* @param {${pascal}Params} [params]
* @returns {${pascal}Params}
* @see __contracts__/${toMethodFileName(contract.method)}.contract.md
*/
export function build${pascal}Params(params = {}) {
const payload = {};
${paramLines || "\t// TODO: 映射请求参数"}
return payload;
}
export default build${pascal}Params;
`;
}
function buildResponseTemplate(contract) {
const pascal = methodSuffixToPascal(contract.method);
const isPage = !!contract.response.pagination;
const typedefs = buildJsdocTypedefs(contract);
const rowFields = contract.response.fields
.filter((f) => !f.name.includes(".") && f.name !== "code" && f.name !== "message")
.slice(0, 12);
const mapLines = rowFields.map((f) => `\t\t${f.name.split(".").pop()}: row.${f.name.split(".").pop()},`).join("\n");
return `${typedefs}
/**
* ${contract.method} 响应 → 页面数据
* @param {${pascal}Row} [row]
* @returns {${pascal}Row}
* @see __contracts__/${toMethodFileName(contract.method)}.contract.md
*/
export function map${pascal}Row(row = {}) {
return {
${mapLines || "\t\t// TODO: 映射响应字段"}
};
}
${isPage ? `/**
* @param {${pascal}PageResponse} [res]
* @returns {${pascal}PageResponse}
*/
export function map${pascal}PageResponse(res = {}) {
const list = Array.isArray(res.list) ? res.list.map(map${pascal}Row) : [];
return {
...res,
list,
pageNum: res.pageNum ?? res.currentPage,
};
}
` : `/**
* @param {Object} [res]
* @param {Object} [fallback]
* @returns {Object}
*/
export function map${pascal}Response(res = {}, fallback = {}) {
return {
...res,
...fallback,
};
}
`}
export default map${pascal}Row;
`;
}
function buildMockStub(contract, feature) {
const fnName = `mock${methodSuffixToPascal(contract.method)}`;
return `
export function ${fnName}(params = {}) {
\t// TODO: 使用 Swagger 字段名构造 mock 数据,并走 adapter 映射
\treturn delay({});
}
`;
}
function toMethodFileName(methodName) {
return methodName.replace(/\./g, "_");
}
/**
* 统计 swagger paths 中 ROP router method 数量
*/
function countRouterMethods(swagger) {
if (!swagger?.paths) {
return 0;
}
return Object.keys(swagger.paths).filter(
(route) => route.startsWith(ROUTER_PREFIX) && route.endsWith(ROUTER_SUFFIX),
).length;
}
/**
* 按 method 前缀列出所有 ROP 接口
*/
function listMethodsByPrefix(swagger, prefix = "") {
if (!swagger?.paths) {
return [];
}
const methods = [];
Object.keys(swagger.paths).forEach((route) => {
if (!route.startsWith(ROUTER_PREFIX) || !route.endsWith(ROUTER_SUFFIX)) {
return;
}
const method = route.slice(ROUTER_PREFIX.length, -ROUTER_SUFFIX.length);
if (!prefix || method.startsWith(prefix)) {
methods.push(method);
}
});
return methods.sort();
}
module.exports = {
loadSwagger,
findMethod,
extractRequestContract,
extractResponseContract,
detectPagination,
buildContract,
formatContractMarkdown,
methodSuffixToPascal,
buildJsdocTypedefs,
buildParamsTemplate,
buildResponseTemplate,
buildMockStub,
toMethodFileName,
countRouterMethods,
listMethodsByPrefix,
DEFAULT_SWAGGER_SNAPSHOT,
ROUTER_PREFIX,
ROUTER_SUFFIX,
};