swagger2api-v3 1.1.0 → 1.1.2

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,234 +1,235 @@
1
- # Swagger2API-v3
2
-
3
- English | [中文](./README_CN.md)
4
-
5
- A powerful command-line tool for automatically generating TypeScript interface code from Swagger (OAS3.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 automatically generates configuration files in the corresponding format based on the project environment:
37
-
38
- **CommonJS Environment** (`"type": "commonjs"` or not set):
39
- ```javascript
40
- const config = {
41
- input: 'https://petstore.swagger.io/v2/swagger.json',
42
- output: './src/api',
43
- importTemplate: "import { request } from '@/utils/request';",
44
- generator: 'typescript',
45
- groupByTags: true,
46
- overwrite: true,
47
- prefix: '',
48
- lint: 'prettier --write',
49
- options: {
50
- addComments: true
51
- }
52
- };
53
-
54
- module.exports = config;
55
- ```
56
-
57
- **ES Module Environment** (`"type": "module"`):
58
- ```javascript
59
- const config = {
60
- // ... same configuration
61
- };
62
-
63
- export default config;
64
- ```
65
-
66
- ### 3. Generate Interface Code
67
-
68
- ```bash
69
- npx swagger2api-v3 generate
70
- ```
71
-
72
- ## ⚙️ Configuration Options
73
-
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. Supports `'typescript'` and `'javascript'`. `'javascript'` outputs `.js` files and skips type file generation |
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
- | `requestStyle` | 'method' \| 'generic' | `'generic'` | Request call style: `method` uses `request.get/post`, `generic` uses `request({ method })` |
84
- | `lint` | string | - | Code formatting command (optional) |
85
- | `options.addComments` | boolean | `true` | Whether to add detailed comments |
86
-
87
- ## 📁 Generated File Structure
88
-
89
- ### Grouped by Tags (Recommended)
90
-
91
- ```
92
- src/api/
93
- ├── types.ts # Data type definitions (TypeScript mode only)
94
- ├── user/ # User-related APIs
95
- │ └── index.ts
96
- ├── auth/ # Auth-related APIs
97
- │ └── index.ts
98
- └── index.ts # Entry file
99
- ```
100
-
101
- ### JavaScript Output
102
-
103
- When `generator: 'javascript'` is set:
104
-
105
- - Outputs `.js` files (`index.js`, `api.js`, `user/index.js`, etc.)
106
- - Does not generate a `types.ts` file
107
- - Removes TypeScript-specific syntax (types, `import type`, generics like `<T>`)
108
-
109
- Example generated API function (method style):
110
-
111
- ```javascript
112
- export const codeAuth = (data, config) => {
113
- return request.post({ url: '/api/auth/codeAuth', data, ...config });
114
- };
115
- ```
116
-
117
- Example generated API function (generic style):
118
-
119
- ```javascript
120
- export const codeAuth = (data, config) => {
121
- return request({ url: '/api/auth/codeAuth', method: 'POST', data, ...config });
122
- };
123
- ```
124
-
125
- ### Not Grouped
126
-
127
- ```
128
- src/api/
129
- ├── types.ts # Data type definitions
130
- ├── api.ts # All API interfaces
131
- └── index.ts # Entry file
132
- ```
133
-
134
- ## 💡 Usage Examples
135
-
136
- ### Generated Type Definitions
137
-
138
- ```typescript
139
- // types.ts
140
- export interface LoginDto {
141
- /** Account */
142
- account: string;
143
- /** Password */
144
- password: string;
145
- }
146
-
147
- export interface UserInfo {
148
- /** User ID */
149
- id: string;
150
- /** Username */
151
- username: string;
152
- }
153
- ```
154
-
155
- ### Generated API Interfaces
156
-
157
- ```typescript
158
- // authController/index.ts
159
- import { request } from '@/utils/request';
160
- import type { LoginDto, LoginRespDto } from '../types';
161
-
162
- /**
163
- * Login
164
- * @param data Login parameters
165
- * @param config Optional request configuration
166
- */
167
- export const authControllerLoginPost = (data: LoginDto, config?: any) => {
168
- return request.post<LoginRespDto>({
169
- url: '/admin/auth/login',
170
- data,
171
- ...config
172
- });
173
- };
174
-
175
- // When requestStyle is set to 'generic':
176
- export const authControllerLoginPost2 = (data: LoginDto, config?: any) => {
177
- return request<LoginRespDto>({
178
- url: '/admin/auth/login',
179
- data,
180
- method: 'POST',
181
- ...config
182
- });
183
- };
184
- ```
185
-
186
- ## 🔧 CLI Commands
187
-
188
- ```bash
189
- # Initialize configuration file
190
- npx swagger2api-v3 init [--force]
191
-
192
- # Generate interface code
193
- npx swagger2api-v3 generate [--config <path>]
194
-
195
- # Validate configuration file
196
- npx swagger2api-v3 validate [--config <path>]
197
-
198
- # Show help
199
- npx swagger2api-v3 --help
200
- ```
201
-
202
- ## 📝 NPM Scripts
203
-
204
- Add to `package.json`:
205
-
206
- ```json
207
- {
208
- "scripts": {
209
- "api:generate": "swagger2api-v3 generate",
210
- "api:init": "swagger2api-v3 init",
211
- "api:validate": "swagger2api-v3 validate"
212
- }
213
- }
214
- ```
215
-
216
- ## 🎨 Code Formatting
217
-
218
- Support automatic execution of formatting commands after generation:
219
-
220
- ```javascript
221
- // In configuration file
222
- const config = {
223
- // ... other configurations
224
- lint: 'prettier --write' // or 'eslint --fix', etc.
225
- };
226
- ```
227
-
228
- ## 🤝 Contributing
229
-
230
- Issues and Pull Requests are welcome!
231
-
232
- ## 📄 License
233
-
1
+ # Swagger2API-v3
2
+
3
+ English | [中文](./README_CN.md)
4
+
5
+ A powerful command-line tool for automatically generating TypeScript interface code from Swagger (OAS3.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 automatically generates configuration files in the corresponding format based on the project environment:
37
+
38
+ **CommonJS Environment** (`"type": "commonjs"` or not set):
39
+ ```javascript
40
+ const config = {
41
+ input: 'https://petstore.swagger.io/v2/swagger.json',
42
+ output: './src/api',
43
+ importTemplate: "import { request } from '@/utils/request';",
44
+ generator: 'typescript',
45
+ groupByTags: true,
46
+ overwrite: true,
47
+ prefix: '',
48
+ lint: 'prettier --write',
49
+ options: {
50
+ addComments: true
51
+ }
52
+ };
53
+
54
+ module.exports = config;
55
+ ```
56
+
57
+ **ES Module Environment** (`"type": "module"`):
58
+ ```javascript
59
+ const config = {
60
+ // ... same configuration
61
+ };
62
+
63
+ export default config;
64
+ ```
65
+
66
+ ### 3. Generate Interface Code
67
+
68
+ ```bash
69
+ npx swagger2api-v3 generate
70
+ ```
71
+
72
+ ## ⚙️ Configuration Options
73
+
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. Supports `'typescript'` and `'javascript'`. `'javascript'` outputs `.js` files and skips type file generation |
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
+ | `requestStyle` | 'method' \| 'generic' | `'generic'` | Request call style: `method` uses `request.get/post`, `generic` uses `request({ method })` |
84
+ | `lint` | string | - | Code formatting command (optional) |
85
+ | `methodNameIgnorePrefix` | string[] | `[]` | Array of prefixes to ignore when generating method names. For example, `['api', 'auth']` will transform `apiGetName` to `getName` and `authUserInfo` to `userInfo` |
86
+ | `options.addComments` | boolean | `true` | Whether to add detailed comments |
87
+
88
+ ## 📁 Generated File Structure
89
+
90
+ ### Grouped by Tags (Recommended)
91
+
92
+ ```
93
+ src/api/
94
+ ├── types.ts # Data type definitions (TypeScript mode only)
95
+ ├── user/ # User-related APIs
96
+ │ └── index.ts
97
+ ├── auth/ # Auth-related APIs
98
+ └── index.ts
99
+ └── index.ts # Entry file
100
+ ```
101
+
102
+ ### JavaScript Output
103
+
104
+ When `generator: 'javascript'` is set:
105
+
106
+ - Outputs `.js` files (`index.js`, `api.js`, `user/index.js`, etc.)
107
+ - Does not generate a `types.ts` file
108
+ - Removes TypeScript-specific syntax (types, `import type`, generics like `<T>`)
109
+
110
+ Example generated API function (method style):
111
+
112
+ ```javascript
113
+ export const codeAuth = (data, config) => {
114
+ return request.post({ url: '/api/auth/codeAuth', data, ...config });
115
+ };
116
+ ```
117
+
118
+ Example generated API function (generic style):
119
+
120
+ ```javascript
121
+ export const codeAuth = (data, config) => {
122
+ return request({ url: '/api/auth/codeAuth', method: 'POST', data, ...config });
123
+ };
124
+ ```
125
+
126
+ ### Not Grouped
127
+
128
+ ```
129
+ src/api/
130
+ ├── types.ts # Data type definitions
131
+ ├── api.ts # All API interfaces
132
+ └── index.ts # Entry file
133
+ ```
134
+
135
+ ## 💡 Usage Examples
136
+
137
+ ### Generated Type Definitions
138
+
139
+ ```typescript
140
+ // types.ts
141
+ export interface LoginDto {
142
+ /** Account */
143
+ account: string;
144
+ /** Password */
145
+ password: string;
146
+ }
147
+
148
+ export interface UserInfo {
149
+ /** User ID */
150
+ id: string;
151
+ /** Username */
152
+ username: string;
153
+ }
154
+ ```
155
+
156
+ ### Generated API Interfaces
157
+
158
+ ```typescript
159
+ // authController/index.ts
160
+ import { request } from '@/utils/request';
161
+ import type { LoginDto, LoginRespDto } from '../types';
162
+
163
+ /**
164
+ * Login
165
+ * @param data Login parameters
166
+ * @param config Optional request configuration
167
+ */
168
+ export const authControllerLoginPost = (data: LoginDto, config?: any) => {
169
+ return request.post<LoginRespDto>({
170
+ url: '/admin/auth/login',
171
+ data,
172
+ ...config
173
+ });
174
+ };
175
+
176
+ // When requestStyle is set to 'generic':
177
+ export const authControllerLoginPost2 = (data: LoginDto, config?: any) => {
178
+ return request<LoginRespDto>({
179
+ url: '/admin/auth/login',
180
+ data,
181
+ method: 'POST',
182
+ ...config
183
+ });
184
+ };
185
+ ```
186
+
187
+ ## 🔧 CLI Commands
188
+
189
+ ```bash
190
+ # Initialize configuration file
191
+ npx swagger2api-v3 init [--force]
192
+
193
+ # Generate interface code
194
+ npx swagger2api-v3 generate [--config <path>]
195
+
196
+ # Validate configuration file
197
+ npx swagger2api-v3 validate [--config <path>]
198
+
199
+ # Show help
200
+ npx swagger2api-v3 --help
201
+ ```
202
+
203
+ ## 📝 NPM Scripts
204
+
205
+ Add to `package.json`:
206
+
207
+ ```json
208
+ {
209
+ "scripts": {
210
+ "api:generate": "swagger2api-v3 generate",
211
+ "api:init": "swagger2api-v3 init",
212
+ "api:validate": "swagger2api-v3 validate"
213
+ }
214
+ }
215
+ ```
216
+
217
+ ## 🎨 Code Formatting
218
+
219
+ Support automatic execution of formatting commands after generation:
220
+
221
+ ```javascript
222
+ // In configuration file
223
+ const config = {
224
+ // ... other configurations
225
+ lint: 'prettier --write' // or 'eslint --fix', etc.
226
+ };
227
+ ```
228
+
229
+ ## 🤝 Contributing
230
+
231
+ Issues and Pull Requests are welcome!
232
+
233
+ ## 📄 License
234
+
234
235
  MIT License
package/dist/cli/index.js CHANGED
@@ -110,46 +110,51 @@ program
110
110
  console.warn('⚠️ 无法读取package.json,使用默认ES Module格式');
111
111
  }
112
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
- options: {
147
- // 是否添加注释
148
- addComments: true
149
- }
150
- };
151
-
152
- ${isESModule ? 'export default config;' : 'module.exports = config;'}
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
+ // 生成选项
151
+ options: {
152
+ // 是否添加注释
153
+ addComments: true
154
+ }
155
+ };
156
+
157
+ ${isESModule ? 'export default config;' : 'module.exports = config;'}
153
158
  `;
154
159
  try {
155
160
  fs.writeFileSync(configPath, configContent, 'utf-8');
@@ -64,6 +64,7 @@ export declare class CodeGenerator {
64
64
  /**
65
65
  * 收集API数组中实际使用的类型
66
66
  * @param apis API接口数组
67
+ * @param definedTypes 已定义的类型数组
67
68
  * @returns 使用的类型名称数组
68
69
  */
69
70
  private collectUsedTypes;
@@ -166,7 +166,7 @@ class CodeGenerator {
166
166
  importTemplate + ';'
167
167
  ];
168
168
  // 收集当前文件实际使用的类型
169
- const usedTypes = this.collectUsedTypes(apis);
169
+ const usedTypes = this.collectUsedTypes(apis, types); // 传入 types
170
170
  // 添加类型导入(仅在 TypeScript 且生成类型文件时)
171
171
  if (this.config.generator === 'typescript' &&
172
172
  this.config.options?.generateModels !== false &&
@@ -307,9 +307,10 @@ class CodeGenerator {
307
307
  /**
308
308
  * 收集API数组中实际使用的类型
309
309
  * @param apis API接口数组
310
+ * @param definedTypes 已定义的类型数组
310
311
  * @returns 使用的类型名称数组
311
312
  */
312
- collectUsedTypes(apis) {
313
+ collectUsedTypes(apis, definedTypes) {
313
314
  const usedTypes = new Set();
314
315
  apis.forEach((api) => {
315
316
  // 收集响应类型
@@ -334,6 +335,13 @@ class CodeGenerator {
334
335
  }
335
336
  });
336
337
  });
338
+ // 如果提供了 definedTypes,则只保留已定义的类型
339
+ if (definedTypes) {
340
+ const definedTypeNames = new Set(definedTypes.map((t) => t.name));
341
+ return Array.from(usedTypes)
342
+ .filter((name) => definedTypeNames.has(name))
343
+ .sort();
344
+ }
337
345
  return Array.from(usedTypes).sort();
338
346
  }
339
347
  /**
@@ -76,6 +76,8 @@ class SwaggerParser {
76
76
  const methodSuffix = method.charAt(0).toUpperCase() + method.slice(1).toLowerCase();
77
77
  functionName = functionName + methodSuffix;
78
78
  }
79
+ // 应用前缀忽略规则
80
+ functionName = (0, utils_1.stripMethodNamePrefixes)(functionName, this.config.methodNameIgnorePrefix);
79
81
  // 获取响应类型
80
82
  const responseType = (0, utils_1.getResponseType)(operation.responses);
81
83
  // 获取请求体类型
@@ -114,6 +116,16 @@ class SwaggerParser {
114
116
  */
115
117
  parseTypes() {
116
118
  const types = [];
119
+ // Debug log
120
+ console.log('解析类型定义...');
121
+ console.log('Has definitions:', !!this.document.definitions);
122
+ console.log('Has components:', !!this.document.components);
123
+ if (this.document.components) {
124
+ console.log('Has schemas:', !!this.document.components.schemas);
125
+ if (this.document.components.schemas) {
126
+ console.log('Schema keys:', Object.keys(this.document.components.schemas));
127
+ }
128
+ }
117
129
  // 解析 Swagger 2.0 definitions
118
130
  if (this.document.definitions) {
119
131
  for (const [name, schema] of Object.entries(this.document.definitions)) {
@@ -29,6 +29,8 @@ export interface SwaggerConfig {
29
29
  importTemplate?: string;
30
30
  /** 格式化代码命令 */
31
31
  lint?: string;
32
+ /** 生成方法名时需要忽略的前缀数组,如 ['api', 'auth'] */
33
+ methodNameIgnorePrefix?: string[];
32
34
  }
33
35
  /**
34
36
  * 标签分组配置
@@ -27,6 +27,13 @@ export declare function toPascalCase(str: string): string;
27
27
  * @returns camelCase字符串
28
28
  */
29
29
  export declare function toCamelCase(str: string): string;
30
+ /**
31
+ * 从方法名中移除指定的前缀
32
+ * @param methodName 方法名
33
+ * @param prefixes 需要移除的前缀数组
34
+ * @returns 移除前缀后的方法名
35
+ */
36
+ export declare function stripMethodNamePrefixes(methodName: string, prefixes?: string[]): string;
30
37
  /**
31
38
  * 将Swagger类型转换为TypeScript类型
32
39
  * @param schema Swagger模式
@@ -40,6 +40,7 @@ exports.pathToFunctionName = pathToFunctionName;
40
40
  exports.toKebabCase = toKebabCase;
41
41
  exports.toPascalCase = toPascalCase;
42
42
  exports.toCamelCase = toCamelCase;
43
+ exports.stripMethodNamePrefixes = stripMethodNamePrefixes;
43
44
  exports.swaggerTypeToTsType = swaggerTypeToTsType;
44
45
  exports.generateParameterTypes = generateParameterTypes;
45
46
  exports.ensureDirectoryExists = ensureDirectoryExists;
@@ -111,6 +112,44 @@ function toCamelCase(str) {
111
112
  const pascalCase = toPascalCase(str);
112
113
  return pascalCase.charAt(0).toLowerCase() + pascalCase.slice(1);
113
114
  }
115
+ /**
116
+ * 从方法名中移除指定的前缀
117
+ * @param methodName 方法名
118
+ * @param prefixes 需要移除的前缀数组
119
+ * @returns 移除前缀后的方法名
120
+ */
121
+ function stripMethodNamePrefixes(methodName, prefixes) {
122
+ if (!prefixes || prefixes.length === 0) {
123
+ return methodName;
124
+ }
125
+ let result = methodName;
126
+ // 循环移除所有匹配的前缀,直到没有前缀可以移除
127
+ let changed = true;
128
+ while (changed) {
129
+ changed = false;
130
+ for (const prefix of prefixes) {
131
+ if (!prefix)
132
+ continue;
133
+ // 将前缀转换为小驼峰格式进行匹配
134
+ const camelPrefix = toCamelCase(prefix);
135
+ // 检查方法名是否以该前缀开头(不区分大小写)
136
+ const lowerMethodName = result.toLowerCase();
137
+ const lowerPrefix = camelPrefix.toLowerCase();
138
+ if (lowerMethodName.startsWith(lowerPrefix)) {
139
+ // 移除前缀,保持后续字符的大小写
140
+ const remaining = result.substring(camelPrefix.length);
141
+ // 如果移除前缀后还有内容,则更新结果
142
+ if (remaining.length > 0) {
143
+ // 确保首字母小写
144
+ result = remaining.charAt(0).toLowerCase() + remaining.slice(1);
145
+ changed = true;
146
+ break; // 重新开始检查
147
+ }
148
+ }
149
+ }
150
+ }
151
+ return result;
152
+ }
114
153
  /**
115
154
  * 将Swagger类型转换为TypeScript类型
116
155
  * @param schema Swagger模式
@@ -300,9 +339,15 @@ function removeDirectory(dirPath) {
300
339
  async function loadSwaggerDocument(input) {
301
340
  try {
302
341
  if (input.startsWith('http://') || input.startsWith('https://')) {
303
- // 从URL加载
304
- const response = await axios_1.default.get(input);
305
- return response.data;
342
+ const { data } = await axios_1.default.get(input);
343
+ console.log('Loaded from URL:', input);
344
+ if (data.components?.schemas) {
345
+ console.log('Schemas count:', Object.keys(data.components.schemas).length);
346
+ }
347
+ else {
348
+ console.log('No schemas in loaded data');
349
+ }
350
+ return data;
306
351
  }
307
352
  else {
308
353
  // 从文件加载
@@ -351,8 +396,8 @@ function generateApiComment(operation, parameters) {
351
396
  // 如果有查询参数或路径参数,添加params注释
352
397
  if (hasParams) {
353
398
  const paramDescriptions = [...pathParams, ...queryParams]
354
- .map(p => p.description || '')
355
- .filter(desc => desc)
399
+ .map((p) => p.description || '')
400
+ .filter((desc) => desc)
356
401
  .join(', ');
357
402
  const description = paramDescriptions || '请求参数';
358
403
  comments.push(` * @param params ${description}`);
@@ -387,6 +432,9 @@ function sanitizeFilename(filename) {
387
432
  * @returns TypeScript类型字符串
388
433
  */
389
434
  function getResponseType(responses) {
435
+ if (!responses) {
436
+ return 'any';
437
+ }
390
438
  // 优先获取200响应
391
439
  const successResponse = responses['200'] || responses['201'] || responses['default'];
392
440
  if (!successResponse) {
package/package.json CHANGED
@@ -1,68 +1,68 @@
1
- {
2
- "name": "swagger2api-v3",
3
- "version": "1.1.0",
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.2",
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
+ }