generateApiFromOpenAPI.cjs
17.9 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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
/**
* 从 OpenAPI 文档自动生成 API 接口文件
*
* 功能:
* 1. 扫描 docs/api-specs 目录
* 2. 解析每个 .md 文件中的 OpenAPI YAML 规范
* 3. 提取 API 信息并生成对应的 JavaScript API 文件
* 4. 保存到 src/api/ 目录
*
* 目录结构:
* docs/api-specs/
* ├── module1/
* │ ├── api1.md
* │ └── api2.md
* └── module2/
* └── api3.md
*
* 生成到:
* src/api/
* ├── module1.js
* └── module2.js
*/
const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
const { generateReport, parseOpenAPIPath } = require('./apiDiff.cjs');
/**
* 提取 Markdown 文件中的 YAML 代码块
* @param {string} content - Markdown 文件内容
* @returns {string|null} - YAML 字符串或 null
*/
function extractYAMLFromMarkdown(content) {
const yamlRegex = /```yaml\s*\n([\s\S]*?)\n```/;
const match = content.match(yamlRegex);
return match ? match[1] : null;
}
/**
* 将字符串转换为驼峰命名
* @param {string} str - 输入字符串
* @returns {string} - 驼峰命名字符串
*/
function toCamelCase(str) {
return str
.replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''))
.replace(/^(.)/, (c) => c.toLowerCase());
}
/**
* 将字符串转换为帕斯卡命名(首字母大写)
* @param {string} str - 输入字符串
* @returns {string} - 帕斯卡命名字符串
*/
function toPascalCase(str) {
const camelCase = toCamelCase(str);
return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
}
/**
* 解析对象属性,生成字段描述
* @param {object} properties - 属性对象
* @param {number} indent - 缩进级别
* @returns {string} - 字段描述字符串
*/
function parseProperties(properties, indent = 0) {
if (!properties) return '';
const lines = [];
const prefix = ' '.repeat(indent);
Object.entries(properties).forEach(([key, value]) => {
const type = value.type || 'any';
const desc = value.description || value.title || '';
const required = value.required ? '' : ' (可选)';
// 基本类型
if (type !== 'object' && type !== 'array') {
lines.push(`${prefix}${key}: ${type}${required} - ${desc}`);
}
// 对象类型
else if (type === 'object' && value.properties) {
lines.push(`${prefix}${key}: {`);
lines.push(`${prefix} // ${desc}`);
lines.push(parseProperties(value.properties, indent + 2));
lines.push(prefix + '}');
}
// 数组类型
else if (type === 'array' && value.items) {
const itemType = value.items.type || 'any';
if (itemType === 'object' && value.items.properties) {
lines.push(`${prefix}${key}: Array<{`);
lines.push(`${prefix} // ${desc}`);
lines.push(parseProperties(value.items.properties, indent + 2));
lines.push(prefix + '}>');
} else {
lines.push(`${prefix}${key}: Array<${itemType}>${required} - ${desc}`);
}
}
});
return lines.join('\n');
}
/**
* 从 requestBody 中提取参数
* @param {object} requestBody - requestBody 对象
* @returns {Array} - 参数数组
*/
function extractRequestParams(requestBody) {
if (!requestBody || !requestBody.content) {
return [];
}
// 获取内容类型(可能是 application/x-www-form-urlencoded 或 application/json)
const content = requestBody.content['application/x-www-form-urlencoded'] ||
requestBody.content['application/json'];
if (!content || !content.schema || !content.schema.properties) {
return [];
}
const params = [];
Object.entries(content.schema.properties).forEach(([key, value]) => {
params.push({
name: key,
type: value.type || 'any',
description: value.description || '',
example: value.example || '',
required: content.schema.required?.includes(key) || false,
});
});
return params;
}
/**
* 生成 JSDoc 参数注释
* @param {Array} parameters - parameters 数组(GET 请求)
* @param {Array} bodyParams - requestBody 参数数组(POST 请求)
* @param {string} method - HTTP 方法
* @returns {string} - JSDoc 参数注释
*/
function generateParamJSDoc(parameters, bodyParams, method) {
const lines = [' * @param {Object} params 请求参数'];
// POST 请求使用 body 参数
if (method === 'POST' && bodyParams && bodyParams.length > 0) {
// 过滤掉 a 和 f 参数
const filteredParams = bodyParams.filter(p => p.name !== 'a' && p.name !== 'f');
filteredParams.forEach((param) => {
const type = param.type || 'any';
const desc = param.description || '';
const required = param.required ? '' : ' (可选)';
lines.push(` * @param {${type}} params.${param.name}${required} ${desc}`);
});
}
// GET 请求使用 query 参数
else if (method === 'GET' && parameters && parameters.length > 0) {
// 只保留 query 参数,过滤 header 参数
const queryParams = parameters.filter(p => p.in === 'query' && p.name !== 'a' && p.name !== 'f');
queryParams.forEach((param) => {
const type = param.schema?.type || 'any';
const desc = param.description || '';
const required = param.required ? '' : ' (可选)';
lines.push(` * @param {${type}} params.${param.name}${required} ${desc}`);
});
}
return lines.join('\n');
}
/**
* 生成 JSDoc 返回值注释
* @param {object} responseSchema - 响应 schema
* @returns {string} - JSDoc 返回值注释
*/
function generateReturnJSDoc(responseSchema) {
if (!responseSchema || !responseSchema.properties) {
return ' * @returns {Promise<{code:number,data:any,msg:string}>} 标准返回';
}
const { code, msg, data } = responseSchema.properties;
let returnDesc = ' * @returns {Promise<{\n';
returnDesc += ' * code: number; // 状态码\n';
returnDesc += ' * msg: string; // 消息\n';
if (data && data.properties) {
returnDesc += ' * data: {\n';
Object.entries(data.properties).forEach(([key, value]) => {
const type = value.type || 'any';
const desc = value.description || value.title || '';
if (type === 'object' && value.properties) {
returnDesc += ` * ${key}: {\n`;
Object.entries(value.properties).forEach(([subKey, subValue]) => {
const subType = subValue.type || 'any';
const subDesc = subValue.description || subValue.title || '';
returnDesc += ` * ${subKey}: ${subType}; // ${subDesc}\n`;
});
returnDesc += ` * };\n`;
} else if (type === 'array' && value.items && value.items.properties) {
returnDesc += ` * ${key}: Array<{\n`;
Object.entries(value.items.properties).forEach(([subKey, subValue]) => {
const subType = subValue.type || 'any';
const subDesc = subValue.description || subValue.title || '';
returnDesc += ` * ${subKey}: ${subType}; // ${subDesc}\n`;
});
returnDesc += ` * }>;\n`;
} else {
returnDesc += ` * ${key}: ${type}; // ${desc}\n`;
}
});
returnDesc += ' * };\n';
} else {
returnDesc += ' * data: any;\n';
}
returnDesc += ' * }>}';
return returnDesc;
}
/**
* 解析 OpenAPI 文档并提取 API 信息
* @param {object} openapiDoc - 解析后的 OpenAPI 对象
* @param {string} fileName - 文件名(用作 API 名称)
* @returns {object} - 提取的 API 信息
*/
function parseOpenAPIDocument(openapiDoc, fileName) {
try {
const path = Object.keys(openapiDoc.paths)[0];
const method = Object.keys(openapiDoc.paths[path])[0];
const apiInfo = openapiDoc.paths[path][method];
// 提取 query 参数
const parameters = apiInfo.parameters || [];
const queryParams = {};
let actionValue = '';
// 提取 body 参数(用于 POST 请求)
const requestBody = apiInfo.requestBody;
const bodyParams = extractRequestParams(requestBody);
// 对于 POST 请求,从 requestBody 中提取 action
if (requestBody && bodyParams.length > 0) {
const actionParam = bodyParams.find(p => p.name === 'a');
if (actionParam) {
actionValue = actionParam.example || '';
}
}
// 对于 GET 请求,从 query 参数中提取 action
if (!actionValue && parameters.length > 0) {
parameters.forEach((param) => {
if (param.in === 'query') {
queryParams[param.name] = param.example || param.schema?.default || '';
// 提取 action 参数(通常是 'a' 参数)
if (param.name === 'a') {
actionValue = param.example || '';
}
}
});
}
// 提取响应结构
const responseSchema = apiInfo.responses?.['200']?.content?.['application/json']?.schema;
return {
summary: apiInfo.summary || fileName,
description: apiInfo.description || '',
method: method.toUpperCase(),
action: actionValue,
queryParams,
parameters, // 保存完整的参数信息用于生成 JSDoc(GET 请求)
bodyParams, // 保存 requestBody 参数用于生成 JSDoc(POST 请求)
responseSchema, // 保存响应结构用于生成 JSDoc
fileName,
};
} catch (error) {
console.error(`解析 OpenAPI 文档失败: ${error.message}`);
return null;
}
}
/**
* 生成 API 文件内容
* @param {string} moduleName - 模块名称
* @param {Array} apis - API 信息数组
* @returns {string} - 生成的文件内容
*/
function generateApiFileContent(moduleName, apis) {
const imports = `import { fn, fetch } from '@/api/fn';\n\n`;
const apiConstants = [];
const apiFunctions = [];
apis.forEach((api) => {
// 生成常量名(帕斯卡命名)
const constantName = toPascalCase(api.fileName);
// 生成函数名(驼峰命名 + API 后缀)
const functionName = toCamelCase(api.fileName) + 'API';
// 添加常量定义
apiConstants.push(
` ${constantName}: '/srv/?a=${api.action}',`
);
// 生成详细的 JSDoc 注释
const paramJSDoc = generateParamJSDoc(api.parameters, api.bodyParams, api.method);
const returnJSDoc = generateReturnJSDoc(api.responseSchema);
// 添加函数定义
const fetchMethod = api.method === 'GET' ? 'fetch.get' : 'fetch.post';
const comment = `/**
* @description: ${api.summary}
${paramJSDoc}
${returnJSDoc}
*/`;
apiFunctions.push(`${comment}\nexport const ${functionName} = (params) => fn(${fetchMethod}(Api.${constantName}, params));`);
});
return `${imports}const Api = {\n${apiConstants.join('\n')}\n}\n\n${apiFunctions.join('\n\n')}\n`;
}
/**
* 扫描目录并处理所有 OpenAPI 文档
* @param {string} openAPIDir - OpenAPI 文档目录
* @param {string} outputDir - 输出目录
*/
function scanAndGenerate(openAPIDir, outputDir) {
if (!fs.existsSync(openAPIDir)) {
console.error(`OpenAPI 目录不存在: ${openAPIDir}`);
return;
}
// 确保输出目录存在
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
// 扫描第一级目录(模块)
const modules = fs.readdirSync(openAPIDir, { withFileTypes: true })
.filter(dirent => dirent.isDirectory())
.map(dirent => dirent.name);
console.log(`找到 ${modules.length} 个模块: ${modules.join(', ')}`);
modules.forEach((moduleName) => {
const moduleDir = path.join(openAPIDir, moduleName);
const apiFiles = fs.readdirSync(moduleDir)
.filter(file => file.endsWith('.md'));
if (apiFiles.length === 0) {
console.log(`模块 ${moduleName} 中没有找到 .md 文件`);
return;
}
console.log(`\n处理模块: ${moduleName}`);
console.log(`找到 ${apiFiles.length} 个 API 文档`);
const apis = [];
apiFiles.forEach((fileName) => {
const filePath = path.join(moduleDir, fileName);
const content = fs.readFileSync(filePath, 'utf8');
const yamlContent = extractYAMLFromMarkdown(content);
if (!yamlContent) {
console.warn(` ⚠️ ${fileName}: 未找到 YAML 代码块`);
return;
}
try {
const openapiDoc = yaml.load(yamlContent);
const apiName = path.basename(fileName, '.md');
const apiInfo = parseOpenAPIDocument(openapiDoc, apiName);
if (apiInfo) {
apis.push(apiInfo);
console.log(` ✓ ${apiName}: ${apiInfo.summary}`);
}
} catch (error) {
console.error(` ✗ ${fileName}: 解析失败 - ${error.message}`);
}
});
// 生成并保存 API 文件
if (apis.length > 0) {
const fileContent = generateApiFileContent(moduleName, apis);
const outputPath = path.join(outputDir, `${moduleName}.js`);
fs.writeFileSync(outputPath, fileContent, 'utf8');
console.log(` 📝 生成文件: ${outputPath}`);
}
});
console.log('\n✅ API 文档生成完成!');
// 对比新旧 API
console.log('\n🔍 开始检测 API 变更...\n');
compareAPIChanges(openAPIDir);
}
/**
* 备份 OpenAPI 文档目录
* @param {string} sourceDir - 源目录
* @returns {string} - 备份目录路径
*/
function backupOpenAPIDir(sourceDir) {
const backupBaseDir = path.resolve(__dirname, '../.tmp');
const backupDir = path.join(backupBaseDir, 'openAPI-backup');
// 创建备份目录
if (!fs.existsSync(backupBaseDir)) {
fs.mkdirSync(backupBaseDir, { recursive: true });
}
// 删除旧备份
if (fs.existsSync(backupDir)) {
fs.rmSync(backupDir, { recursive: true, force: true });
}
// 复制目录
copyDirectory(sourceDir, backupDir);
return backupDir;
}
/**
* 递归复制目录
* @param {string} src - 源路径
* @param {string} dest - 目标路径
*/
function copyDirectory(src, dest) {
if (!fs.existsSync(dest)) {
fs.mkdirSync(dest, { recursive: true });
}
const entries = fs.readdirSync(src, { withFileTypes: true });
for (const entry of entries) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
if (entry.isDirectory()) {
copyDirectory(srcPath, destPath);
} else {
fs.copyFileSync(srcPath, destPath);
}
}
}
/**
* 对比新旧 API 变更
* @param {string} openAPIDir - OpenAPI 文档目录
*/
function compareAPIChanges(openAPIDir) {
const backupDir = path.resolve(__dirname, '../.tmp/openAPI-backup');
const tempDir = path.resolve(__dirname, '../.tmp/openAPI-temp');
// 检查是否存在临时备份(上一次的版本)
if (!fs.existsSync(tempDir)) {
console.log('ℹ️ 首次运行,已建立基线。下次运行将检测 API 变更。');
// 将当前备份移动到临时目录,作为下次对比的基线
if (fs.existsSync(backupDir)) {
fs.renameSync(backupDir, tempDir);
}
return;
}
// 扫描模块
const modules = fs.readdirSync(openAPIDir, { withFileTypes: true })
.filter(dirent => dirent.isDirectory())
.map(dirent => dirent.name);
let hasChanges = false;
const moduleReports = [];
modules.forEach((moduleName) => {
const moduleDir = path.join(openAPIDir, moduleName);
const tempModuleDir = path.join(tempDir, moduleName);
// 如果临时备份中不存在该模块,说明是新增模块
if (!fs.existsSync(tempModuleDir)) {
console.log(`📦 新增模块: ${moduleName}`);
hasChanges = true;
return;
}
// 读取当前和临时备份的文档
const currentFiles = fs.readdirSync(moduleDir).filter(f => f.endsWith('.md'));
const tempFiles = fs.readdirSync(tempModuleDir).filter(f => f.endsWith('.md'));
// 检查是否有文件变更
const hasNewFiles = currentFiles.some(f => !tempFiles.includes(f));
const hasRemovedFiles = tempFiles.some(f => !currentFiles.includes(f));
const hasModifiedFiles = currentFiles.some(f => {
if (!tempFiles.includes(f)) return false;
const currentContent = fs.readFileSync(path.join(moduleDir, f), 'utf8');
const tempContent = fs.readFileSync(path.join(tempModuleDir, f), 'utf8');
return currentContent !== tempContent;
});
if (hasNewFiles || hasRemovedFiles || hasModifiedFiles) {
hasChanges = true;
moduleReports.push({ moduleName, moduleDir, tempModuleDir });
}
});
// 检查删除的模块
const tempModules = fs.existsSync(tempDir)
? fs.readdirSync(tempDir, { withFileTypes: true })
.filter(dirent => dirent.isDirectory())
.map(dirent => dirent.name)
: [];
const deletedModules = tempModules.filter(m => !modules.includes(m));
if (deletedModules.length > 0) {
hasChanges = true;
console.log(`\n❌ 删除模块: ${deletedModules.join(', ')}`);
}
if (!hasChanges) {
console.log('✅ 未检测到 API 变更');
// 更新基线
if (fs.existsSync(backupDir)) {
fs.rmSync(tempDir, { recursive: true, force: true });
fs.renameSync(backupDir, tempDir);
}
return;
}
// 逐个模块对比
console.log('');
moduleReports.forEach(({ moduleName, moduleDir, tempModuleDir }) => {
try {
const oldDocs = parseOpenAPIPath(tempModuleDir);
const newDocs = parseOpenAPIPath(moduleDir);
const report = generateReport(oldDocs, newDocs, 'text');
console.log(report);
console.log('');
} catch (error) {
console.error(`⚠️ 模块 ${moduleName} 对比失败: ${error.message}`);
}
});
// 更新基线:将当前备份作为下次对比的基准
console.log('📝 更新 API 基线...');
if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true, force: true });
}
if (fs.existsSync(backupDir)) {
fs.renameSync(backupDir, tempDir);
}
}
// 执行生成
const openAPIDir = path.resolve(__dirname, '../../../../docs/api-specs');
const outputDir = path.resolve(__dirname, '../../../../src/api');
console.log('=== OpenAPI 转 API 文档生成器 ===\n');
console.log(`输入目录: ${openAPIDir}`);
console.log(`输出目录: ${outputDir}\n`);
// 备份当前的 OpenAPI 文档(用于下次对比)
if (fs.existsSync(openAPIDir)) {
console.log('💾 备份当前 OpenAPI 文档...');
backupOpenAPIDir(openAPIDir);
console.log('');
}
scanAndGenerate(openAPIDir, outputDir);