UNPKG

auto-request

Version:

通过Yapi JSON Schema生成接口Axios或Taro接口

189 lines (170 loc) 7.15 kB
import { autoRequest, renderMethodArgs, SwaggerFetcherFunction } from '@/index'; import { wrapperMethodPreInterface } from '@/methods/generator-interface'; import path from 'path'; import { accountConfig } from '../base/configs'; const accountApi = require('@/../example/account/swagger.json'); const outputDir = path.join(__dirname, './../../example/account/api/'); const snapshotsFile = path.join(__dirname, './../../example/account/snapshots.md'); const logDir = path.join(__dirname, './../../example/account/api/'); const swaggerBackupPath = path.join(__dirname, './../../example/account/swagger.json'); // Account 配置(包含自定义 renderMethodCall) const getAccountConfig = (): any => ({ ...accountConfig.baseConfig, snapshotsPath: snapshotsFile, loggerPath: path.join(logDir, 'errors.json'), // 使用完整路径 swaggerBackupPath: swaggerBackupPath, skipPrompt: true, // 测试时跳过交互提示 renderHeaderTemplate: () => `import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'\n\n`, renderMethodCall: function (this: any): string { // 清理函数名中的特殊字符 let methodName: string = this.getMethodsName(); // 移除所有花括号及其内容 methodName = methodName.replace(/\{[^}]*\}/g, ''); // 移除所有特殊字符,只保留字母数字和下划线 methodName = methodName.replace(/[^a-zA-Z0-9_]/g, ''); // 使用标准的泛型参数生成器 const preInterface = renderMethodArgs(wrapperMethodPreInterface(this)); // 获取函数参数(带类型) const pathArgs = this.getMethodPrePath(); const paramsArgs = this.getMethodPreParams(); const dataArgs = this.renderGetMethodData(); const optionArgs = this.getMethodOption(); const args = renderMethodArgs([pathArgs, paramsArgs, dataArgs, optionArgs]); const requestArgs = renderMethodArgs([ `url: \`${this.getUrl()}\``, `method: '${this.method}'`, `${this.renderOptionsStr.data}`, `${this.renderOptionsStr.params}`, `...options`, ]); // 生成summary(如果与description不同) const summary = this.description === this.summary ? '' : `\n * @summary ${this.summary}`; return ` /*** * @description ${this.description || ''}${summary} **/ export const ${methodName} = <${preInterface}>(${args}): Promise<S> => { return axios.request({${requestArgs}}) }\n`; }, }); const runGenerator = async (source: any, testName: string) => { console.log(`\n--- Running Account API Generator: ${testName} ---`); try { const result: any = await autoRequest(source, outputDir, getAccountConfig()); await result.write(); console.log(`✅ ${testName} - API generation successful.`); } catch (error) { console.error(`❌ ${testName} - API generation failed:`, error); throw error; } }; const runTests = async (testType: string) => { console.log('\n╔════════════════════════════════════════════╗'); console.log('║ Account API 测试 ║'); console.log('╚════════════════════════════════════════════╝\n'); switch (testType) { case 'local': console.log('=== 测试 1: 从本地 swagger.json 生成 ==='); await runGenerator(JSON.stringify(accountApi), 'Local Swagger JSON'); break; case 'kepler': console.log('=== 测试 2: 从 Kepler API 获取并生成 ==='); const keplerHttpConfig = { url: accountConfig.KEPLER_API.url, method: 'POST' as const, headers: { 'Content-Type': 'application/json', authorization: accountConfig.KEPLER_API.authorization, }, data: { type: 'swagger', include_case: true, ids: [], project_id: accountConfig.KEPLER_API.projectId, service_id: accountConfig.KEPLER_API.serviceId, branch_id: accountConfig.KEPLER_API.branchId, }, timeout: 30000, }; await runGenerator(keplerHttpConfig, 'Kepler API (HTTP Config)'); break; case 'mock': console.log('=== 测试 3: 使用 Mock 数据生成 ==='); const mockFetcher: SwaggerFetcherFunction = async () => { console.log(' → Using mock fetcher...'); return JSON.stringify({ swagger: '2.0', info: { title: 'Mock API', version: '1.0' }, paths: { '/mock/users': { get: { summary: 'Get all mock users', operationId: 'getMockUsers', parameters: [], responses: { 200: { description: 'A list of mock users' } }, }, }, }, }); }; await runGenerator(mockFetcher, 'Mock Data (Custom Function)'); break; case 'all': console.log('=== 测试 ALL: 运行所有测试 ===\n'); // 本地 await runGenerator(JSON.stringify(accountApi), 'Local Swagger JSON'); // Kepler const allKeplerConfig = { url: accountConfig.KEPLER_API.url, method: 'POST' as const, headers: { 'Content-Type': 'application/json', authorization: accountConfig.KEPLER_API.authorization, }, data: { type: 'swagger', include_case: true, ids: [], project_id: accountConfig.KEPLER_API.projectId, service_id: accountConfig.KEPLER_API.serviceId, branch_id: accountConfig.KEPLER_API.branchId, }, timeout: 30000, }; await runGenerator(allKeplerConfig, 'Kepler API (HTTP Config)'); // Mock await runGenerator( async () => { console.log(' → Using mock fetcher for "all" test...'); return JSON.stringify({ swagger: '2.0', info: { title: 'Mock API All', version: '1.0' }, paths: { '/mock/all/items': { get: { summary: 'Get all mock items', operationId: 'getMockAllItems', parameters: [], responses: { 200: { description: 'A list of all mock items' } }, }, }, }, }); }, 'Mock Data (Custom Function for All)' ); break; default: console.log('Usage: npm run dev:test account [local|kepler|mock|all]'); process.exit(1); } console.log('\n╔════════════════════════════════════════════╗'); console.log('║ ✅ 测试完成 ║'); console.log('╚════════════════════════════════════════════╝\n'); }; const testType = process.argv[3] || 'local'; // Default to 'local' runTests(testType).catch((error) => { console.error('Test execution failed:', error); process.exit(1); });