apifox-to-openapi.js
11.7 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
#!/usr/bin/env node
/**
* Apifox 到 OpenAPI 转换工具
*
* 功能:
* 1. 从 Apifox 获取所有接口数据
* 2. 转换为 OpenAPI 3.0 格式
* 3. 保存到 docs/api-specs/ 目录
* 4. 可选择运行 generateApiFromOpenAPI.js 生成 API 代码
*
* 使用:
* node scripts/apifox-to-openapi.js
*
* 环境变量:
* VITE_APIFOX_TOKEN - Apifox API Token
* VITE_APIFOX_PROJECT_ID - Apifox 项目 ID
*/
const fs = require('fs');
const path = require('path');
const https = require('https');
const { execSync } = require('child_process');
// 配置
const CONFIG = {
token: null,
projectId: null,
baseUrl: 'api.apifox.com',
outputDir: path.join(__dirname, '../docs/api-specs'),
autoGenerate: true // 是否自动运行 API 代码生成
};
// 颜色输出
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
green: '\x1b[32m',
yellow: '\x1b[33m',
red: '\x1b[31m',
blue: '\x1b[34m',
cyan: '\x1b[36m'
};
function log(message, color = 'reset') {
console.log(`${colors[color]}${message}${colors.reset}`);
}
// 加载 .env.apifox 文件
function loadEnv() {
const envPath = path.join(__dirname, '../.env.apifox');
if (!fs.existsSync(envPath)) {
log('❌ 未找到 .env.apifox 文件', 'red');
log('📝 请先创建 .env.apifox 文件并填写 Apifox 凭证:', 'yellow');
log('');
log('VITE_APIFOX_TOKEN=your_api_token_here', 'blue');
log('VITE_APIFOX_PROJECT_ID=your_project_id_here', 'blue');
process.exit(1);
}
const env = fs.readFileSync(envPath, 'utf-8');
env.split('\n').forEach(line => {
const [key, ...valueParts] = line.split('=');
const value = valueParts.join('=');
if (key && !key.startsWith('#') && value) {
process.env[key.trim()] = value.trim();
}
});
if (!process.env.VITE_APIFOX_TOKEN || !process.env.VITE_APIFOX_PROJECT_ID) {
log('❌ .env.apifox 文件中缺少必要的配置', 'red');
log('请确保填写了 VITE_APIFOX_TOKEN 和 VITE_APIFOX_PROJECT_ID', 'yellow');
process.exit(1);
}
CONFIG.token = process.env.VITE_APIFOX_TOKEN;
CONFIG.projectId = process.env.VITE_APIFOX_PROJECT_ID;
log(`✅ 已加载配置,项目 ID: ${CONFIG.projectId}`, 'green');
}
// 发送 HTTPS 请求
function httpsRequest(options) {
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
const chunks = [];
res.on('data', chunk => {
chunks.push(chunk);
});
res.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf8').trim();
if (!raw) {
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve({ data: null, total: 0, __empty: true, statusCode: res.statusCode });
return;
}
reject(new Error(`HTTP ${res.statusCode}: Empty response`));
return;
}
try {
const json = JSON.parse(raw.replace(/^\uFEFF/, ''));
if (res.statusCode === 200) {
resolve(json);
} else {
reject(new Error(`HTTP ${res.statusCode}: ${json.message || raw}`));
}
} catch (err) {
reject(new Error(`解析响应失败: ${err.message}`));
}
});
});
req.on('error', reject);
req.end();
});
}
// 获取 Apifox 项目所有接口
async function fetchApis() {
log('\n📡 正在从 Apifox 获取接口数据...', 'blue');
const options = {
hostname: CONFIG.baseUrl,
path: `/api/v1/projects/${CONFIG.projectId}/apis?pageSize=1000`,
method: 'GET',
headers: {
'Authorization': `Bearer ${CONFIG.token}`,
'Content-Type': 'application/json'
}
};
try {
const response = await httpsRequest(options);
const apis = Array.isArray(response.data) ? response.data : [];
log(`✅ 成功获取 ${apis.length} 个接口`, 'green');
return apis;
} catch (err) {
log(`❌ 获取接口失败: ${err.message}`, 'red');
throw err;
}
}
// 获取接口详情
async function fetchApiDetail(apiId) {
const options = {
hostname: CONFIG.baseUrl,
path: `/api/v1/projects/${CONFIG.projectId}/apis/${apiId}`,
method: 'GET',
headers: {
'Authorization': `Bearer ${CONFIG.token}`,
'Content-Type': 'application/json'
}
};
try {
const response = await httpsRequest(options);
return response.data;
} catch (err) {
log(`⚠️ 获取接口详情失败 (${apiId}): ${err.message}`, 'yellow');
return null;
}
}
// 将 Apifox 接口转换为 OpenAPI 3.0 格式
function convertToOpenAPI(apiDetail) {
const attributes = apiDetail.attributes || {};
const method = attributes.method ? attributes.method.toLowerCase() : 'get';
const path = attributes.path || '/';
// 构建参数
const parameters = [];
const requestBody = {};
// 处理 query 参数
if (attributes.parameters && attributes.parameters.length > 0) {
attributes.parameters.forEach(param => {
if (param.in === 'query') {
parameters.push({
name: param.name,
in: 'query',
description: param.description || '',
required: param.required || false,
schema: {
type: param.schema?.type || 'string',
example: param.example
}
});
}
});
}
// 处理 body 参数(POST/PUT 请求)
if (['post', 'put', 'patch'].includes(method)) {
const bodyParams = attributes.requestBody?.content?.['application/json']?.schema?.properties || {};
const requiredParams = attributes.requestBody?.content?.['application/json']?.schema?.required || [];
if (Object.keys(bodyParams).length > 0) {
requestBody.content = {
'application/json': {
schema: {
type: 'object',
properties: bodyParams,
required: requiredParams
}
}
};
}
}
// 构建响应
const responses = {
'200': {
description: '成功',
content: {
'application/json': {
schema: extractResponseSchema(attributes.responses)
}
}
}
};
// 构建 OpenAPI 文档
const openapi = {
openapi: '3.0.0',
info: {
title: attributes.name || apiDetail.id,
description: attributes.description || '',
version: '1.0.0'
},
paths: {
[path]: {
[method]: {
summary: attributes.name || apiDetail.id,
description: attributes.description || '',
parameters,
requestBody: Object.keys(requestBody).length > 0 ? requestBody : undefined,
responses
}
}
}
};
return openapi;
}
// 提取响应结构
function extractResponseSchema(responses) {
if (!responses || responses.length === 0) {
return {
type: 'object',
properties: {
code: { type: 'number', description: '状态码' },
msg: { type: 'string', description: '消息' },
data: { type: 'any', description: '数据' }
}
};
}
const successResponse = responses.find(r => r.code === 200) || responses[0];
if (successResponse && successResponse.schema) {
return successResponse.schema;
}
return {
type: 'object',
properties: {
code: { type: 'number', description: '状态码' },
msg: { type: 'string', description: '消息' },
data: { type: 'any', description: '数据' }
}
};
}
// 将 OpenAPI 对象转换为 YAML 字符串
function openAPIToYAML(openapi) {
const yaml = require('js-yaml');
return yaml.dump(openapi, {
indent: 2,
lineWidth: -1,
noRefs: true
});
}
// 生成 Markdown 文件内容
function generateMarkdown(openapi, apiDetail) {
const yaml = openAPIToYAML(openapi);
const attributes = apiDetail.attributes || {};
return `# ${attributes.name || apiDetail.id}
${attributes.description || '暂无描述'}
## 接口信息
- **方法**: ${attributes.method?.toUpperCase() || 'GET'}
- **路径**: ${attributes.path || '/'}
- **标签**: ${(attributes.tags || []).join(', ') || '默认'}
## OpenAPI 规范
\`\`\`yaml
${yaml}
\`\`\`
`;
}
// 将接口按标签分组
function groupApisByTag(apis) {
const grouped = {};
apis.forEach(api => {
const tags = api.attributes?.tags || ['default'];
const tag = tags[0];
if (!grouped[tag]) {
grouped[tag] = [];
}
grouped[tag].push(api);
});
return grouped;
}
// 生成文件名(从接口路径和名称)
function generateFileName(api) {
const attributes = api.attributes || {};
const path = attributes.path || '/';
const method = attributes.method?.toLowerCase() || 'get';
// 从路径提取文件名
const pathParts = path.split('/').filter(Boolean);
const lastPart = pathParts[pathParts.length - 1] || 'index';
// 移除路径参数
const cleanName = lastPart.replace(/^:/, '').replace(/[^a-zA-Z0-9]/g, '-');
return `${method}-${cleanName}`;
}
// 保存 OpenAPI 文档到文件
async function saveOpenAPIDocs(groupedApis) {
log('\n📝 正在生成 OpenAPI 文档...', 'blue');
// 确保输出目录存在
if (!fs.existsSync(CONFIG.outputDir)) {
fs.mkdirSync(CONFIG.outputDir, { recursive: true });
}
let totalFiles = 0;
for (const [tag, apis] of Object.entries(groupedApis)) {
const moduleDir = path.join(CONFIG.outputDir, tag);
// 创建模块目录
if (!fs.existsSync(moduleDir)) {
fs.mkdirSync(moduleDir, { recursive: true });
}
log(`\n处理模块: ${tag}`, 'cyan');
for (const api of apis) {
try {
// 获取接口详情
const apiDetail = await fetchApiDetail(api.id);
if (!apiDetail) continue;
// 转换为 OpenAPI
const openapi = convertToOpenAPI(apiDetail);
// 生成 Markdown 文件
const fileName = generateFileName(api);
const markdown = generateMarkdown(openapi, apiDetail);
const filePath = path.join(moduleDir, `${fileName}.md`);
// 写入文件
fs.writeFileSync(filePath, markdown, 'utf-8');
log(` ✓ ${fileName}.md`, 'green');
totalFiles++;
} catch (err) {
log(` ✗ 处理失败: ${err.message}`, 'red');
}
}
}
log(`\n✅ 共生成 ${totalFiles} 个 OpenAPI 文档`, 'green');
log(`📁 输出目录: ${CONFIG.outputDir}`, 'blue');
return totalFiles;
}
// 运行 API 代码生成
function runAPIGenerator() {
if (!CONFIG.autoGenerate) {
log('\n⏭️ 跳过 API 代码生成', 'yellow');
return;
}
log('\n🔧 正在运行 API 代码生成...', 'blue');
try {
const generatorPath = path.join(__dirname, 'generateApiFromOpenAPI.js');
execSync(`node "${generatorPath}"`, {
stdio: 'inherit',
cwd: path.join(__dirname, '..')
});
log('✅ API 代码生成完成', 'green');
} catch (err) {
log(`⚠️ API 代码生成失败: ${err.message}`, 'yellow');
}
}
// 主函数
async function main() {
try {
log('\n🚀 Apifox 到 OpenAPI 转换工具', 'bright');
log('=' .repeat(50), 'bright');
// 1. 加载配置
loadEnv();
// 2. 获取接口列表
const apis = await fetchApis();
// 3. 按标签分组
const groupedApis = groupApisByTag(apis);
log(`\n📦 找到 ${Object.keys(groupedApis).length} 个模块:`, 'cyan');
Object.keys(groupedApis).forEach(tag => {
log(` - ${tag} (${groupedApis[tag].length} 个接口)`, 'cyan');
});
// 4. 保存 OpenAPI 文档
await saveOpenAPIDocs(groupedApis);
// 5. 运行 API 代码生成
runAPIGenerator();
// 完成
log('\n✅ 转换完成!', 'green');
log('\n💡 提示:', 'yellow');
log(' 1. 检查 docs/api-specs/ 目录查看生成的 OpenAPI 文档', 'blue');
log(' 2. 检查 src/api/ 目录查看生成的 API 代码', 'blue');
log(' 3. 在组件中导入并使用生成的 API', 'blue');
} catch (err) {
log(`\n❌ 转换失败: ${err.message}`, 'red');
process.exit(1);
}
}
// 运行
main();