在现代前端开发中,与后端 API 的对接是一项重要且重复性高的工作。为了提高开发效率并减少手动编写 API 请求代码的工作量,我们可以使用 openapi-ts-request 工具,根据 Apifox 文档自动生成 TypeScript 类型安全的 API 请求文件。
openapi-ts-request 是一个基于 OpenAPI 规范的代码生成工具,它可以从 API 文档自动生成类型定义和请求函数。通过与 Apifox 平台集成,我们可以直接从项目文档生成完整的 API 客户端代码。
首先,在项目根目录下创建配置文件,例如 openapi-ts.config.ts:
import type { GenerateServiceProps } from 'openapi-ts-request'
export default [
{
serversPath: './src/api/openApiRequest',
requestLibPath: `import request from '@/http/openApiRequest';\n import { CustomRequestOptions } from '@/http/interceptor';`,
requestOptionsType: 'CustomRequestOptions',
reactQueryMode: 'vue',
enableLogging: true,
isGenJavaScript: false,
apifoxConfig: {
oasVersion: '3.1',
projectId: '66666',//项目ID 需要拥有项目导出权限
apifoxToken: 'APS-xxxx', //apifox中获取的token
},
hook: {
// 生成自定义方法名称的函数
customFunctionName: (data) => {
// 查找路径中第一个'{'的位置,用于处理带参数的路径
const index = data.path.indexOf('{')
let newPath = data.path
if (index !== -1) {
// 如果路径中有参数(用{}表示),则截取参数前的部分
newPath = data.path.slice(0, index - 1)
}
// 定义首字母大写函数
const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1)
// 分割路径并过滤空字符串
const paths = newPath.split('/').filter(path => path)
// 获取倒数第二个路径段并首字母大写
const secondLastPath = capitalize(paths[paths.length - 2])
// 获取最后一个路径段并首字母大写
const lastPath = capitalize(paths[paths.length - 1])
// 返回组合的方法名:HTTP方法名 + 倒数第二路径 + 最后路径(如:get:/api/user/list -> getUserList,post:/api/user/add -> postAddUser)
return `${data.method}${secondLastPath}${lastPath}`
},
},
},
] as GenerateServiceProps[]
| 配置项 | 说明 |
|---|---|
serversPath | 生成文件的存放路径 |
requestLibPath | 自定义请求库的引入路径 |
requestOptionsType | 请求选项的类型定义 |
reactQueryMode | 设置为 'vue' 以适配 Vue 项目 |
enableLogging | 是否启用日志输出 |
isGenJavaScript | 是否生成 JavaScript 代码(false 表示生成 TypeScript) |
apifoxConfig | Apifox 项目配置 |
运行命令后,工具会在指定位置自动生成以下文件:
src/
└── api/
└── openApiRequest/
├── common.ts
├── index.ts
├── types.ts
└── v1.ts
生成的 API 请求函数具有完整的类型支持:
/** 派遣战舰远征 POST /api/v1/game/warshipAdventure */
export async function postGameWarshipAdventure({
body,
options,
}: {
body: API.PostGameWarshipAdventureBody;
options?: CustomRequestOptions;
}) {
return request<API.PostGameWarshipAdventureResponse>(
'/api/v1/game/warshipAdventure',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
data: body,
...(options || {}),
}
);
}
通过使用 openapi-ts-request,我们可以显著提高 API 对接的效率,同时确保类型安全,减少人为错误。
(注:文档内容由 Copilot 生成)