本页导航
article
swagger自动生成接口
AI摘要
使用 @zeronejs/cli 工具根据 Swagger 文档自动生成前端 API 接口代码
生成js/ts接口代码
github地址: https://github.com/zeronejs/zerone
官方文档地址:https://zerone.top/guide/cli.html#api
安装
npm i @zeronejs/cli --save-dev
编写swagger.config.json放置在src/api中
{
"docsUrl": "http://www.example.com/v3/api-docs", //json文档地址
"includeTags": [], //要包含的标签(未填充或空数组表示全部包含)
"excludeTags": ["bot-callback-controller"], //要排除的标签
"axiosInstanceUrl": "@/utils/request", //axios实例地址(默认:@/utils/request)
"prefix": "api" //接口添加的前缀
}
运行命令生成代码
//package.json
"scripts": {
"OpenAPI": "zerone api -p ./src/api -d -js"
}
提示
后端swagger的@Tag(name=“UserController”),name需要设置为英文
eslintignore忽略生成的文件
src/api/controller
src/api/interface
生成ts接口代码
github地址:https://github.com/ferdikoomen/openapi-typescript-codegen
安装
npm install openapi-typescript-codegen --save-dev
npm install axios --save-dev
npm install form-data@4.x --save-dev
在tsconfig.json文件中添加以下属性
{
"compilerOptions": {
"lib": ["...", "dom"],
"allowSyntheticDefaultImports": true
}
}
自定义请求文件
import axios, { InternalAxiosRequestConfig } from 'axios';
import { useUserStoreHook } from "@/store/modules/user";
import { CancelablePromise, OpenAPIConfig } from "@/generated";
import { ApiRequestOptions } from "@/generated/core/ApiRequestOptions";
const axiosInstance = axios.create({
baseURL: import.meta.env.VITE_APP_BASE_API,
timeout: 50000,
// todo 必不可少
withCredentials: true,
headers: { 'Content-Type': 'application/json;charset=utf-8' }
});
// 请求拦截器
axiosInstance.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
const userStore = useUserStoreHook();
if (userStore.accessToken) {
config.headers.Authorization = userStore.accessToken;
}
return config;
},
(error: any) => {
return Promise.reject(error);
}
);
// 响应拦截器
axiosInstance.interceptors.response.use(
response => {
const res = response.data
if (res.code !== 0) {
ElMessage({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000
})
if (res.code === 40100) {
ElMessageBox.alert('登录超时', 'Confirm logout', {
confirmButtonText: '确定',
type: 'warning',
center: true,
}).then(() => {
const userStore = useUserStoreHook();
userStore.resetToken();
location.reload();
})
}
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
},
error => {
ElMessage({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export const request = <T>(config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise<T> => {
return new CancelablePromise((resolve: any, reject: any, onCancel: any) => {
const url = `${config.BASE}${options.url}`;
axiosInstance.request({
url,
data: options.body,
method: options.method,
// cancelToken: source.token,
}).then(data => {
resolve(data);
}).catch(error => {
reject(error);
});
});
};
运行命令生成代码
//package.json
"scripts": {
"generate": "openapi --input http://localhost:8101/api/v3/api-docs/default --output ./src/generated --request ./src/utils/axios.ts"
}
eslintignore忽略生成的文件
src/generated
参数说明
$ openapi --help
Usage: openapi [options]
Options:
-V, --version output the version number
-i, --input <value> OpenAPI specification, can be a path, url or string content (required)
-o, --output <value> Output directory (required)
-c, --client <value> HTTP client to generate [fetch, xhr, node, axios, angular] (default: "fetch")
--name <value> Custom client class name
--useOptions Use options instead of arguments
--useUnionTypes Use union types instead of enums
--exportCore <value> Write core files to disk (default: true)
--exportServices <value> Write services to disk (default: true)
--exportModels <value> Write models to disk (default: true)
--exportSchemas <value> Write schemas to disk (default: false)
--indent <value> Indentation options [4, 2, tab] (default: "4")
--postfixServices Service name postfix (default: "Service")
--postfixModels Model name postfix
--request <value> Path to custom request file
-h, --help display help for command
Examples
$ openapi --input ./spec.json --output ./generated
$ openapi --input ./spec.json --output ./generated --client axios
最后更新于 2026-02-18 18:09