generateApiFromOpenAPI.js
12.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
/**
* 从 OpenAPI 文档自动生成 API 接口文件
*
* 功能:
* 1. 扫描 docs/openAPI 目录
* 2. 解析每个 .md 文件中的 OpenAPI YAML 规范
* 3. 提取 API 信息并生成对应的 JavaScript API 文件
* 4. 保存到 src/api/ 目录
*
* 目录结构:
* docs/openAPI/
* ├── 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');
/**
* 提取 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 文档生成完成!');
}
// 执行生成
const openAPIDir = path.resolve(__dirname, '../docs/openAPI');
const outputDir = path.resolve(__dirname, '../src/api');
console.log('=== OpenAPI 转 API 文档生成器 ===\n');
console.log(`输入目录: ${openAPIDir}`);
console.log(`输出目录: ${outputDir}\n`);
scanAndGenerate(openAPIDir, outputDir);