swagger2api-v3 1.0.7 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,39 +1,41 @@
1
1
  # Swagger2API-v3
2
2
 
3
- 一个强大的命令行工具,用于从 Swagger/OpenAPI 文档自动生成 TypeScript 接口代码。
3
+ English | [中文](./README_CN.md)
4
4
 
5
- ## 特性
5
+ A powerful command-line tool for automatically generating TypeScript interface code from Swagger (OAS3.0) documentation.
6
6
 
7
- - 🚀 **快速生成** - 从 Swagger JSON 快速生成 TypeScript 接口代码
8
- - 📁 **智能分组** - 支持按 Swagger 标签自动分组生成文件
9
- - 📝 **详细注释** - 自动生成包含描述、参数、返回值的详细注释
10
- - 🎨 **代码格式化** - 支持自定义格式化命令
11
- - ⚙️ **环境适配** - 自动检测项目环境,生成对应格式的配置文件
12
- - 🔧 **CLI 工具** - 提供完整的命令行工具
7
+ ## Features
13
8
 
14
- ## 📦 安装
9
+ - 🚀 **Fast Generation** - Quickly generate TypeScript interface code from Swagger JSON
10
+ - 📁 **Smart Grouping** - Support automatic file grouping by Swagger tags
11
+ - 📝 **Detailed Comments** - Automatically generate detailed comments including descriptions, parameters, and return values
12
+ - 🎨 **Code Formatting** - Support custom formatting commands
13
+ - ⚙️ **Environment Adaptation** - Automatically detect project environment and generate corresponding configuration files
14
+ - 🔧 **CLI Tool** - Provide complete command-line tools
15
+
16
+ ## 📦 Installation
15
17
 
16
18
  ```bash
17
- # 全局安装
19
+ # Global installation
18
20
  npm install -g swagger2api-v3
19
21
 
20
- # 项目依赖
22
+ # Project dependency
21
23
  npm install swagger2api-v3
22
24
  ```
23
25
 
24
- ## 🚀 快速开始
26
+ ## 🚀 Quick Start
25
27
 
26
- ### 1. 初始化配置文件
28
+ ### 1. Initialize Configuration File
27
29
 
28
30
  ```bash
29
- swagger2api-v3 init
31
+ npx swagger2api-v3 init
30
32
  ```
31
33
 
32
- ### 2. 配置文件说明
34
+ ### 2. Configuration File Description
33
35
 
34
- 工具会根据项目环境自动生成对应格式的配置文件:
36
+ The tool automatically generates configuration files in the corresponding format based on the project environment:
35
37
 
36
- **CommonJS 环境** (`"type": "commonjs"` 或未设置)
38
+ **CommonJS Environment** (`"type": "commonjs"` or not set):
37
39
  ```javascript
38
40
  const config = {
39
41
  input: 'https://petstore.swagger.io/v2/swagger.json',
@@ -52,80 +54,80 @@ const config = {
52
54
  module.exports = config;
53
55
  ```
54
56
 
55
- **ES 模块环境** (`"type": "module"`)
57
+ **ES Module Environment** (`"type": "module"`):
56
58
  ```javascript
57
59
  const config = {
58
- // ... 相同配置
60
+ // ... same configuration
59
61
  };
60
62
 
61
63
  export default config;
62
64
  ```
63
65
 
64
- ### 3. 生成接口代码
66
+ ### 3. Generate Interface Code
65
67
 
66
68
  ```bash
67
- swagger2api-v3 generate
69
+ npx swagger2api-v3 generate
68
70
  ```
69
71
 
70
- ## ⚙️ 配置选项
72
+ ## ⚙️ Configuration Options
71
73
 
72
- | 选项 | 类型 | 默认值 | 说明 |
73
- |------|------|--------|------|
74
- | `input` | string | - | Swagger JSON 文件路径或 URL |
75
- | `output` | string | `'./src/api'` | 生成代码的输出目录 |
76
- | `generator` | string | `'typescript'` | 代码生成器类型 |
77
- | `groupByTags` | boolean | `true` | 是否按标签分组生成文件 |
78
- | `overwrite` | boolean | `true` | 是否覆盖已存在的文件 |
79
- | `prefix` | string | `''` | 接口路径公共前缀 |
80
- | `importTemplate` | string | - | request 函数导入语句模板 |
81
- | `lint` | string | - | 代码格式化命令(可选) |
82
- | `options.addComments` | boolean | `true` | 是否添加详细注释 |
74
+ | Option | Type | Default | Description |
75
+ |--------|------|---------|-------------|
76
+ | `input` | string | - | Swagger JSON file path or URL |
77
+ | `output` | string | `'./src/api'` | Output directory for generated code |
78
+ | `generator` | string | `'typescript'` | Code generator type |
79
+ | `groupByTags` | boolean | `true` | Whether to group files by tags |
80
+ | `overwrite` | boolean | `true` | Whether to overwrite existing files |
81
+ | `prefix` | string | `''` | Common prefix for API paths |
82
+ | `importTemplate` | string | - | Import statement template for request function |
83
+ | `lint` | string | - | Code formatting command (optional) |
84
+ | `options.addComments` | boolean | `true` | Whether to add detailed comments |
83
85
 
84
- ## 📁 生成的文件结构
86
+ ## 📁 Generated File Structure
85
87
 
86
- ### 按标签分组 (推荐)
88
+ ### Grouped by Tags (Recommended)
87
89
 
88
90
  ```
89
91
  src/api/
90
- ├── types.ts # 数据类型定义
91
- ├── user/ # User 相关接口
92
+ ├── types.ts # Data type definitions
93
+ ├── user/ # User-related APIs
92
94
  │ └── index.ts
93
- ├── auth/ # Auth 相关接口
95
+ ├── auth/ # Auth-related APIs
94
96
  │ └── index.ts
95
- └── index.ts # 入口文件
97
+ └── index.ts # Entry file
96
98
  ```
97
99
 
98
- ### 不分组
100
+ ### Not Grouped
99
101
 
100
102
  ```
101
103
  src/api/
102
- ├── types.ts # 数据类型定义
103
- ├── api.ts # 所有 API 接口
104
- └── index.ts # 入口文件
104
+ ├── types.ts # Data type definitions
105
+ ├── api.ts # All API interfaces
106
+ └── index.ts # Entry file
105
107
  ```
106
108
 
107
- ## 💡 使用示例
109
+ ## 💡 Usage Examples
108
110
 
109
- ### 生成的类型定义
111
+ ### Generated Type Definitions
110
112
 
111
113
  ```typescript
112
114
  // types.ts
113
115
  export interface LoginDto {
114
- /** 账号 */
116
+ /** Account */
115
117
  account: string;
116
- /** 密码 */
118
+ /** Password */
117
119
  password: string;
118
120
  }
119
121
 
120
122
  export interface UserInfo {
121
- /** 用户ID */
123
+ /** User ID */
122
124
  id: string;
123
- /** 用户名 */
125
+ /** Username */
124
126
  username: string;
125
127
  }
126
128
  ```
127
129
 
128
- ### 生成的 API 接口
130
+ ### Generated API Interfaces
129
131
 
130
132
  ```typescript
131
133
  // authController/index.ts
@@ -133,9 +135,9 @@ import { request } from '@/utils/request';
133
135
  import type { LoginDto, LoginRespDto } from '../types';
134
136
 
135
137
  /**
136
- * 登录
137
- * @param data 登录参数
138
- * @param config 可选的请求配置
138
+ * Login
139
+ * @param data Login parameters
140
+ * @param config Optional request configuration
139
141
  */
140
142
  export const authControllerLoginPost = (data: LoginDto, config?: any) => {
141
143
  return request.post<LoginRespDto>({
@@ -146,51 +148,52 @@ export const authControllerLoginPost = (data: LoginDto, config?: any) => {
146
148
  };
147
149
  ```
148
150
 
149
- ## 🔧 CLI 命令
151
+ ## 🔧 CLI Commands
150
152
 
151
153
  ```bash
152
- # 初始化配置文件
153
- swagger2api-v3 init [--force]
154
+ # Initialize configuration file
155
+ npx swagger2api-v3 init [--force]
154
156
 
155
- # 生成接口代码
156
- swagger2api-v3 generate [--config <path>]
157
+ # Generate interface code
158
+ npx swagger2api-v3 generate [--config <path>]
157
159
 
158
- # 验证配置文件
159
- swagger2api-v3 validate [--config <path>]
160
+ # Validate configuration file
161
+ npx swagger2api-v3 validate [--config <path>]
160
162
 
161
- # 查看帮助
162
- swagger2api-v3 --help
163
+ # Show help
164
+ npx swagger2api-v3 --help
163
165
  ```
164
166
 
165
- ## 📝 NPM 脚本
167
+ ## 📝 NPM Scripts
166
168
 
167
- `package.json` 中添加:
169
+ Add to `package.json`:
168
170
 
169
171
  ```json
170
172
  {
171
173
  "scripts": {
172
174
  "api:generate": "swagger2api-v3 generate",
173
- "api:init": "swagger2api-v3 init"
175
+ "api:init": "swagger2api-v3 init",
176
+ "api:validate": "swagger2api-v3 validate"
174
177
  }
175
178
  }
176
179
  ```
177
180
 
178
- ## 🎨 代码格式化
181
+ ## 🎨 Code Formatting
179
182
 
180
- 支持在生成完成后自动执行格式化命令:
183
+ Support automatic execution of formatting commands after generation:
181
184
 
182
185
  ```javascript
183
- // 配置文件中
186
+ // In configuration file
184
187
  const config = {
185
- // ... 其他配置
186
- lint: 'prettier --write' // 'eslint --fix'
188
+ // ... other configurations
189
+ lint: 'prettier --write' // or 'eslint --fix', etc.
187
190
  };
188
191
  ```
189
192
 
190
- ## 🤝 贡献
193
+ ## 🤝 Contributing
191
194
 
192
- 欢迎提交 Issue Pull Request!
195
+ Issues and Pull Requests are welcome!
193
196
 
194
- ## 📄 许可证
197
+ ## 📄 License
195
198
 
196
199
  MIT License
package/dist/cli/index.js CHANGED
@@ -109,43 +109,43 @@ program
109
109
  console.warn('⚠️ 无法读取package.json,使用默认CommonJS格式');
110
110
  }
111
111
  }
112
- const configContent = `/**
113
- * Swagger2API 配置文件
114
- * 用于配置从 Swagger JSON 生成前端接口的参数
115
- */
116
- const config = {
117
- // Swagger JSON 文件路径或 URL
118
- input: 'http://localhost:3000/admin/docs/json',
119
-
120
- // 输出目录
121
- output: './src/api',
122
-
123
- // request 导入路径模板
124
- importTemplate: "import { request } from '@/utils/request';",
125
-
126
- // 生成器类型
127
- generator: 'typescript',
128
-
129
- // 按标签分组生成文件
130
- groupByTags: true,
131
-
132
- // 是否覆盖更新,默认为true。为true时会先删除输出目录下的所有文件
133
- overwrite: true,
134
-
135
- // 接口路径公共前缀,默认为空字符串
136
- prefix: '',
137
-
138
- // 代码格式化命令(可选)
139
- lint: 'prettier --write',
140
-
141
- // 生成选项
142
- options: {
143
- // 是否添加注释
144
- addComments: true
145
- }
146
- };
147
-
148
- ${isESModule ? 'export default config;' : 'module.exports = config;'}
112
+ const configContent = `/**
113
+ * Swagger2API 配置文件
114
+ * 用于配置从 Swagger JSON 生成前端接口的参数
115
+ */
116
+ const config = {
117
+ // Swagger JSON 文件路径或 URL
118
+ input: 'http://localhost:3000/admin/docs/json',
119
+
120
+ // 输出目录
121
+ output: './src/api',
122
+
123
+ // request 导入路径模板
124
+ importTemplate: "import { request } from '@/utils/request';",
125
+
126
+ // 生成器类型
127
+ generator: 'typescript',
128
+
129
+ // 按标签分组生成文件
130
+ groupByTags: true,
131
+
132
+ // 是否覆盖更新,默认为true。为true时会先删除输出目录下的所有文件
133
+ overwrite: true,
134
+
135
+ // 接口路径公共前缀,默认为空字符串
136
+ prefix: '',
137
+
138
+ // 代码格式化命令(可选)
139
+ lint: 'prettier --write',
140
+
141
+ // 生成选项
142
+ options: {
143
+ // 是否添加注释
144
+ addComments: true
145
+ }
146
+ };
147
+
148
+ ${isESModule ? 'export default config;' : 'module.exports = config;'}
149
149
  `;
150
150
  try {
151
151
  fs.writeFileSync(configPath, configContent, 'utf-8');
@@ -120,6 +120,7 @@ function swaggerTypeToTsType(schema) {
120
120
  if (!schema) {
121
121
  return 'any';
122
122
  }
123
+ let baseType;
123
124
  // 处理 allOf 类型组合
124
125
  if (schema.allOf && schema.allOf.length > 0) {
125
126
  // 检查是否为泛型模式:第一个是引用类型,第二个定义了扩展属性
@@ -137,7 +138,7 @@ function swaggerTypeToTsType(schema) {
137
138
  }
138
139
  // 如果只有一个属性,直接作为泛型参数
139
140
  if (propertyTypes.length === 1) {
140
- return `${refName}<${propertyTypes[0]}>`;
141
+ baseType = `${refName}<${propertyTypes[0]}>`;
141
142
  }
142
143
  // 如果有多个属性,组合成联合类型或对象类型
143
144
  else if (propertyTypes.length > 1) {
@@ -148,29 +149,36 @@ function swaggerTypeToTsType(schema) {
148
149
  return `${key}${optional}: ${type}`;
149
150
  })
150
151
  .join('; ')} }`;
151
- return `${refName}<${combinedType}>`;
152
+ baseType = `${refName}<${combinedType}>`;
152
153
  }
154
+ else {
155
+ baseType = refName || 'any';
156
+ }
157
+ }
158
+ else {
159
+ baseType = refName || 'any';
153
160
  }
154
- return refName || 'any';
155
161
  }
156
- // 如果不是引用,尝试合并所有类型
157
- const types = schema.allOf
158
- .map((s) => swaggerTypeToTsType(s))
159
- .filter((t) => t !== 'any');
160
- return types.length > 0 ? types[0] : 'any';
162
+ else {
163
+ // 如果不是引用,尝试合并所有类型
164
+ const types = schema.allOf
165
+ .map((s) => swaggerTypeToTsType(s))
166
+ .filter((t) => t !== 'any');
167
+ baseType = types.length > 0 ? types[0] : 'any';
168
+ }
161
169
  }
162
170
  // 处理引用类型
163
- if (schema.$ref) {
171
+ else if (schema.$ref) {
164
172
  const refName = schema.$ref.split('/').pop();
165
- return refName || 'any';
173
+ baseType = refName || 'any';
166
174
  }
167
175
  // 处理数组类型
168
- if (schema.type === 'array') {
176
+ else if (schema.type === 'array') {
169
177
  const itemType = swaggerTypeToTsType(schema.items);
170
- return `${itemType}[]`;
178
+ baseType = `${itemType}[]`;
171
179
  }
172
180
  // 处理对象类型
173
- if (schema.type === 'object') {
181
+ else if (schema.type === 'object') {
174
182
  if (schema.properties) {
175
183
  const properties = Object.entries(schema.properties)
176
184
  .map(([key, value]) => {
@@ -179,27 +187,43 @@ function swaggerTypeToTsType(schema) {
179
187
  return ` ${key}${optional}: ${type};`;
180
188
  })
181
189
  .join('\n');
182
- return `{\n${properties}\n}`;
190
+ baseType = `{\n${properties}\n}`;
191
+ }
192
+ else {
193
+ baseType = 'Record<string, any>';
183
194
  }
184
- return 'Record<string, any>';
185
195
  }
186
196
  // 处理基本类型
187
- switch (schema.type) {
188
- case 'integer':
189
- case 'number':
190
- return 'number';
191
- case 'string':
192
- if (schema.enum) {
193
- return schema.enum.map((value) => `'${value}'`).join(' | ');
194
- }
195
- return 'string';
196
- case 'boolean':
197
- return 'boolean';
198
- case 'file':
199
- return 'File';
200
- default:
201
- return 'any';
197
+ else {
198
+ switch (schema.type) {
199
+ case 'integer':
200
+ case 'number':
201
+ baseType = 'number';
202
+ break;
203
+ case 'string':
204
+ if (schema.enum) {
205
+ baseType = schema.enum.map((value) => `'${value}'`).join(' | ');
206
+ }
207
+ else {
208
+ baseType = 'string';
209
+ }
210
+ break;
211
+ case 'boolean':
212
+ baseType = 'boolean';
213
+ break;
214
+ case 'file':
215
+ baseType = 'File';
216
+ break;
217
+ default:
218
+ baseType = 'any';
219
+ break;
220
+ }
221
+ }
222
+ // 处理 nullable 属性
223
+ if (schema.nullable === true) {
224
+ return `${baseType} | null`;
202
225
  }
226
+ return baseType;
203
227
  }
204
228
  /**
205
229
  * 从Swagger参数生成TypeScript参数类型
@@ -315,11 +339,33 @@ function generateApiComment(operation, parameters) {
315
339
  comments.push(` * ${operation.description}`);
316
340
  }
317
341
  if (parameters && parameters.length > 0) {
318
- comments.push(' *');
319
- parameters.forEach((param) => {
320
- const description = param.description || '';
321
- comments.push(` * @param ${param.name} ${description}`);
322
- });
342
+ // 收集不同类型的参数
343
+ const queryParams = parameters.filter((p) => p.in === 'query');
344
+ const pathParams = parameters.filter((p) => p.in === 'path');
345
+ const bodyParams = parameters.filter((p) => p.in === 'body');
346
+ const formParams = parameters.filter((p) => p.in === 'formData');
347
+ const hasParams = queryParams.length > 0 || pathParams.length > 0;
348
+ const hasData = bodyParams.length > 0 || formParams.length > 0;
349
+ if (hasParams || hasData) {
350
+ comments.push(' *');
351
+ // 如果有查询参数或路径参数,添加params注释
352
+ if (hasParams) {
353
+ const paramDescriptions = [...pathParams, ...queryParams]
354
+ .map(p => p.description || '')
355
+ .filter(desc => desc)
356
+ .join(', ');
357
+ const description = paramDescriptions || '请求参数';
358
+ comments.push(` * @param params ${description}`);
359
+ }
360
+ // 如果有请求体参数,添加data注释
361
+ if (hasData) {
362
+ const dataParam = bodyParams[0] || formParams[0];
363
+ const description = dataParam?.description || '请求数据';
364
+ comments.push(` * @param data ${description}`);
365
+ }
366
+ // 添加config参数注释
367
+ comments.push(` * @param config 可选的请求配置`);
368
+ }
323
369
  }
324
370
  if (operation.deprecated) {
325
371
  comments.push(' * @deprecated');
package/package.json CHANGED
@@ -1,68 +1,68 @@
1
- {
2
- "name": "swagger2api-v3",
3
- "version": "1.0.7",
4
- "description": "从 Swagger/OpenAPI 文档生成 TypeScript API 接口的命令行工具",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
7
- "type": "commonjs",
8
- "bin": {
9
- "swagger2api-v3": "dist/cli/index.js"
10
- },
11
- "files": [
12
- "dist",
13
- "README.md",
14
- "package.json"
15
- ],
16
- "scripts": {
17
- "test": "jest",
18
- "test:watch": "jest --watch",
19
- "test:coverage": "jest --coverage",
20
- "test:ci": "jest --ci --coverage --watchAll=false",
21
- "build": "tsc",
22
- "clean": "rimraf dist",
23
- "prebuild": "npm run clean",
24
- "start": "node dist/cli/index.js",
25
- "dev": "npm run build && npm start",
26
- "lint": "prettier --write",
27
- "generate": "npm run build && node dist/cli/index.js generate",
28
- "init": "npm run build && node dist/cli/index.js init",
29
- "validate": "npm run build && node dist/cli/index.js validate",
30
- "swagger:generate": "npm run generate",
31
- "swagger:run": "npm run generate",
32
- "swagger:init": "npm run init",
33
- "swagger:validate": "npm run validate"
34
- },
35
- "keywords": [
36
- "swagger",
37
- "openapi",
38
- "typescript",
39
- "api",
40
- "generator",
41
- "cli",
42
- "code-generation"
43
- ],
44
- "author": "xiaoyang",
45
- "license": "MIT",
46
- "homepage": "https://github.com/xiaoyang33/swagger2api-v3#readme",
47
- "repository": {
48
- "type": "git",
49
- "url": "https://github.com/xiaoyang33/swagger2api-v3.git"
50
- },
51
- "bugs": {
52
- "url": "https://github.com/xiaoyang33/swagger2api-v3/issues"
53
- },
54
- "packageManager": "pnpm@10.11.0",
55
- "devDependencies": {
56
- "@types/jest": "^29.5.0",
57
- "@types/node": "^24.3.1",
58
- "jest": "^29.5.0",
59
- "prettier": "^3.6.2",
60
- "rimraf": "^6.0.1",
61
- "ts-jest": "^29.1.0",
62
- "typescript": "^5.9.2"
63
- },
64
- "dependencies": {
65
- "axios": "^1.11.0",
66
- "commander": "^12.0.0"
67
- }
68
- }
1
+ {
2
+ "name": "swagger2api-v3",
3
+ "version": "1.0.9",
4
+ "description": "从 Swagger(OAS3.0) 文档生成 TypeScript API 接口的命令行工具",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "type": "commonjs",
8
+ "bin": {
9
+ "swagger2api-v3": "dist/cli/index.js"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "README.md",
14
+ "package.json"
15
+ ],
16
+ "scripts": {
17
+ "test": "jest",
18
+ "test:watch": "jest --watch",
19
+ "test:coverage": "jest --coverage",
20
+ "test:ci": "jest --ci --coverage --watchAll=false",
21
+ "build": "tsc",
22
+ "clean": "rimraf dist",
23
+ "prebuild": "npm run clean",
24
+ "start": "node dist/cli/index.js",
25
+ "dev": "npm run build && npm start",
26
+ "lint": "prettier --write",
27
+ "generate": "npm run build && node dist/cli/index.js generate",
28
+ "init": "npm run build && node dist/cli/index.js init",
29
+ "validate": "npm run build && node dist/cli/index.js validate",
30
+ "swagger:generate": "npm run generate",
31
+ "swagger:run": "npm run generate",
32
+ "swagger:init": "npm run init",
33
+ "swagger:validate": "npm run validate"
34
+ },
35
+ "keywords": [
36
+ "swagger",
37
+ "openapi",
38
+ "typescript",
39
+ "api",
40
+ "generator",
41
+ "cli",
42
+ "code-generation"
43
+ ],
44
+ "author": "xiaoyang",
45
+ "license": "MIT",
46
+ "homepage": "https://github.com/xiaoyang33/swagger2api-v3#readme",
47
+ "repository": {
48
+ "type": "git",
49
+ "url": "https://github.com/xiaoyang33/swagger2api-v3.git"
50
+ },
51
+ "bugs": {
52
+ "url": "https://github.com/xiaoyang33/swagger2api-v3/issues"
53
+ },
54
+ "packageManager": "pnpm@10.11.0",
55
+ "devDependencies": {
56
+ "@types/jest": "^29.5.0",
57
+ "@types/node": "^24.3.1",
58
+ "jest": "^29.5.0",
59
+ "prettier": "^3.6.2",
60
+ "rimraf": "^6.0.1",
61
+ "ts-jest": "^29.1.0",
62
+ "typescript": "^5.9.2"
63
+ },
64
+ "dependencies": {
65
+ "axios": "^1.11.0",
66
+ "commander": "^12.0.0"
67
+ }
68
+ }