swagger2api-v3 1.1.3 → 1.1.5
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 +230 -243
- package/dist/cli/index.js +34 -72
- package/dist/core/parser.d.ts +5 -0
- package/dist/core/parser.js +17 -4
- package/dist/index.js +15 -10
- package/dist/utils/index.d.ts +2 -1
- package/dist/utils/index.js +10 -1
- package/package.json +68 -68
package/README.md
CHANGED
|
@@ -1,243 +1,230 @@
|
|
|
1
|
-
# Swagger2API-v3
|
|
2
|
-
|
|
3
|
-
English | [中文](./README_CN.md)
|
|
4
|
-
|
|
5
|
-
A powerful command-line tool for automatically generating TypeScript interface code from
|
|
6
|
-
|
|
7
|
-
## ✨ Features
|
|
8
|
-
|
|
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
|
|
17
|
-
|
|
18
|
-
```bash
|
|
19
|
-
# Global installation
|
|
20
|
-
npm install -g swagger2api-v3
|
|
21
|
-
|
|
22
|
-
# Project dependency
|
|
23
|
-
npm install swagger2api-v3
|
|
24
|
-
```
|
|
25
|
-
|
|
26
|
-
## 🚀 Quick Start
|
|
27
|
-
|
|
28
|
-
### 1. Initialize Configuration File
|
|
29
|
-
|
|
30
|
-
```bash
|
|
31
|
-
npx swagger2api-v3 init
|
|
32
|
-
```
|
|
33
|
-
|
|
34
|
-
### 2. Configuration File Description
|
|
35
|
-
|
|
36
|
-
The tool
|
|
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
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
###
|
|
135
|
-
|
|
136
|
-
```
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
const config = {
|
|
232
|
-
// ... other configurations
|
|
233
|
-
lint: 'prettier --write' // or 'eslint --fix', etc.
|
|
234
|
-
};
|
|
235
|
-
```
|
|
236
|
-
|
|
237
|
-
## 🤝 Contributing
|
|
238
|
-
|
|
239
|
-
Issues and Pull Requests are welcome!
|
|
240
|
-
|
|
241
|
-
## 📄 License
|
|
242
|
-
|
|
243
|
-
MIT License
|
|
1
|
+
# Swagger2API-v3
|
|
2
|
+
|
|
3
|
+
English | [中文](./README_CN.md)
|
|
4
|
+
|
|
5
|
+
A powerful command-line tool for automatically generating TypeScript or JavaScript interface code from OpenAPI 3.0 documentation.
|
|
6
|
+
|
|
7
|
+
## ✨ Features
|
|
8
|
+
|
|
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
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
# Global installation
|
|
20
|
+
npm install -g swagger2api-v3
|
|
21
|
+
|
|
22
|
+
# Project dependency
|
|
23
|
+
npm install swagger2api-v3
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## 🚀 Quick Start
|
|
27
|
+
|
|
28
|
+
### 1. Initialize Configuration File
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
npx swagger2api-v3 init
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### 2. Configuration File Description
|
|
35
|
+
|
|
36
|
+
The tool generates a `.swagger.config.json` configuration file:
|
|
37
|
+
|
|
38
|
+
```json
|
|
39
|
+
{
|
|
40
|
+
"input": "https://petstore.swagger.io/v2/swagger.json",
|
|
41
|
+
"output": "./src/api",
|
|
42
|
+
"importTemplate": "import { request } from '@/utils/request';",
|
|
43
|
+
"generator": "typescript",
|
|
44
|
+
"requestStyle": "generic",
|
|
45
|
+
"groupByTags": true,
|
|
46
|
+
"overwrite": true,
|
|
47
|
+
"prefix": "",
|
|
48
|
+
"lint": "prettier --write",
|
|
49
|
+
"methodNameIgnorePrefix": [],
|
|
50
|
+
"addMethodSuffix": true,
|
|
51
|
+
"options": {
|
|
52
|
+
"addComments": true
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### 3. Generate Interface Code
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
npx swagger2api-v3 generate
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## ⚙️ Configuration Options
|
|
64
|
+
|
|
65
|
+
| Option | Type | Default | Description |
|
|
66
|
+
| ------------------------ | --------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
67
|
+
| `input` | string | - | Swagger JSON file path or URL |
|
|
68
|
+
| `output` | string | `'./src/api'` | Output directory for generated code |
|
|
69
|
+
| `generator` | string | `'typescript'` | Code generator type. Supports `'typescript'` and `'javascript'`. `'javascript'` outputs `.js` files and skips type file generation |
|
|
70
|
+
| `groupByTags` | boolean | `true` | Whether to group files by tags |
|
|
71
|
+
| `overwrite` | boolean | `true` | Whether to overwrite existing files |
|
|
72
|
+
| `prefix` | string | `''` | Common prefix for API paths |
|
|
73
|
+
| `importTemplate` | string | - | Import statement template for request function |
|
|
74
|
+
| `requestStyle` | 'method' \| 'generic' | `'generic'` | Request call style: `method` uses `request.get/post`, `generic` uses `request({ method })` |
|
|
75
|
+
| `lint` | string | - | Code formatting command (optional) |
|
|
76
|
+
| `methodNameIgnorePrefix` | string[] | `[]` | Array of prefixes to ignore when generating method names. For example, `['api', 'auth']` will transform `apiGetName` to `getName` and `authUserInfo` to `userInfo` |
|
|
77
|
+
| `addMethodSuffix` | boolean | `true` | Whether to add HTTP method suffix to generated function names. `true` generates `userListPost`, `false` generates `userList` |
|
|
78
|
+
| `options.addComments` | boolean | `true` | Whether to add detailed comments |
|
|
79
|
+
|
|
80
|
+
## 📁 Generated File Structure
|
|
81
|
+
|
|
82
|
+
### Grouped by Tags (Recommended)
|
|
83
|
+
|
|
84
|
+
```
|
|
85
|
+
src/api/
|
|
86
|
+
├── types.ts # Data type definitions (TypeScript mode only)
|
|
87
|
+
├── user/ # User-related APIs
|
|
88
|
+
│ └── index.ts
|
|
89
|
+
├── auth/ # Auth-related APIs
|
|
90
|
+
│ └── index.ts
|
|
91
|
+
└── index.ts # Entry file
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### JavaScript Output
|
|
95
|
+
|
|
96
|
+
When `generator: 'javascript'` is set:
|
|
97
|
+
|
|
98
|
+
- Outputs `.js` files (`index.js`, `api.js`, `user/index.js`, etc.)
|
|
99
|
+
- Does not generate a `types.ts` file
|
|
100
|
+
- Removes TypeScript-specific syntax (types, `import type`, generics like `<T>`)
|
|
101
|
+
|
|
102
|
+
Example generated API function (method style):
|
|
103
|
+
|
|
104
|
+
```javascript
|
|
105
|
+
export const codeAuth = (data, config) => {
|
|
106
|
+
return request.post({ url: '/api/auth/codeAuth', data, ...config });
|
|
107
|
+
};
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Example generated API function (generic style):
|
|
111
|
+
|
|
112
|
+
```javascript
|
|
113
|
+
export const codeAuth = (data, config) => {
|
|
114
|
+
return request({
|
|
115
|
+
url: '/api/auth/codeAuth',
|
|
116
|
+
method: 'POST',
|
|
117
|
+
data,
|
|
118
|
+
...config
|
|
119
|
+
});
|
|
120
|
+
};
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### Not Grouped
|
|
124
|
+
|
|
125
|
+
```
|
|
126
|
+
src/api/
|
|
127
|
+
├── types.ts # Data type definitions
|
|
128
|
+
├── api.ts # All API interfaces
|
|
129
|
+
└── index.ts # Entry file
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
## 💡 Usage Examples
|
|
133
|
+
|
|
134
|
+
### Generated Type Definitions
|
|
135
|
+
|
|
136
|
+
```typescript
|
|
137
|
+
// types.ts
|
|
138
|
+
export interface LoginDto {
|
|
139
|
+
/** Account */
|
|
140
|
+
account: string;
|
|
141
|
+
/** Password */
|
|
142
|
+
password: string;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export interface UserInfo {
|
|
146
|
+
/** User ID */
|
|
147
|
+
id: string;
|
|
148
|
+
/** Username */
|
|
149
|
+
username: string;
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### Generated API Interfaces
|
|
154
|
+
|
|
155
|
+
```typescript
|
|
156
|
+
// authController/index.ts
|
|
157
|
+
import { request } from '@/utils/request';
|
|
158
|
+
import type { LoginDto, LoginRespDto } from '../types';
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Login
|
|
162
|
+
* @param data Login parameters
|
|
163
|
+
* @param config Optional request configuration
|
|
164
|
+
*/
|
|
165
|
+
export const authControllerLoginPost = (data: LoginDto, config?: any) => {
|
|
166
|
+
return request.post<LoginRespDto>({
|
|
167
|
+
url: '/admin/auth/login',
|
|
168
|
+
data,
|
|
169
|
+
...config
|
|
170
|
+
});
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
// When requestStyle is set to 'generic':
|
|
174
|
+
export const authControllerLoginPost2 = (data: LoginDto, config?: any) => {
|
|
175
|
+
return request<LoginRespDto>({
|
|
176
|
+
url: '/admin/auth/login',
|
|
177
|
+
data,
|
|
178
|
+
method: 'POST',
|
|
179
|
+
...config
|
|
180
|
+
});
|
|
181
|
+
};
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
## 🔧 CLI Commands
|
|
185
|
+
|
|
186
|
+
```bash
|
|
187
|
+
# Initialize configuration file
|
|
188
|
+
npx swagger2api-v3 init [--force]
|
|
189
|
+
|
|
190
|
+
# Generate interface code
|
|
191
|
+
npx swagger2api-v3 generate [--config <path>]
|
|
192
|
+
|
|
193
|
+
# Validate configuration file
|
|
194
|
+
npx swagger2api-v3 validate [--config <path>]
|
|
195
|
+
|
|
196
|
+
# Show help
|
|
197
|
+
npx swagger2api-v3 --help
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
## 📝 NPM Scripts
|
|
201
|
+
|
|
202
|
+
Add to `package.json`:
|
|
203
|
+
|
|
204
|
+
```json
|
|
205
|
+
{
|
|
206
|
+
"scripts": {
|
|
207
|
+
"api:generate": "swagger2api-v3 generate",
|
|
208
|
+
"api:init": "swagger2api-v3 init",
|
|
209
|
+
"api:validate": "swagger2api-v3 validate"
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
## 🎨 Code Formatting
|
|
215
|
+
|
|
216
|
+
Support automatic execution of formatting commands after generation:
|
|
217
|
+
|
|
218
|
+
```json
|
|
219
|
+
{
|
|
220
|
+
"lint": "prettier --write"
|
|
221
|
+
}
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
## 🤝 Contributing
|
|
225
|
+
|
|
226
|
+
If you encounter any problems or have suggestions, please feel free to [submit an issue](https://github.com/xiaoyang33/swagger2api-v3/issues) on GitHub. Pull Requests are also welcome!
|
|
227
|
+
|
|
228
|
+
## 📄 License
|
|
229
|
+
|
|
230
|
+
MIT License
|
package/dist/cli/index.js
CHANGED
|
@@ -50,7 +50,7 @@ program
|
|
|
50
50
|
.command('generate')
|
|
51
51
|
.alias('gen')
|
|
52
52
|
.description('根据配置文件生成 API 接口')
|
|
53
|
-
.option('-c, --config <path>', '配置文件路径', '.swagger.config.
|
|
53
|
+
.option('-c, --config <path>', '配置文件路径', '.swagger.config.json')
|
|
54
54
|
.option('-i, --input <path>', 'Swagger JSON 文件路径或 URL')
|
|
55
55
|
.option('-o, --output <path>', '输出目录')
|
|
56
56
|
.option('--no-types', '不生成类型文件')
|
|
@@ -92,79 +92,31 @@ program
|
|
|
92
92
|
.description('初始化配置文件')
|
|
93
93
|
.option('-f, --force', '强制覆盖已存在的配置文件')
|
|
94
94
|
.action(async (options) => {
|
|
95
|
-
const configPath = path.resolve(process.cwd(), '.swagger.config.
|
|
95
|
+
const configPath = path.resolve(process.cwd(), '.swagger.config.json');
|
|
96
96
|
if (fs.existsSync(configPath) && !options.force) {
|
|
97
97
|
console.error('❌ 配置文件已存在,使用 --force 参数强制覆盖');
|
|
98
98
|
process.exit(1);
|
|
99
99
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
100
|
+
const config = {
|
|
101
|
+
input: 'http://localhost:3000/admin/docs/json',
|
|
102
|
+
output: './src/api',
|
|
103
|
+
importTemplate: "import { request } from '@/utils/request';",
|
|
104
|
+
generator: 'typescript',
|
|
105
|
+
requestStyle: 'generic',
|
|
106
|
+
groupByTags: true,
|
|
107
|
+
overwrite: true,
|
|
108
|
+
prefix: '',
|
|
109
|
+
lint: 'prettier --write',
|
|
110
|
+
methodNameIgnorePrefix: [],
|
|
111
|
+
addMethodSuffix: true,
|
|
112
|
+
options: {
|
|
113
|
+
addComments: true
|
|
108
114
|
}
|
|
109
|
-
|
|
110
|
-
console.warn('⚠️ 无法读取package.json,使用默认ES Module格式');
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
const configContent = `/**
|
|
114
|
-
* Swagger2API 配置文件
|
|
115
|
-
* 用于配置从 Swagger JSON 生成前端接口的参数
|
|
116
|
-
*/
|
|
117
|
-
const config = {
|
|
118
|
-
// Swagger JSON 文件路径或 URL
|
|
119
|
-
input: 'http://localhost:3000/admin/docs/json',
|
|
120
|
-
|
|
121
|
-
// 输出目录
|
|
122
|
-
output: './src/api',
|
|
123
|
-
|
|
124
|
-
// request 导入路径模板
|
|
125
|
-
importTemplate: "import { request } from '@/utils/request';",
|
|
126
|
-
|
|
127
|
-
// 生成器类型
|
|
128
|
-
generator: 'typescript', // 可选 'javascript'(JS 模式输出 .js 文件且不生成类型文件)
|
|
129
|
-
|
|
130
|
-
// 请求调用风格:'method' 使用 request.get/post;'generic' 使用 request({ method })
|
|
131
|
-
requestStyle: 'generic',
|
|
132
|
-
|
|
133
|
-
// 按标签分组生成文件
|
|
134
|
-
groupByTags: true,
|
|
135
|
-
|
|
136
|
-
// 是否覆盖更新,默认为true。为true时会先删除输出目录下的所有文件
|
|
137
|
-
overwrite: true,
|
|
138
|
-
|
|
139
|
-
// 接口路径公共前缀,默认为空字符串
|
|
140
|
-
prefix: '',
|
|
141
|
-
|
|
142
|
-
// 代码格式化命令(可选)
|
|
143
|
-
lint: 'prettier --write',
|
|
144
|
-
|
|
145
|
-
// 生成方法名时需要忽略的前缀(可选)
|
|
146
|
-
// 例如:配置 ['api', 'auth'] 后,apiGetName 会变成 getName,authUserInfo 会变成 userInfo
|
|
147
|
-
// 如果方法名是 apiAuthGetName,会依次移除所有匹配的前缀,最终变成 getName
|
|
148
|
-
methodNameIgnorePrefix: [],
|
|
149
|
-
|
|
150
|
-
// 是否在生成的方法名中添加 HTTP method 后缀,默认为 true
|
|
151
|
-
// true: userListPost, userDetailGet
|
|
152
|
-
// false: userList, userDetail
|
|
153
|
-
addMethodSuffix: true,
|
|
154
|
-
|
|
155
|
-
// 生成选项
|
|
156
|
-
options: {
|
|
157
|
-
// 是否添加注释
|
|
158
|
-
addComments: true
|
|
159
|
-
}
|
|
160
|
-
};
|
|
161
|
-
|
|
162
|
-
${isESModule ? 'export default config;' : 'module.exports = config;'}
|
|
163
|
-
`;
|
|
115
|
+
};
|
|
164
116
|
try {
|
|
165
|
-
fs.writeFileSync(configPath,
|
|
117
|
+
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
|
|
166
118
|
console.log('✅ 配置文件已创建:', configPath);
|
|
167
|
-
console.log('💡 请根据需要修改配置文件,然后运行 swagger2api generate');
|
|
119
|
+
console.log('💡 请根据需要修改配置文件,然后运行 swagger2api-v3 generate');
|
|
168
120
|
}
|
|
169
121
|
catch (error) {
|
|
170
122
|
console.error('❌ 创建配置文件失败:', error);
|
|
@@ -175,12 +127,16 @@ ${isESModule ? 'export default config;' : 'module.exports = config;'}
|
|
|
175
127
|
program
|
|
176
128
|
.command('validate')
|
|
177
129
|
.description('验证配置文件')
|
|
178
|
-
.option('-c, --config <path>', '配置文件路径', '.swagger.config.
|
|
130
|
+
.option('-c, --config <path>', '配置文件路径', '.swagger.config.json')
|
|
179
131
|
.action(async (options) => {
|
|
180
132
|
const configPath = path.resolve(process.cwd(), options.config);
|
|
181
133
|
try {
|
|
182
|
-
|
|
183
|
-
|
|
134
|
+
if (!fs.existsSync(configPath)) {
|
|
135
|
+
console.error(`❌ 找不到配置文件: ${configPath}`);
|
|
136
|
+
process.exit(1);
|
|
137
|
+
}
|
|
138
|
+
const configContent = fs.readFileSync(configPath, 'utf-8');
|
|
139
|
+
const config = JSON.parse(configContent);
|
|
184
140
|
const { Swagger2API } = await Promise.resolve().then(() => __importStar(require('../index')));
|
|
185
141
|
const swagger2api = new Swagger2API(config);
|
|
186
142
|
if (swagger2api.validateConfig()) {
|
|
@@ -200,7 +156,13 @@ program
|
|
|
200
156
|
}
|
|
201
157
|
}
|
|
202
158
|
catch (error) {
|
|
203
|
-
|
|
159
|
+
if (error instanceof SyntaxError) {
|
|
160
|
+
console.error(`❌ 配置文件 JSON 格式错误: ${configPath}`);
|
|
161
|
+
console.error('错误详情:', error.message);
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
console.error('❌ 配置文件验证失败:', error);
|
|
165
|
+
}
|
|
204
166
|
process.exit(1);
|
|
205
167
|
}
|
|
206
168
|
});
|
|
@@ -208,7 +170,7 @@ program
|
|
|
208
170
|
program
|
|
209
171
|
.command('run')
|
|
210
172
|
.description('运行生成器(generate 命令的别名)')
|
|
211
|
-
.option('-c, --config <path>', '配置文件路径', '.swagger.config.
|
|
173
|
+
.option('-c, --config <path>', '配置文件路径', '.swagger.config.json')
|
|
212
174
|
.action(async (options) => {
|
|
213
175
|
try {
|
|
214
176
|
await (0, index_1.generateFromConfig)(options.config);
|
package/dist/core/parser.d.ts
CHANGED
|
@@ -6,6 +6,11 @@ export declare class SwaggerParser {
|
|
|
6
6
|
private document;
|
|
7
7
|
private config;
|
|
8
8
|
constructor(document: SwaggerDocument, config: SwaggerConfig);
|
|
9
|
+
/**
|
|
10
|
+
* 获取所有 schemas (包括 definitions 和 components.schemas)
|
|
11
|
+
* @returns schemas 对象
|
|
12
|
+
*/
|
|
13
|
+
private getAllSchemas;
|
|
9
14
|
/**
|
|
10
15
|
* 解析所有API接口
|
|
11
16
|
* @returns API接口信息数组
|
package/dist/core/parser.js
CHANGED
|
@@ -10,6 +10,16 @@ class SwaggerParser {
|
|
|
10
10
|
this.document = document;
|
|
11
11
|
this.config = config;
|
|
12
12
|
}
|
|
13
|
+
/**
|
|
14
|
+
* 获取所有 schemas (包括 definitions 和 components.schemas)
|
|
15
|
+
* @returns schemas 对象
|
|
16
|
+
*/
|
|
17
|
+
getAllSchemas() {
|
|
18
|
+
return {
|
|
19
|
+
...(this.document.definitions || {}),
|
|
20
|
+
...(this.document.components?.schemas || {})
|
|
21
|
+
};
|
|
22
|
+
}
|
|
13
23
|
/**
|
|
14
24
|
* 解析所有API接口
|
|
15
25
|
* @returns API接口信息数组
|
|
@@ -163,12 +173,14 @@ class SwaggerParser {
|
|
|
163
173
|
parseTypeDefinition(name, schema) {
|
|
164
174
|
const typeName = (0, utils_1.toPascalCase)(name);
|
|
165
175
|
let definition;
|
|
176
|
+
// 获取所有 schemas 用于类型解析
|
|
177
|
+
const allSchemas = this.getAllSchemas();
|
|
166
178
|
if (schema.type === 'object' && schema.properties) {
|
|
167
179
|
// 对象类型
|
|
168
180
|
const properties = Object.entries(schema.properties)
|
|
169
181
|
.map(([key, value]) => {
|
|
170
182
|
const optional = schema.required?.includes(key) ? '' : '?';
|
|
171
|
-
const type = (0, utils_1.swaggerTypeToTsType)(value);
|
|
183
|
+
const type = (0, utils_1.swaggerTypeToTsType)(value, allSchemas);
|
|
172
184
|
const comment = value.description
|
|
173
185
|
? ` /** ${value.description} */`
|
|
174
186
|
: '';
|
|
@@ -178,9 +190,10 @@ class SwaggerParser {
|
|
|
178
190
|
definition = `export interface ${typeName} {\n${properties}\n}`;
|
|
179
191
|
}
|
|
180
192
|
else if (schema.type === 'array') {
|
|
181
|
-
// 数组类型
|
|
182
|
-
|
|
183
|
-
|
|
193
|
+
// 数组类型 - 生成指向 items 类型的别名(不带 [])
|
|
194
|
+
// 在引用时会自动添加 []
|
|
195
|
+
const itemType = (0, utils_1.swaggerTypeToTsType)(schema.items, allSchemas);
|
|
196
|
+
definition = `export type ${typeName} = ${itemType};`;
|
|
184
197
|
}
|
|
185
198
|
else if (schema.enum) {
|
|
186
199
|
// 枚举类型
|
package/dist/index.js
CHANGED
|
@@ -40,6 +40,7 @@ exports.CodeGenerator = exports.SwaggerParser = exports.Swagger2API = void 0;
|
|
|
40
40
|
exports.generateFromConfig = generateFromConfig;
|
|
41
41
|
exports.generate = generate;
|
|
42
42
|
const path = __importStar(require("path"));
|
|
43
|
+
const fs = __importStar(require("fs"));
|
|
43
44
|
const parser_1 = require("./core/parser");
|
|
44
45
|
const generator_1 = require("./core/generator");
|
|
45
46
|
const utils_1 = require("./utils");
|
|
@@ -119,15 +120,19 @@ exports.Swagger2API = Swagger2API;
|
|
|
119
120
|
* @param configPath 配置文件路径
|
|
120
121
|
*/
|
|
121
122
|
async function generateFromConfig(configPath) {
|
|
122
|
-
const configFile = configPath || '.swagger.config.
|
|
123
|
+
const configFile = configPath || '.swagger.config.json';
|
|
123
124
|
const fullPath = path.resolve(process.cwd(), configFile);
|
|
124
125
|
try {
|
|
125
126
|
let config;
|
|
126
|
-
//
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
127
|
+
// 读取并解析 JSON 配置文件
|
|
128
|
+
if (!fs.existsSync(fullPath)) {
|
|
129
|
+
console.error(`❌ 找不到配置文件: ${fullPath}`);
|
|
130
|
+
console.error('请确保配置文件存在并且路径正确');
|
|
131
|
+
console.error('提示: 运行 swagger2api-v3 init 来创建配置文件');
|
|
132
|
+
process.exit(1);
|
|
133
|
+
}
|
|
134
|
+
const configContent = fs.readFileSync(fullPath, 'utf-8');
|
|
135
|
+
config = JSON.parse(configContent);
|
|
131
136
|
const swagger2api = new Swagger2API(config);
|
|
132
137
|
if (!swagger2api.validateConfig()) {
|
|
133
138
|
process.exit(1);
|
|
@@ -135,10 +140,10 @@ async function generateFromConfig(configPath) {
|
|
|
135
140
|
await swagger2api.generate();
|
|
136
141
|
}
|
|
137
142
|
catch (error) {
|
|
138
|
-
if (error instanceof
|
|
139
|
-
error
|
|
140
|
-
console.error(
|
|
141
|
-
console.error('
|
|
143
|
+
if (error instanceof SyntaxError) {
|
|
144
|
+
console.error(`❌ 配置文件 JSON 格式错误: ${fullPath}`);
|
|
145
|
+
console.error('请检查 JSON 语法是否正确');
|
|
146
|
+
console.error('错误详情:', error.message);
|
|
142
147
|
}
|
|
143
148
|
else {
|
|
144
149
|
console.error('❌ 加载配置文件失败:', error);
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -44,9 +44,10 @@ export declare function removeMethodSuffix(functionName: string, method: string)
|
|
|
44
44
|
/**
|
|
45
45
|
* 将Swagger类型转换为TypeScript类型
|
|
46
46
|
* @param schema Swagger模式
|
|
47
|
+
* @param schemas 可选的 schemas 上下文,用于查找被引用的类型定义
|
|
47
48
|
* @returns TypeScript类型字符串
|
|
48
49
|
*/
|
|
49
|
-
export declare function swaggerTypeToTsType(schema: any): string;
|
|
50
|
+
export declare function swaggerTypeToTsType(schema: any, schemas?: any): string;
|
|
50
51
|
/**
|
|
51
52
|
* 从Swagger参数生成TypeScript参数类型
|
|
52
53
|
* @param parameters Swagger参数数组
|
package/dist/utils/index.js
CHANGED
|
@@ -168,9 +168,10 @@ function removeMethodSuffix(functionName, method) {
|
|
|
168
168
|
/**
|
|
169
169
|
* 将Swagger类型转换为TypeScript类型
|
|
170
170
|
* @param schema Swagger模式
|
|
171
|
+
* @param schemas 可选的 schemas 上下文,用于查找被引用的类型定义
|
|
171
172
|
* @returns TypeScript类型字符串
|
|
172
173
|
*/
|
|
173
|
-
function swaggerTypeToTsType(schema) {
|
|
174
|
+
function swaggerTypeToTsType(schema, schemas) {
|
|
174
175
|
if (!schema)
|
|
175
176
|
return 'any';
|
|
176
177
|
let baseType = 'any';
|
|
@@ -246,6 +247,14 @@ function swaggerTypeToTsType(schema) {
|
|
|
246
247
|
else if (schema.$ref) {
|
|
247
248
|
const refName = schema.$ref.split('/').pop();
|
|
248
249
|
baseType = sanitizeTypeName(refName || 'any');
|
|
250
|
+
// 如果提供了 schemas 上下文,检查被引用的 schema 是否是数组类型
|
|
251
|
+
if (schemas && refName) {
|
|
252
|
+
const referencedSchema = schemas[refName];
|
|
253
|
+
if (referencedSchema && referencedSchema.type === 'array') {
|
|
254
|
+
// 被引用的 schema 是数组类型,添加 []
|
|
255
|
+
baseType = `${baseType}[]`;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
249
258
|
}
|
|
250
259
|
// 处理数组类型
|
|
251
260
|
else if (schema.type === 'array') {
|
package/package.json
CHANGED
|
@@ -1,68 +1,68 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "swagger2api-v3",
|
|
3
|
-
"version": "1.1.
|
|
4
|
-
"description": "A command-line tool for generating TypeScript API interfaces from Swagger (OAS 3.0) documentation",
|
|
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.1.5",
|
|
4
|
+
"description": "A command-line tool for generating TypeScript API interfaces from Swagger (OAS 3.0) documentation",
|
|
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
|
+
}
|