编程随笔 编程随笔
  • 前端
  • 后端
  • 星球项目
  • 开源项目
  • 海康AGV
  • 四向车
  • 工具类
  • 项目仓库

    • 部署仓库 (opens new window)
    • 代码仓库 (opens new window)
  • vuepress插件

    • 自动生成导航栏与侧边栏 (opens new window)
    • 评论系统 (opens new window)
    • 全文搜索 (opens new window)
    • 选项卡 (opens new window)
    • 自动生成sitemap (opens new window)
  • 自主开发插件

    • 批量操作frontmatter (opens new window)
    • 链接美化 (opens new window)
    • 折叠代码块 (opens new window)
    • 复制代码块 (opens new window)

liyao52033

走运时,要想到倒霉,不要得意得过了头;倒霉时,要想到走运,不必垂头丧气。心态始终保持平衡,情绪始终保持稳定,此亦长寿之道
  • 前端
  • 后端
  • 星球项目
  • 开源项目
  • 海康AGV
  • 四向车
  • 工具类
  • 项目仓库

    • 部署仓库 (opens new window)
    • 代码仓库 (opens new window)
  • vuepress插件

    • 自动生成导航栏与侧边栏 (opens new window)
    • 评论系统 (opens new window)
    • 全文搜索 (opens new window)
    • 选项卡 (opens new window)
    • 自动生成sitemap (opens new window)
  • 自主开发插件

    • 批量操作frontmatter (opens new window)
    • 链接美化 (opens new window)
    • 折叠代码块 (opens new window)
    • 复制代码块 (opens new window)
  • 知识点

  • 代码调试

  • vue2

  • vue3

    • 注意事项
    • swagger自动生成接口
      • 1. 生成js/ts接口代码
      • 2. 生成ts接口代码
    • 动态路由
    • 整合 Element Plus
    • wangeditor使用
    • monacoEditor使用
    • 自定义404页面
    • 验证码封装
    • 联表查询SQL
    • element-plus多文件手动上传
  • react

  • typescript

  • 前端
  • vue3
华总
2023-08-24
0
0
目录

swagger自动生成接口原创

# 1. 生成js/ts接口代码

github地址: https://github.com/zeronejs/zerone

官方文档地址:https://zerone.top/guide/cli.html#api

# 1.1 安装

npm i @zeronejs/cli --save-dev
1

# 1.2 编写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" //接口添加的前缀
}
1
2
3
4
5
6
7

# 1.3 运行命令生成代码

//package.json
"scripts": {
    "OpenAPI": "zerone api -p ./src/api -d -js"
  }
1
2
3
4

提示

后端swagger的@Tag(name="UserController"),name需要设置为英文

# 1.4 eslintignore忽略生成的文件

src/api/controller
src/api/interface
1
2

# 2. 生成ts接口代码

github地址:https://github.com/ferdikoomen/openapi-typescript-codegen

# 2.1 安装

npm install openapi-typescript-codegen --save-dev
npm install axios --save-dev
npm install form-data@4.x --save-dev
1
2
3

# 2.2 在tsconfig.json文件中添加以下属性

{
    "compilerOptions": {
        "lib": ["...", "dom"],
        "allowSyntheticDefaultImports": true
    }
}
1
2
3
4
5
6

# 2.3 自定义请求文件

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);
	});
  });
};

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

# 2.4 运行命令生成代码

//package.json
"scripts": {
   "generate": "openapi --input http://localhost:8101/api/v3/api-docs/default --output ./src/generated --request ./src/utils/axios.ts"

  }
1
2
3
4
5

# 2.5 eslintignore忽略生成的文件

src/generated
1

# 2.6 参数说明

$ 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
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
#前端#swagger
上次更新: 2024/01/14 16:27:31
注意事项
动态路由

← 注意事项 动态路由→

最近更新
01
element-plus多文件手动上传 原创
11-03
02
TrueLicense 创建及安装证书 原创
10-25
03
手动修改迅捷配置 原创
09-03
04
安装 acme.sh 原创
08-29
05
zabbix部署 原创
08-20
更多文章>
Copyright © 2023-2024 liyao52033
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式