OpenAPI 自动生成接口请求代码

OpenAPI Typescript Codegen
Node.js库,该库基于OpenAPI规范生成Typescript客户端。
https://github.com/ferdikoomen/openapi-typescript-codegen
安装:

1
npm install openapi-typescript-codegen --save-dev

例如通过请求工具类 Axios:

1
openapi --input (这里是你的后端接口文档地址) --output ./generated --client axios

详细用法建议去查看readme

如果想要自定义请求参数,怎么办?
1)使用代码生成器提供的全局参数修改对象:
在/generated/core/OpenAPI.ts 可以修改请求地址

1
2
3
4
5
6
7
8
9
10
11
export const OpenAPI: OpenAPIConfig = {
BASE: 'http://localhost:8101',
VERSION: '1.0',
WITH_CREDENTIALS: false,
CREDENTIALS: 'include',
TOKEN: undefined,
USERNAME: undefined,
PASSWORD: undefined,
HEADERS: undefined,
ENCODE_PATH: undefined,
};

2)直接定义 axios 请求库的全局参数,比如全局请求响应拦截器
文档:https://axios-http.com/docs/interceptors
示例代码:

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
// Add a request interceptor
import axios from "axios";
axios.interceptors.request.use(
function (config) {
// Do something before request is sent
return config;
},
function (error) {
// Do something with request error
return Promise.reject(error);
}
);
// Add a response interceptor
axios.interceptors.response.use(
function (response) {
console.log("响应", response);
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
},
function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
}
);

我放在了/src/plugins/axios中
接着在main.ts中引入一下:

1
import "@/plugins/axios";

OpenAPI 自动生成接口请求代码
https://xmas-nnnut.github.io/2023/09/04/OpenAPI-自动生成接口请求代码/
作者
Xmas-nnnut
发布于
2023年9月4日
许可协议