gen-api-types 1.0.19 → 1.1.0
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.en.md +137 -31
- package/README.md +162 -35
- package/package.json +2 -1
- package/src/cli/index.ts +7 -6
- package/src/decotators/index.ts +2 -3
- package/src/generation/scanner.ts +7 -8
- package/src/generation/types.ts +3 -0
- package/src/transformer/index.ts +52 -13
- package/src/transformer/typeTransformer.ts +10 -18
package/README.en.md
CHANGED
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
#### Introduction
|
|
4
4
|
|
|
5
|
-
🚀 A CLI tool for automatically generating
|
|
5
|
+
🚀 A CLI tool for automatically generating API response types
|
|
6
6
|
|
|
7
|
-
In TypeScript projects, you often need to write
|
|
7
|
+
In TypeScript projects, you often need to write API response types. Manually referring to API documentation can be tedious, especially when working with third-party APIs or incomplete documentation that requires debugging the endpoint before its response type can be written.
|
|
8
8
|
|
|
9
|
-
With this tool,
|
|
9
|
+
With this tool, you can mark API classes and methods with TypeScript decorators, call the marked methods, and convert the returned data into type definition files for use in your project.
|
|
10
10
|
|
|
11
11
|
> Note:
|
|
12
12
|
>
|
|
@@ -19,7 +19,7 @@ With this tool, we can mark request interface classes and methods through TypeSc
|
|
|
19
19
|
1. npm installation
|
|
20
20
|
|
|
21
21
|
```shell
|
|
22
|
-
npm install gen-api-types
|
|
22
|
+
npm install gen-api-types -D
|
|
23
23
|
```
|
|
24
24
|
|
|
25
25
|
#### Usage
|
|
@@ -29,20 +29,25 @@ npm install gen-api-types
|
|
|
29
29
|
```ts
|
|
30
30
|
import { gen_type_c, gen_type_m } from 'gen-api-types'
|
|
31
31
|
|
|
32
|
+
const asleep = (t = 1000) => new Promise(r => setTimeout(r, t))
|
|
33
|
+
const aa = 99
|
|
34
|
+
|
|
32
35
|
@gen_type_c()
|
|
33
|
-
export class
|
|
36
|
+
export class SampleApi {
|
|
34
37
|
@gen_type_m({
|
|
35
|
-
args: [
|
|
36
|
-
typeName: '
|
|
38
|
+
args: [aa],
|
|
39
|
+
typeName: 'GetListResult',
|
|
37
40
|
})
|
|
38
|
-
|
|
41
|
+
/** Simulated async request */
|
|
42
|
+
getList(id: number) {
|
|
39
43
|
return asleep(1000).then(() => {
|
|
40
44
|
return { name: 'zs', id }
|
|
41
45
|
})
|
|
42
46
|
}
|
|
43
47
|
|
|
44
48
|
@gen_type_m()
|
|
45
|
-
|
|
49
|
+
/** Real async request */
|
|
50
|
+
static async getWeather() {
|
|
46
51
|
return fetch('http://t.weather.sojson.com/api/weather/city/101030100').then(r => r.json())
|
|
47
52
|
}
|
|
48
53
|
}
|
|
@@ -56,15 +61,6 @@ As shown in the code above:
|
|
|
56
61
|
- `typeName: string` is the generated type name. If omitted, it defaults to `Response_${ClassName}_${MethodName}`.
|
|
57
62
|
- The marked class is only a decorator carrier; the Runner does not instantiate it. Non-static methods must not depend on `this` or instance fields.
|
|
58
63
|
|
|
59
|
-
Decorator options may span multiple lines:
|
|
60
|
-
|
|
61
|
-
```ts
|
|
62
|
-
@gen_type_m({
|
|
63
|
-
args: [100],
|
|
64
|
-
typeName: 'XXX'
|
|
65
|
-
})
|
|
66
|
-
```
|
|
67
|
-
|
|
68
64
|
> Note:
|
|
69
65
|
|
|
70
66
|
If TypeScript reports the decorator error "The runtime will invoke the decorator with 2 arguments, but the decorator expects 3", set `compilerOptions.experimentalDecorators` to `true` in `tsconfig.json`.
|
|
@@ -112,6 +108,12 @@ Available commands:
|
|
|
112
108
|
|
|
113
109
|
The CLI scans `.ts` files in the input directories to find marked classes, methods, and their modules. It then imports those modules so decorators can register tasks. After all modules have loaded, the Runner invokes the registered API methods and converts successful results into a type declaration file. Each API method has a default execution timeout of 5 seconds; registered methods run concurrently.
|
|
114
110
|
|
|
111
|
+
After generating the declaration file, the CLI also completes the return type annotations of successful API methods using their generated type names. For example, an async method is updated to return `Promise<Response_TestApi_getWeather>`, while a synchronous method is updated to return `Response_TestApi_getList`. Methods whose requests fail are not modified.
|
|
112
|
+
|
|
113
|
+
This step modifies the API source files directly. Review the changes with `git diff` after generation to verify the completed annotations.
|
|
114
|
+
|
|
115
|
+
> Note: The completion logic uses `fullMethodName` (`ClassName.methodName`) to match execution results back to API methods. It does not currently include the module path, so every `ClassName.methodName` pair across the scanned modules must be unique. If different modules contain a class and method with the same names, a type may be written to the wrong method. Avoid such duplicates or carefully review the generated source changes.
|
|
116
|
+
|
|
115
117
|
Command output:
|
|
116
118
|
|
|
117
119
|
```shell
|
|
@@ -119,7 +121,7 @@ Command output:
|
|
|
119
121
|
sourceFilesGlob [ 'src\\**\\*.ts' ]
|
|
120
122
|
✅ API type generation completed: /path/to/api-types.d.ts
|
|
121
123
|
|
|
122
|
-
# If a request fails,
|
|
124
|
+
# If a request fails, that method is skipped; types are generated only for successful requests.
|
|
123
125
|
sourceFilesGlob [ 'test/api/**/*.ts' ]
|
|
124
126
|
❌ SampleApi.testError execute error: ReferenceError: arg is not defined
|
|
125
127
|
|
|
@@ -133,7 +135,113 @@ Request results:
|
|
|
133
135
|
✅ API type generation completed: /path/to/api-types.d.ts
|
|
134
136
|
```
|
|
135
137
|
|
|
136
|
-
##### 3.
|
|
138
|
+
##### 3. Automatically complete API method return types
|
|
139
|
+
|
|
140
|
+
After type generation, the CLI automatically adds return type annotations to the API methods. You do not need to add them manually.
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
import { gen_type_c, gen_type_m } from 'gen-api-types'
|
|
144
|
+
|
|
145
|
+
const asleep = (t = 1000) => new Promise(r => setTimeout(r, t))
|
|
146
|
+
const aa = 99
|
|
147
|
+
|
|
148
|
+
@gen_type_c()
|
|
149
|
+
export class SampleApi {
|
|
150
|
+
@gen_type_m({
|
|
151
|
+
args: [aa],
|
|
152
|
+
typeName: 'GetListResult',
|
|
153
|
+
})
|
|
154
|
+
/** Simulated async request */
|
|
155
|
+
getList(id: number): Promise<GetListResult> {
|
|
156
|
+
return asleep(1000).then(() => {
|
|
157
|
+
return { name: 'zs', id }
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
@gen_type_m()
|
|
162
|
+
/** Real async request */
|
|
163
|
+
static async getWeather(): Promise<Response_SampleApi_getWeather> {
|
|
164
|
+
return fetch('http://t.weather.sojson.com/api/weather/city/101030100').then(r => r.json())
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const weather = await SampleApi.getWeather()
|
|
169
|
+
// weather has type Response_SampleApi_getWeather
|
|
170
|
+
|
|
171
|
+
const cityInfo = weather.cityInfo
|
|
172
|
+
// cityInfo has type Response_SampleApi_getWeather['cityInfo']:
|
|
173
|
+
// {
|
|
174
|
+
// city: string;
|
|
175
|
+
// citykey: string;
|
|
176
|
+
// parent: string;
|
|
177
|
+
// updateTime: string;
|
|
178
|
+
// }
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
The return-type completion logic works as follows:
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
/**
|
|
185
|
+
* Automatically completes API method return types.
|
|
186
|
+
*/
|
|
187
|
+
export async function completeReturnTypeToApiMethod(moduleMap: ScanModuleMap, typeList: TypeList) {
|
|
188
|
+
const p = new Project()
|
|
189
|
+
moduleMap.forEach((fullMethods, modulePath) => {
|
|
190
|
+
const sf = p.addSourceFileAtPath(modulePath)
|
|
191
|
+
fullMethods.forEach(fullMethodName => {
|
|
192
|
+
const [className, methodName] = fullMethodName.split('.')
|
|
193
|
+
const cs = sf.getClass(className)
|
|
194
|
+
const m = cs?.getMethod(methodName)
|
|
195
|
+
const oldReturnTypeText = m?.getReturnType().getText()
|
|
196
|
+
const isAsync = oldReturnTypeText?.startsWith('Promise<') || m?.isAsync()
|
|
197
|
+
|
|
198
|
+
const typeName = typeList.find(item => item.fullMethodName === fullMethodName)?.typeName
|
|
199
|
+
if (m && typeName) {
|
|
200
|
+
m?.setReturnType(isAsync ? `Promise<${typeName}>` : typeName)
|
|
201
|
+
}
|
|
202
|
+
})
|
|
203
|
+
})
|
|
204
|
+
return p.save()
|
|
205
|
+
}
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
###### About `fullMethodName`
|
|
209
|
+
|
|
210
|
+
`fullMethodName` (`className.methodName`) must be unique across all scanned modules. Otherwise, a generated `typeName` may be matched to the wrong method. When `gen_type_m` registers an API method, the module path is not available, so `fullMethodName` is currently used as the identifier. Different modules can therefore contain the same `fullMethodName`.
|
|
211
|
+
|
|
212
|
+
The current decorator registration looks like this:
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
export const gen_type_m = createMethodDecorator(async ({ target, propertyKey, descriptor }, { typeName, args }: GenTypeOptions = { args: [] }) => {
|
|
216
|
+
const className = typeof target == 'function' ? target.name : target.constructor.name
|
|
217
|
+
const fullMethodName = `${className}.${propertyKey}`
|
|
218
|
+
typeName ??= `Response_${className}_${propertyKey}`
|
|
219
|
+
const handler = () => descriptor.value.apply(target, args)
|
|
220
|
+
registry.register({
|
|
221
|
+
key: descriptor.value,
|
|
222
|
+
meta: { typeName, name: fullMethodName, handler },
|
|
223
|
+
})
|
|
224
|
+
})
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
It may be possible to infer the source module from `Error.stack`, but this approach is not used for now:
|
|
228
|
+
|
|
229
|
+
```ts
|
|
230
|
+
export const gen_type_c = createClassDecorator((ctx, options) => {
|
|
231
|
+
console.log(new Error())
|
|
232
|
+
})
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
The stack trace includes a frame from the API module (for example, `project/test/api/index.ts`). However, parsing stack traces to obtain a file path is not preferred at this time.
|
|
236
|
+
|
|
237
|
+
###### How async return types are determined
|
|
238
|
+
|
|
239
|
+
The generated type is wrapped in `Promise<${typeName}>` if either condition is true:
|
|
240
|
+
|
|
241
|
+
1. TypeScript resolves the method's existing return type to a Promise, such as `Promise<SomeType>` (`oldReturnTypeText` starts with `Promise<`).
|
|
242
|
+
2. The method is declared with the `async` keyword (`m?.isAsync()` is `true`).
|
|
243
|
+
|
|
244
|
+
##### 4. Using the types
|
|
137
245
|
|
|
138
246
|
By default, a type definition file api-types.d.ts is generated, and the type declarations are not exported:
|
|
139
247
|
|
|
@@ -142,16 +250,16 @@ type XXX = { name: string };
|
|
|
142
250
|
type Response_TestApi_getWeather = {...}
|
|
143
251
|
```
|
|
144
252
|
|
|
145
|
-
You can
|
|
253
|
+
You can include it in `tsconfig.json`:
|
|
146
254
|
|
|
147
255
|
```json
|
|
148
256
|
// tsconfig.json
|
|
149
257
|
{
|
|
150
|
-
"include": ["api-types.d.ts"]
|
|
258
|
+
"include": ["path/to/api-types.d.ts"]
|
|
151
259
|
}
|
|
152
260
|
```
|
|
153
261
|
|
|
154
|
-
Or reference it
|
|
262
|
+
Or reference it at the top of a module:
|
|
155
263
|
|
|
156
264
|
```ts
|
|
157
265
|
/// <reference path="./api-types.d.ts" />
|
|
@@ -166,22 +274,22 @@ export class TestApi {
|
|
|
166
274
|
const data = await TestApi.getWeather()
|
|
167
275
|
```
|
|
168
276
|
|
|
169
|
-
|
|
277
|
+
To generate exported type declarations, use the `--isExported` CLI option:
|
|
170
278
|
|
|
171
279
|
```shell
|
|
172
280
|
npx gen-api-types --isExported -o output_dir -O output_file_name ./api_dir1 ./api_dir2
|
|
173
281
|
```
|
|
174
282
|
|
|
175
|
-
Generated output
|
|
283
|
+
Generated output:
|
|
176
284
|
|
|
177
285
|
```ts
|
|
178
286
|
export type XXX = { name: string };
|
|
179
287
|
export type Response_TestApi_getWeather = {...}
|
|
180
288
|
```
|
|
181
289
|
|
|
182
|
-
#####
|
|
290
|
+
##### 5. Vite plugin
|
|
183
291
|
|
|
184
|
-
|
|
292
|
+
The decorators are intended for type generation and should not affect application code. In a Vite project, use the `removeGatDecorators` plugin to remove `gen_type_c` and `gen_type_m` from source code during production builds:
|
|
185
293
|
|
|
186
294
|
```ts
|
|
187
295
|
// vite.config.ts
|
|
@@ -193,9 +301,7 @@ export default defineConfig({
|
|
|
193
301
|
})
|
|
194
302
|
```
|
|
195
303
|
|
|
196
|
-
The plugin processes `.ts`
|
|
197
|
-
|
|
198
|
-
The Vite plugin only affects Vite's transform pipeline. It is not involved when the CLI imports and executes API modules.
|
|
304
|
+
The plugin processes `.ts` files and currently removes decorators named `gen_type_c` and `gen_type_m`.
|
|
199
305
|
|
|
200
306
|
#### VS Code Extension
|
|
201
307
|
|
|
@@ -205,7 +311,7 @@ If you use `gen-api-types` in VS Code, you can install the companion extension [
|
|
|
205
311
|
|
|
206
312
|
The extension does not bundle the CLI. It invokes the version of `gen-api-types` installed locally in the current project.
|
|
207
313
|
|
|
208
|
-
After installing the extension, right-click in a `.ts`
|
|
314
|
+
After installing the extension, right-click in a `.ts` file containing the decorated APIs and select `Generate API Return Types (gen-api-types)`. By default, the extension will:
|
|
209
315
|
|
|
210
316
|
- Use the directory containing the current TypeScript file as the `api_dirs` argument
|
|
211
317
|
- Generate the type file in the same directory as the current TypeScript file
|
package/README.md
CHANGED
|
@@ -6,20 +6,20 @@
|
|
|
6
6
|
|
|
7
7
|
在 ts 项目中,经常需要编写接口返回类型。但是每次都要查看接口文档,手动编写非常麻烦。如果遇到一些第三方接口或者接口文档不全的情况,还需要先调试接口后,再编写接口返回类型,很令人头疼
|
|
8
8
|
|
|
9
|
-
借助这个工具,我们可以通过 ts 装饰器来标记请求接口的类和方法,然后动态调用这些接口,并将接口返回的数据转换成
|
|
9
|
+
借助这个工具,我们可以通过 ts 装饰器来标记请求接口的类和方法,然后动态调用这些接口,并将接口返回的数据转换成 类型文件,这样我们就可以在项目中直接使用了
|
|
10
10
|
|
|
11
11
|
> 注意:
|
|
12
12
|
>
|
|
13
|
-
> 1. 由于需要使用 TypeScript 方法装饰器,接口需要以 **API 类 + API 方法**
|
|
14
|
-
> 2. CLI 会动态导入包含标记方法的模块。模块顶层代码会在导入时执行;装饰器只登记任务,CLI 随后才调用已登记的 API
|
|
15
|
-
> 3. API 方法会在 CLI
|
|
13
|
+
> 1. 由于需要使用 TypeScript 方法装饰器,接口需要以 **API 类 + API 方法** 的形式书写
|
|
14
|
+
> 2. CLI 会动态导入包含标记方法的模块。模块顶层代码会在导入时执行;装饰器只登记任务,CLI 随后才调用已登记的 API 方法
|
|
15
|
+
> 3. API 方法会在 CLI 进程中真实执行,请确保运行所需的环境变量、网络权限和鉴权配置已经准备好
|
|
16
16
|
|
|
17
17
|
#### 安装教程
|
|
18
18
|
|
|
19
19
|
1.npm 安装
|
|
20
20
|
|
|
21
21
|
```shell
|
|
22
|
-
npm install gen-api-types
|
|
22
|
+
npm install gen-api-types -D
|
|
23
23
|
```
|
|
24
24
|
|
|
25
25
|
#### 使用说明
|
|
@@ -29,20 +29,25 @@ npm install gen-api-types
|
|
|
29
29
|
```ts
|
|
30
30
|
import { gen_type_c, gen_type_m } from 'gen-api-types'
|
|
31
31
|
|
|
32
|
+
const asleep = (t = 1000) => new Promise(r => setTimeout(r, t))
|
|
33
|
+
const aa = 99
|
|
34
|
+
|
|
32
35
|
@gen_type_c()
|
|
33
|
-
export class
|
|
36
|
+
export class SampleApi {
|
|
34
37
|
@gen_type_m({
|
|
35
|
-
args: [
|
|
36
|
-
typeName: '
|
|
38
|
+
args: [aa],
|
|
39
|
+
typeName: 'GetListResult',
|
|
37
40
|
})
|
|
38
|
-
|
|
41
|
+
/**模拟异步*/
|
|
42
|
+
getList(id: number) {
|
|
39
43
|
return asleep(1000).then(() => {
|
|
40
44
|
return { name: 'zs', id }
|
|
41
45
|
})
|
|
42
46
|
}
|
|
43
47
|
|
|
44
48
|
@gen_type_m()
|
|
45
|
-
|
|
49
|
+
/**真实异步请求*/
|
|
50
|
+
static async getWeather() {
|
|
46
51
|
return fetch('http://t.weather.sojson.com/api/weather/city/101030100').then(r => r.json())
|
|
47
52
|
}
|
|
48
53
|
}
|
|
@@ -56,15 +61,6 @@ export class TestApi {
|
|
|
56
61
|
- `typeName: string` 是生成的类型名称;不指定时默认为 `Response_${类名}_${方法名}`。
|
|
57
62
|
- 标记类仅用于承载装饰器;Runner 不会创建类实例。普通方法不要依赖 `this` 或实例字段。
|
|
58
63
|
|
|
59
|
-
装饰器参数可以跨多行书写:
|
|
60
|
-
|
|
61
|
-
```ts
|
|
62
|
-
@gen_type_m({
|
|
63
|
-
args: [100],
|
|
64
|
-
typeName: 'XXX'
|
|
65
|
-
})
|
|
66
|
-
```
|
|
67
|
-
|
|
68
64
|
> 注意:
|
|
69
65
|
|
|
70
66
|
若使用装饰器时 TypeScript 报错“运行时将使用 2 个自变量调用修饰器,但修饰器需要 3 个”,请将 `tsconfig.json` 中的 `compilerOptions.experimentalDecorators` 设置为 `true`。
|
|
@@ -120,7 +116,7 @@ sourceFilesGlob [ 'src\\**\\*.ts' ]
|
|
|
120
116
|
✅ API 类型生成完成: /path/to/api-types.d.ts
|
|
121
117
|
|
|
122
118
|
|
|
123
|
-
#
|
|
119
|
+
# 包含错误请求时,会忽略该条请求,只生成 Success 的类型
|
|
124
120
|
|
|
125
121
|
sourceFilesGlob [ 'test/api/**/*.ts' ]
|
|
126
122
|
❌ SampleApi.testError execute error: ReferenceError: arg is not defined
|
|
@@ -135,7 +131,139 @@ sourceFilesGlob [ 'test/api/**/*.ts' ]
|
|
|
135
131
|
✅ API 类型生成完成: /Users/xuejiangping/Desktop/demo/gen-api-types/test/output/api-types.d.ts
|
|
136
132
|
```
|
|
137
133
|
|
|
138
|
-
##### 3.
|
|
134
|
+
##### 3. 自动补全返回类型
|
|
135
|
+
|
|
136
|
+
生成类型声明文件后,CLI 还会自动补全成功 API 方法的返回类型:根据生成的类型名称更新对应方法的返回类型注解。例如,异步方法会补全为 `Promise<Response_TestApi_getWeather>`,同步方法会补全为 `Response_TestApi_getList`。请求失败的方法不会被修改。
|
|
137
|
+
|
|
138
|
+
此步骤会直接修改 API 源文件。建议生成后检查 `git diff`,确认补全结果符合预期。
|
|
139
|
+
|
|
140
|
+
> 注意:补全逻辑使用 `fullMethodName`(`类名.方法名`)将执行结果匹配回 API 方法。目前它不包含模块路径,因此所有扫描模块中的 `类名.方法名` 必须唯一。如果不同模块存在同名类和同名方法,类型可能被补全到错误的方法上。请避免这类重名,或先检查生成后的源码差异。
|
|
141
|
+
|
|
142
|
+
```typescript
|
|
143
|
+
import { gen_type_c, gen_type_m } from 'gen-api-types'
|
|
144
|
+
|
|
145
|
+
const asleep = (t = 1000) => new Promise(r => setTimeout(r, t))
|
|
146
|
+
const aa = 99
|
|
147
|
+
|
|
148
|
+
@gen_type_c()
|
|
149
|
+
export class SampleApi {
|
|
150
|
+
@gen_type_m({
|
|
151
|
+
args: [aa],
|
|
152
|
+
typeName: 'GetListResult',
|
|
153
|
+
})
|
|
154
|
+
/**模拟异步请求*/
|
|
155
|
+
getList(id: number): Promise<GetListResult> {
|
|
156
|
+
return asleep(1000).then(() => {
|
|
157
|
+
return { name: 'zs', id }
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
@gen_type_m()
|
|
162
|
+
/**真实异步请求*/
|
|
163
|
+
static async getWeather(): Promise<Response_SampleApi_getWeather> {
|
|
164
|
+
return fetch('http://t.weather.sojson.com/api/weather/city/101030100').then(r => r.json())
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
//=================================================
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
*
|
|
172
|
+
* @type weather
|
|
173
|
+
* 类型为 Response_SampleApi_getWeather
|
|
174
|
+
* weather
|
|
175
|
+
*
|
|
176
|
+
*/
|
|
177
|
+
const weather = await SampleApi.getWeather()
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* @type weather.cityInfo
|
|
181
|
+
* 类型为 Response_SampleApi_getWeather['cityInfo']
|
|
182
|
+
* cityInfo: {
|
|
183
|
+
* city: string;
|
|
184
|
+
* citykey: string;
|
|
185
|
+
* parent: string;
|
|
186
|
+
* updateTime: string
|
|
187
|
+
* }
|
|
188
|
+
*/
|
|
189
|
+
const cityInfo = weather.cityInfo
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
类型自动补全的逻辑参考:
|
|
193
|
+
|
|
194
|
+
```typescript
|
|
195
|
+
/**
|
|
196
|
+
* 自动补全api方法返回类型
|
|
197
|
+
*/
|
|
198
|
+
export async function completeReturnTypeToApiMethod(moduleMap: ScanModuleMap, typeList: TypeList) {
|
|
199
|
+
const p = new Project()
|
|
200
|
+
moduleMap.forEach((fullMethods, modulePath) => {
|
|
201
|
+
const sf = p.addSourceFileAtPath(modulePath)
|
|
202
|
+
fullMethods.forEach(fullMethodName => {
|
|
203
|
+
const [className, methodName] = fullMethodName.split('.')
|
|
204
|
+
const cs = sf.getClass(className)
|
|
205
|
+
const m = cs?.getMethod(methodName)
|
|
206
|
+
const oldReturnTypeText = m?.getReturnType().getText()
|
|
207
|
+
const isAsync = oldReturnTypeText?.startsWith('Promise<') || m?.isAsync()
|
|
208
|
+
|
|
209
|
+
const typeName = typeList.find(item => item.fullMethodName === fullMethodName)?.typeName
|
|
210
|
+
if (m && typeName) {
|
|
211
|
+
m?.setReturnType(isAsync ? `Promise<${typeName}>` : typeName)
|
|
212
|
+
}
|
|
213
|
+
})
|
|
214
|
+
})
|
|
215
|
+
return p.save()
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
###### 关于`fullMethodName`
|
|
220
|
+
|
|
221
|
+
从补全逻辑中,我们也可以看到 `fullMethodName(className.methodName)` 必须为唯一,不然导致匹配到错误的`typeName`。原因很简单,装饰器 `gen_type_m`在收集API的数据时,是拿不到API方法所在的模块path,只能用`fullMethodName` 作为唯一标识,可能存在不同模块下`fullMethodName` 相同的情况
|
|
222
|
+
|
|
223
|
+
```typescript
|
|
224
|
+
export const gen_type_m = createMethodDecorator(async ({ target, propertyKey, descriptor }, { typeName, args }: GenTypeOptions = { args: [] }) => {
|
|
225
|
+
const className = typeof target == 'function' ? target.name : target.constructor.name
|
|
226
|
+
const fullMethodName = `${className}.${propertyKey}`
|
|
227
|
+
typeName ??= `Response_${className}_${propertyKey}`
|
|
228
|
+
const handler = () => descriptor.value.apply(target, args)
|
|
229
|
+
registry.register({
|
|
230
|
+
key: descriptor.value,
|
|
231
|
+
meta: { typeName, name: fullMethodName, handler },
|
|
232
|
+
})
|
|
233
|
+
})
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
但通过查资料我了解到,可以通过`Error.stack`捕获当前的调用栈来推断文件路径
|
|
237
|
+
|
|
238
|
+
```typescript
|
|
239
|
+
export const gen_type_c = createClassDecorator((ctx, options) => {
|
|
240
|
+
console.log(new Error())
|
|
241
|
+
})
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
如下面的输出所示,第三行就是我们的api方法所在的module(`gen-api-types/test/api/index.ts`),但是我不太喜欢这种方法,所以这个问题先放放
|
|
245
|
+
|
|
246
|
+
```Shell
|
|
247
|
+
|
|
248
|
+
Error
|
|
249
|
+
at <anonymous> (/Users/xuejiangping/Desktop/demo/gen-api-types/src/decotators/index.ts:17:15)
|
|
250
|
+
at <anonymous> (/Users/xuejiangping/Desktop/demo/gen-api-types/src/utils/decoratorHelper.ts:33:50)
|
|
251
|
+
at __decorateClass (file:///Users/xuejiangping/Desktop/demo/gen-api-types/test/api/index.ts:1:403)
|
|
252
|
+
at <anonymous> (/Users/xuejiangping/Desktop/demo/gen-api-types/test/api/index.ts:7:8)
|
|
253
|
+
at ModuleJob.run (node:internal/modules/esm/module_job:430:25)
|
|
254
|
+
at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26)
|
|
255
|
+
at async Promise.all (index 0)
|
|
256
|
+
at async main (/Users/xuejiangping/Desktop/demo/gen-api-types/src/cli/index.ts:29:5)
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
###### 关于 `isAsync `
|
|
260
|
+
|
|
261
|
+
当apiMethod满足以下条件之一时,方法会被认为是异步,自动推导会使用 `Promise<${typeName}>` 包装
|
|
262
|
+
|
|
263
|
+
1. 若api方法中,已经明确返回了`ts`可推导的`Promise`,即`oldReturnTypeText`为`Promise<SomeType>`
|
|
264
|
+
2. api 方法被async 标记, `m?.isAsync() `为 `true`
|
|
265
|
+
|
|
266
|
+
##### 4. 使用类型
|
|
139
267
|
|
|
140
268
|
默认生成类型文件 api-types.d.ts,且类型声明没有导出
|
|
141
269
|
|
|
@@ -144,16 +272,16 @@ type XXX = { name: string };
|
|
|
144
272
|
type Response_TestApi_getWeather = {...}
|
|
145
273
|
```
|
|
146
274
|
|
|
147
|
-
可在`tsconfig.json`中配置`include
|
|
275
|
+
可在`tsconfig.json`中配置`include`包含
|
|
148
276
|
|
|
149
277
|
```json
|
|
150
278
|
// tsconfig.json
|
|
151
279
|
{
|
|
152
|
-
"include": ["api-types.d.ts"]
|
|
280
|
+
"include": ["需包含api-types.d.ts"]
|
|
153
281
|
}
|
|
154
282
|
```
|
|
155
283
|
|
|
156
|
-
|
|
284
|
+
或者在模块顶部通过 reference 引用:
|
|
157
285
|
|
|
158
286
|
```ts
|
|
159
287
|
/// <reference path="./api-types.d.ts" />
|
|
@@ -168,22 +296,22 @@ export class TestApi {
|
|
|
168
296
|
const data = await TestApi.getWeather()
|
|
169
297
|
```
|
|
170
298
|
|
|
171
|
-
|
|
299
|
+
当然,如果希望生成可导出的类型声明,`cli`提供了命令选项 `--isExported`以生成可导出的类型
|
|
172
300
|
|
|
173
301
|
```shell
|
|
174
302
|
npx gen-api-types --isExported -o output_dir -O output_file_name ./api_dir1 ./api_dir2
|
|
175
303
|
```
|
|
176
304
|
|
|
177
|
-
|
|
305
|
+
生成结果:
|
|
178
306
|
|
|
179
307
|
```ts
|
|
180
308
|
export type XXX = { name: string };
|
|
181
309
|
export type Response_TestApi_getWeather = {...}
|
|
182
310
|
```
|
|
183
311
|
|
|
184
|
-
#####
|
|
312
|
+
##### 5. Vite 插件
|
|
185
313
|
|
|
186
|
-
|
|
314
|
+
**cli**中的装饰器只适用于生成类型,不应对业务代码产生侵入。Vite 项目可以使用插件`removeGatDecorators`在生产模式下移除 `gen_type_c`和`gen_type_m`,避免装饰器在业务代码中产生副作用
|
|
187
315
|
|
|
188
316
|
```ts
|
|
189
317
|
// vite.config.ts
|
|
@@ -195,18 +323,17 @@ export default defineConfig({
|
|
|
195
323
|
})
|
|
196
324
|
```
|
|
197
325
|
|
|
198
|
-
插件只处理 `.ts`
|
|
199
|
-
|
|
200
|
-
Vite 插件只影响 Vite 的转换流程,不参与 CLI 的 API 执行流程。
|
|
326
|
+
插件只处理 `.ts` 文件,目前只处理`gen_type_c`、`gen_type_m` 这两个装饰器名
|
|
201
327
|
|
|
202
328
|
#### VS Code 插件
|
|
203
329
|
|
|
204
|
-
如果你在 VS Code 中使用 `gen-api-types` ,可以安装配套插件 [gen-api-types-vsce](https://github.com/xuejiangping/gen-api-types-vsce),通过右键菜单生成 API
|
|
330
|
+
如果你在 VS Code 中使用 `gen-api-types` ,可以安装配套插件 [gen-api-types-vsce](https://github.com/xuejiangping/gen-api-types-vsce),通过右键菜单生成 API 返回类型,终于不用再敲命令和脚本啦😄😄😄
|
|
331
|
+
|
|
205
332
|

|
|
206
333
|
|
|
207
|
-
插件不会内置
|
|
334
|
+
插件不会内置 **cli**,它会调用当前业务项目本地安装的 `gen-api-types`:
|
|
208
335
|
|
|
209
|
-
安装插件后,在已标记装饰器的 `.ts`
|
|
336
|
+
安装插件后,在已标记装饰器的 `.ts` 文件中右键选择 `生成 API 返回类型(gen-api-types)` 即可。插件会默认:
|
|
210
337
|
|
|
211
338
|
- 将当前 TypeScript 文件所在目录作为 `api_dirs` 参数
|
|
212
339
|
- 将类型文件生成到当前 TypeScript 文件同目录
|
|
@@ -223,4 +350,4 @@ Vite 插件只影响 Vite 的转换流程,不参与 CLI 的 API 执行流程
|
|
|
223
350
|
| `gen-api-types.tsConfigPath` | `-t, --ts_config_path` | 不传,由 CLI 使用默认值 |
|
|
224
351
|
| `gen-api-types.isExported` | `--isExported` | `false` |
|
|
225
352
|
|
|
226
|
-
|
|
353
|
+
插件本质上是对**cli** 的 VS Code 入口封装,类型分析、接口执行和类型文件生成仍由 `gen-api-types` 完
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gen-api-types",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "一个自动生成请求接口返回类型的 cli 小工具",
|
|
5
5
|
"main": "./src/index.ts",
|
|
6
6
|
"exports": {
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
"scripts": {
|
|
19
19
|
"test": "vitest",
|
|
20
20
|
"publish:patch": "npm version patch && git push --tags && npm publish",
|
|
21
|
+
"publish:minor": "npm version minor && git push --tags && npm publish",
|
|
21
22
|
"preinstall": "echo preinstall 。。。",
|
|
22
23
|
"postinstall": "echo postinstall 。。。",
|
|
23
24
|
"gat": "gat -o test/output test/api "
|
package/src/cli/index.ts
CHANGED
|
@@ -5,7 +5,7 @@ import * as path from 'path';
|
|
|
5
5
|
import { isExported, output_dir, output_file, positionals } from '../argv';
|
|
6
6
|
import { runner, scanner } from '../generation';
|
|
7
7
|
import { importApiModule } from '../generation/moduleLoader';
|
|
8
|
-
import { createDeclarationFile } from '../transformer';
|
|
8
|
+
import { completeReturnTypeToApiMethod, createDeclarationFile } from '../transformer';
|
|
9
9
|
import { formatResultList, getSourceFilesGlobFromEntrances, logResultList } from '../utils';
|
|
10
10
|
|
|
11
11
|
|
|
@@ -24,7 +24,9 @@ async function main() {
|
|
|
24
24
|
process.exit(0)
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
const modulePathList = Array.from(modules.keys())
|
|
28
|
+
|
|
29
|
+
await importApiModule(modulePathList)
|
|
28
30
|
|
|
29
31
|
const executeResultList = await runner.run()
|
|
30
32
|
|
|
@@ -32,12 +34,11 @@ async function main() {
|
|
|
32
34
|
if (executeErrorList.length) logResultList('请求结果:', executeSuccessList, executeErrorList)
|
|
33
35
|
|
|
34
36
|
const out_put_target = path.resolve(output_dir, output_file)
|
|
35
|
-
|
|
36
|
-
const { successList: transformSuccessList, errorList: transformErrorList } = formatResultList(transformList)
|
|
37
|
+
await createDeclarationFile(executeSuccessList, out_put_target, isExported)
|
|
37
38
|
|
|
38
|
-
|
|
39
|
+
await completeReturnTypeToApiMethod(modules, executeSuccessList)
|
|
39
40
|
|
|
40
|
-
|
|
41
|
+
console.log('✅ API 类型生成完成:', out_put_target);
|
|
41
42
|
} catch (error) {
|
|
42
43
|
console.error('❌ 出错了', error)
|
|
43
44
|
process.exitCode = 1
|
package/src/decotators/index.ts
CHANGED
|
@@ -13,11 +13,10 @@ export interface GenTypeOptions {
|
|
|
13
13
|
|
|
14
14
|
|
|
15
15
|
|
|
16
|
-
|
|
17
|
-
|
|
18
16
|
export const gen_type_c = createClassDecorator((ctx, options) => {
|
|
19
|
-
|
|
17
|
+
// console.log(new Error())
|
|
20
18
|
})
|
|
19
|
+
|
|
21
20
|
export const gen_type_m = createMethodDecorator(async (
|
|
22
21
|
{ target, propertyKey, descriptor },
|
|
23
22
|
{ typeName, args }: GenTypeOptions = { args: [] }
|
|
@@ -1,37 +1,36 @@
|
|
|
1
1
|
import { Project } from "ts-morph";
|
|
2
2
|
import { DECO_NAME_C, DECO_NAME_M } from "../constant";
|
|
3
|
+
import { ScanModuleMap } from "./types";
|
|
4
|
+
|
|
3
5
|
|
|
4
6
|
|
|
5
|
-
type ScanResult = Map<string, Set<string>>
|
|
6
7
|
|
|
7
8
|
export class Scanner {
|
|
8
9
|
constructor(public ts_config_path?: string) { }
|
|
9
|
-
public cacheResult:
|
|
10
|
+
public cacheResult: ScanModuleMap | null = null
|
|
10
11
|
/**
|
|
11
12
|
* 扫描指定的源文件路径,查找被装饰器标记的类和方法,并返回一个映射,键为模块路径,值为该模块中被标记的方法集合。
|
|
12
13
|
* @param sourceFilesGlob
|
|
13
14
|
* @returns modulepath -> methods
|
|
14
15
|
*/
|
|
15
16
|
scan(sourceFilesGlob: string[]) {
|
|
16
|
-
const moduleMap:
|
|
17
|
+
const moduleMap: ScanModuleMap = new Map()
|
|
17
18
|
const project = new Project({ tsConfigFilePath: this.ts_config_path, });
|
|
18
19
|
project.addSourceFilesAtPaths(sourceFilesGlob);
|
|
20
|
+
project.createWriter()
|
|
19
21
|
for (const sourceFile of project.getSourceFiles()) {
|
|
20
|
-
|
|
21
22
|
const classes = sourceFile.getClasses();
|
|
22
23
|
for (const classDeclaration of classes) {
|
|
23
24
|
const c_deco = classDeclaration.getDecorator(DECO_NAME_C)
|
|
24
25
|
if (!c_deco) continue
|
|
25
26
|
const methods = classDeclaration.getMethods();
|
|
26
27
|
for (const method of methods) {
|
|
28
|
+
const m_deco = method.getDecorator(DECO_NAME_M)
|
|
29
|
+
if (!m_deco) continue
|
|
27
30
|
const className = classDeclaration.getName()!;
|
|
28
31
|
const methodName = method.getName();
|
|
29
32
|
const fullMethodName = `${className}.${methodName}`;
|
|
30
|
-
|
|
31
|
-
const m_deco = method.getDecorator(DECO_NAME_M)
|
|
32
|
-
if (!m_deco) continue
|
|
33
33
|
const modulePath = sourceFile.getFilePath()
|
|
34
|
-
|
|
35
34
|
const methods = moduleMap.get(modulePath) ?? new Set()
|
|
36
35
|
methods.add(fullMethodName)
|
|
37
36
|
moduleMap.set(modulePath, methods)
|
package/src/generation/types.ts
CHANGED
package/src/transformer/index.ts
CHANGED
|
@@ -1,17 +1,56 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { Project } from "ts-morph"
|
|
2
|
+
import { ExecuteApiMethodResult, ScanModuleMap } from "../generation/types"
|
|
3
|
+
import { SourceList, TypeTransformer } from "./typeTransformer"
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 生成类型文件
|
|
9
|
+
* @param isExported 生成类型是否导出
|
|
10
|
+
*/
|
|
11
|
+
export async function createDeclarationFile(executeList: ExecuteApiMethodResult[], out_put_target: string, isExported: boolean) {
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
3
15
|
|
|
4
|
-
export function createDeclarationFile(executeList: ExecuteApiMethodResult[], out_put_target: string, isExported: boolean) {
|
|
5
16
|
const ttf = new TypeTransformer({ filePath: out_put_target, isExported })
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
} catch (error) {
|
|
11
|
-
console.error('transform error', error)
|
|
12
|
-
return { fullMethodName, error }
|
|
13
|
-
}
|
|
14
|
-
})
|
|
15
|
-
return Promise.all(tasks)
|
|
17
|
+
|
|
18
|
+
const sourceList: SourceList = executeList.map(({ data, typeName }) => ({ value: data, typeName }))
|
|
19
|
+
await ttf.transform(sourceList)
|
|
20
|
+
|
|
16
21
|
}
|
|
17
22
|
|
|
23
|
+
type TypeList = {
|
|
24
|
+
fullMethodName: string
|
|
25
|
+
typeName: string
|
|
26
|
+
}[]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 自动补全api方法返回类型
|
|
31
|
+
*
|
|
32
|
+
* @description fullMethodName 非常重要,用来匹配模块中的方法
|
|
33
|
+
* 由于 fullMethodName由 className+methodName 组成,所以如果不同模块下存在 同名类+同名方法,
|
|
34
|
+
* 会导致匹配出错,比如:将A模块下classA.methodB的类型Type_A 写到B模块下 lassA.methodB
|
|
35
|
+
*/
|
|
36
|
+
export async function completeReturnTypeToApiMethod(moduleMap: ScanModuleMap, typeList: TypeList) {
|
|
37
|
+
const p = new Project()
|
|
38
|
+
moduleMap.forEach((fullMethods, modulePath) => {
|
|
39
|
+
const sf = p.addSourceFileAtPath(modulePath)
|
|
40
|
+
fullMethods.forEach(fullMethodName => {
|
|
41
|
+
const [className, methodName] = fullMethodName.split('.')
|
|
42
|
+
const cs = sf.getClass(className)
|
|
43
|
+
const m = cs?.getMethod(methodName)
|
|
44
|
+
const oldReturnTypeText = m?.getReturnType().getText()
|
|
45
|
+
const isAsync = oldReturnTypeText?.startsWith('Promise<') || m?.isAsync()
|
|
46
|
+
|
|
47
|
+
const typeName = typeList.find(item => item.fullMethodName === fullMethodName)?.typeName
|
|
48
|
+
if (m && typeName) {
|
|
49
|
+
m?.setReturnType(isAsync ? `Promise<${typeName}>` : typeName)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
})
|
|
54
|
+
})
|
|
55
|
+
return p.save()
|
|
56
|
+
}
|
|
@@ -22,6 +22,7 @@ function inferType(value: any): string {
|
|
|
22
22
|
return "any";
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
|
+
export type SourceList = { value: any, typeName: string }[]
|
|
25
26
|
|
|
26
27
|
|
|
27
28
|
export class TypeTransformer {
|
|
@@ -35,28 +36,19 @@ export class TypeTransformer {
|
|
|
35
36
|
}
|
|
36
37
|
|
|
37
38
|
createSourceFile(filePath: string) {
|
|
38
|
-
// try {
|
|
39
|
-
// return project.addSourceFileAtPath(filePath);
|
|
40
|
-
// } catch (error) {
|
|
41
|
-
// return project.createSourceFile(filePath);
|
|
42
|
-
// }
|
|
43
39
|
return this.project.createSourceFile(filePath, '', { overwrite: true });
|
|
44
40
|
}
|
|
45
41
|
|
|
46
|
-
// 根据运行时对象生成类型定义
|
|
47
42
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
}
|
|
57
|
-
async transform(res: any, typeName: string, isAsync = true) {
|
|
58
|
-
this.generateTypeFromObject(res, typeName)
|
|
43
|
+
async transform(sourceList: SourceList, isAsync = true) {
|
|
44
|
+
this.sourceFile.addTypeAliases(
|
|
45
|
+
sourceList.map(({ value, typeName }) => ({
|
|
46
|
+
name: typeName,
|
|
47
|
+
isExported: this.isExported,
|
|
48
|
+
type: inferType(value)
|
|
49
|
+
}))
|
|
50
|
+
)
|
|
59
51
|
await this.sourceFile.save();
|
|
60
52
|
}
|
|
61
53
|
|
|
62
|
-
}
|
|
54
|
+
}
|