UNPKG

auto-request

Version:

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

402 lines (326 loc) 10.1 kB
# auto-request 使用示例 本文档展示 `auto-request` 的实际使用方式,包括完整的类型提示和 IDE 智能感知。 ### 完整的构建脚本 ```typescript // scripts/build-api.ts import { autoRequest, saveSwaggerBackup, type AutoRequestOptions, type SwaggerHttpConfig, } from 'auto-request'; import path from 'path'; // Yapi/Kepler 配置 const fetcherConfig: SwaggerHttpConfig = { url: process.env.API_DOC_URL || 'https://yapi.example.com/api/swagger', method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${process.env.API_TOKEN}`, }, data: { type: 'swagger', project_id: 123, service_id: 456, }, timeout: 30000, }; // 完整配置 const options: AutoRequestOptions = { filename: 'api', isTypeScript: true, // 推荐配置 swaggerBackupPath: path.join(__dirname, '../swagger.json'), snapshotsPath: path.join(__dirname, '../api-changes.md'), loggerPath: path.join(__dirname, '../logs/api-errors.json'), // 完整路径 // CI 环境自动跳过提示 skipPrompt: process.env.CI === 'true', // 过滤不需要的接口 ignoreUrls: [ '/api/internal/*', '/api/test/*', '/api/deprecated/*', ], }; async function main() { try { console.log('🚀 开始生成 API...\n'); const result = await autoRequest( fetcherConfig, path.join(__dirname, '../src/api/'), options ); await result.write(); console.log('\n✅ API 生成成功!'); } catch (error) { console.error('❌ API 生成失败:', error); process.exit(1); } } main(); ``` ## 基础示例 - 完整类型提示 ### 1. TypeScript 项目(推荐) ```typescript // build-api.ts import { autoRequest, // ← IDE 会显示完整函数签名 type AutoRequestOptions, // ← 导入配置类型 } from 'auto-request'; import path from 'path'; // ✅ 配置对象获得完整类型提示和自动补全 const options: AutoRequestOptions = { filename: 'api', // ← IDE 提示:生成文件名 isTypeScript: true, // ← IDE 提示:是否生成 TypeScript // Swagger 对比功能 swaggerBackupPath: './swagger.json', // ← IDE 提示:Swagger 备份路径 snapshotsPath: './snapshots.md', // ← IDE 提示:快照文件路径 // 错误日志 loggerPath: './logs/errors.json', // 完整路径 // 其他配置... // ← 输入时 IDE 会提示所有可用选项 }; // ✅ 函数调用时获得完整类型检查 const swaggerJson = require('./swagger.json'); const result = await autoRequest( JSON.stringify(swaggerJson), // ← 参数类型检查 './src/api/', // ← 参数类型检查 options // ← 参数类型检查 ); await result.write(); // ← 返回值类型提示 ``` ### 2. JavaScript 项目 - 使用 JsDoc ```javascript // build-api.js const { autoRequest } = require('auto-request'); const path = require('path'); /** * @type {import('auto-request').AutoRequestOptions} */ const options = { filename: 'api', isTypeScript: false, // JavaScript 模式 jsdoc: { enabled: true, // ✅ 启用 JsDoc,获得类型提示 }, swaggerBackupPath: './swagger.json', }; // ✅ 即使在 JS 中也能获得类型检查 async function buildApi() { const swaggerJson = require('./swagger.json'); const result = await autoRequest( JSON.stringify(swaggerJson), './src/api/', options ); await result.write(); } buildApi(); ``` ## 高级示例 - 自定义渲染 ### TypeScript + 自定义请求库 ```typescript import { autoRequest, renderMethodArgs, // ← 辅助函数 type AutoRequestOptions } from 'auto-request'; const options: AutoRequestOptions = { filename: 'api', isTypeScript: true, // 自定义文件头部 renderHeaderTemplate: () => { return `import { apiClient } from '@/utils/request';\n\n`; }, // 自定义方法生成(完整类型提示) renderMethodCall: function(this: any) { // ✅ this 上下文提供完整方法信息 const methodName = this.getMethodsName(); // ← 获取方法名 const url = this.getUrl(); // ← 获取 URL const method = this.method; // ← HTTP 方法 // 使用辅助函数渲染参数 const args = renderMethodArgs([ this.getMethodPrePath(), // 路径参数 this.getMethodPreParams(), // 查询参数 this.renderGetMethodData(), // 请求体参数 'options', ]); return ` /** * @description ${this.description || ''} * @summary ${this.summary || ''} */ export const ${methodName} = async (${args}) => { return apiClient.request({ url: \`${url}\`, method: '${method}', ${this.renderOptionsStr.data}, ${this.renderOptionsStr.params}, ...options, }); }; `; }, }; await autoRequest(source, './api/', options); ``` ### JavaScript + 自定义渲染 + 完整类型提示 ```javascript // build-api.js const { autoRequest, renderMethodArgs } = require('auto-request'); /** * @type {import('auto-request').AutoRequestOptions} */ const options = { filename: 'api', isTypeScript: false, jsdoc: { enabled: true }, renderHeaderTemplate: () => { return `import { request } from './request';\n\n`; }, /** * @this {any} // ← 为 this 添加类型注释 */ renderMethodCall: function() { const methodName = this.getMethodsName(); const args = renderMethodArgs([ this.getMethodPrePath(), this.getMethodPreParams(), this.renderGetMethodData(), 'options', ]); // ✅ 关键:添加 @type 引用,获得完整类型提示 return ` /*** * @type {import("./api.types.ts").${methodName}} * @description ${this.description || ''} * @summary ${this.summary || ''} **/ export const ${methodName} = (${args}) => { return request({ url: \`${this.getUrl()}\`, method: '${this.method}', ${this.renderOptionsStr.data}, ${this.renderOptionsStr.params}, ...options, }); }; `; }, }; ``` ## 使用生成的 API - 完整类型安全 ### 生成的文件结构 ``` src/api/ ├── api.ts // 接口函数 └── api.types.ts // TypeScript 类型定义 ``` ### TypeScript 使用(完整类型提示) ```typescript // ✅ 导入接口函数,自动获得类型定义 import { UsersGet, UsersPost, UserDetailGet } from '@/api/api'; // ✅ 函数调用时获得完整类型检查和自动补全 async function fetchUsers() { // IDE 会提示参数类型 const response = await UsersGet({ page: 1, // ← 类型检查 pageSize: 10, // ← 自动补全 }); // response 类型自动推断 console.log(response.data); // ← 类型安全 } // ✅ POST 请求同样获得完整类型提示 async function createUser() { const newUser = await UsersPost({ name: 'John', // ← 类型检查 email: 'john@example.com', // ← 必填字段提示 // age: 'invalid', // ← TypeScript 会报错 }); return newUser; } // ✅ 路径参数也有类型提示 async function getUserDetail(userId: number) { const user = await UserDetailGet( userId, // ← 路径参数类型检查 { include: 'profile' } // ← 查询参数自动补全 ); return user; } ``` ### JavaScript 使用(JsDoc 类型提示) ```javascript // ✅ JavaScript 项目中也能获得类型提示 import { UsersGet, UsersPost } from './api/api'; /** * 获取用户列表 * @returns {Promise<import('./api/api.types').UsersGetResponse>} */ async function fetchUsers() { // ✅ IDE 仍然提供参数提示(基于 JsDoc) const response = await UsersGet({ page: 1, pageSize: 10, }); // ✅ response 对象也有类型提示 console.log(response.data); } ``` ## 实际项目配置示例 ### package.json 脚本配置 ```json { "scripts": { "api:generate": "tsx scripts/build-api.ts", "api:watch": "nodemon --watch swagger.json --exec npm run api:generate", "predev": "npm run api:generate", "prebuild": "npm run api:generate" } } ``` ## 类型提示效果展示 ### IDE 智能提示示例 ```typescript import { autoRequest, type AutoRequestOptions } from 'auto-request'; // ✅ 输入 "options." 时,IDE 会显示: const options: AutoRequestOptions = { filename // 生成文件名 isTypeScript // 是否生成 TypeScript swaggerBackupPath // Swagger 备份路径 snapshotsPath // 快照文件路径 loggerPath // 日志输出目录 loggerFileName // 日志文件名 skipPrompt // 是否跳过提示 ignoreUrls // 忽略的 URL 列表 jsdoc // JsDoc 配置 renderHeaderTemplate // 自定义头部模板 renderMethodCall // 自定义方法生成 // ... 等等 }; // ✅ 鼠标悬停在函数上时,IDE 显示: autoRequest( source: SwaggerSource, // Swagger 数据源 output: string, // 输出目录 options?: AutoRequestOptions // 可选配置 ): Promise<{ write: () => Promise<void>; template: string; }> // ✅ 使用生成的 API 时: import { UsersGet } from './api/api'; UsersGet( params?: UsersGetParams, // ← IDE 显示参数类型 options?: RequestOptions // ← 可选配置 ): Promise<UsersGetResponse> // ← 显示返回类型 ``` ## 总结 使用 `auto-request` 时,无论是 TypeScript 还是 JavaScript 项目,都能获得: ✅ **完整的类型提示** - 导入、配置、调用全流程 ✅ **IDE 智能感知** - 参数自动补全、类型检查 ✅ **错误预防** - 编译时发现类型错误 ✅ **开发效率** - 减少手动查阅文档的时间 ✅ **代码安全** - 类型安全的 API 调用 更多示例请参考: - `tests/dev/account.ts` - TypeScript 完整示例 - `tests/build/account.js` - JavaScript 完整示例 - `README.md` - 详细 API 参考文档