Skip to content

Commit 3a659f1

Browse files
JsonLee12138Json_Lee
andauthored
feat: apifox support, incremental change support, cli concurrency and timeout support, uniquekey filpath support, openapi-ts merge to openapi (#153)
* feat: cli concurrency and timeout support and uniquekey filpath support * feat: add merge rebase openapi-ts and openapi modify function name * fix: merge sort * feat: option full replacement * docs: docs modify --------- Co-authored-by: Json_Lee <[email protected]>
1 parent 911f9bd commit 3a659f1

File tree

17 files changed

+850
-99
lines changed

17 files changed

+850
-99
lines changed

.changeset/happy-foxes-sip.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'openapi-ts-request': patch
3+
---
4+
5+
feat: cli concurrency and timeout support and uniquekey filpath support

.changeset/smooth-lights-greet.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'openapi-ts-request': minor
3+
---
4+
5+
新增增量修改,方法命名规范,合并openapi-ts和openapi命令

README-en_US.md

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ based on [Swagger2/OpenAPI3/Apifox](https://swagger.io/blog/news/whats-new-in-op
1313
- react-query/vue-query
1414
- type field label
1515
- JSON Schemas
16+
- Apifox
1617

1718
docs:[use docs](https://github.com/openapi-ui/openapi-ts-request/issues/100)
1819

@@ -25,6 +26,7 @@ docs:[use docs](https://github.com/openapi-ui/openapi-ts-request/issues/100)
2526
- support filter generate result by tags
2627
- support JSON/YAML specification
2728
- support translate chinese tag name to english tag name
29+
- Support direct configuration of `apifox` `token` and `projectId` direct generation
2830

2931
## Usage
3032

@@ -181,8 +183,10 @@ $ openapi --help
181183
182184
Options:
183185
-V, --version output the version number
184-
-i, --input <string> OpenAPI specification, can be a path, url (required)
185-
-o, --output <string> output directory (required)
186+
-i, --input <string> OpenAPI specification, can be a path, url
187+
-o, --output <string> output directory
188+
-cfn, --configFileName <string> config file name
189+
-cfp, --configFilePath <string> config file path
186190
--requestLibPath <string> custom request lib path, for example: "@/request", "node-fetch" (default: "axios")
187191
--enableLogging <boolean> open the log (default: false)
188192
--priorityRule <string> priority rule, include/exclude/both (default: "include")
@@ -205,6 +209,7 @@ $ openapi --help
205209
--isOnlyGenTypeScriptType <boolean> only generate typescript type (default: false)
206210
--isCamelCase <boolean> camelCase naming of controller files and request client (default: true)
207211
--isSupportParseEnumDesc <boolean> parse enum description to generate enum label (default: false)
212+
-f, --full full replacement
208213
-h, --help display help for command
209214
```
210215

@@ -243,6 +248,8 @@ openapi -i ./spec.json -o ./apis
243248
| isCamelCase | no | boolean | true | camelCase naming of controller files and request client |
244249
| isSupportParseEnumDesc | no | boolean | false | parse enum description to generate enum label, format example: `UserRole:User(Normal User)=0,Agent(Agent)=1,Admin(Administrator)=2` |
245250
| hook | no | [Custom Hook](#Custom-Hook) | - | custom hook |
251+
| apifoxConfig | no | [Apifox Config](#Apifox-Config) | - | apifox configs |
252+
| full | no | boolean | false | full replacement |
246253

247254
## Custom Hook
248255

@@ -255,6 +262,17 @@ openapi -i ./spec.json -o ./apis
255262
| customType | ({<br>schemaObject: SchemaObject \| ReferenceObject,<br>namespace: string,<br>originGetType:(schemaObject: SchemaObject \| ReferenceObject, namespace: string, schemas?: ComponentsObject['schemas']) => string,<br>schemas?: ComponentsObject['schemas'],<br>}) => string | custom type <br> _returning a non-string will use the default method to get the type_ |
256263
| customFileNames | (<br>operationObject: OperationObject,<br>apiPath: string,<br>apiMethod: string,<br>) => string[] | custom generate request client controller file name, can return multiple: generate multiple files. <br> _if the return value is empty, the default getFileNames is used_ |
257264

265+
## Apifox-Config
266+
267+
| attribute | type | description | required |
268+
| --- | --- | --- | --- |
269+
| projectId | string | project id | true |
270+
| local | string | language(default:zh-CN) | false |
271+
| apifoxVersion | string | default: 2024-03-28, [current apifox version](https://api.apifox.com/v1/versions) | false |
272+
| includeTags | \* or string[] | default: \* | false |
273+
| excludeTags | string[] | default: [] | false |
274+
| apifoxToken | string | [get](https://docs.apifox.com/doc-5723694) | true |
275+
258276
## JSON Schemas
259277

260278
- default generate JSON Schemas based on [components.schemas](https://spec.openapis.org/oas/latest.html#components-object), JSON Schemas corresponding to [paths](https://spec.openapis.org/oas/latest.html#paths-object) currently need to be parsed by yourself
@@ -275,6 +293,33 @@ currently using [mockjs](http://mockjs.com) to generate mock data, the mocks fil
275293

276294
it is recommended to use a custom request function to adapt to uniapp. you can also use the `@uni-helper/axios-adapter` adapter. for details, see [【use docs 2.2】](https://github.com/openapi-ui/openapi-ts-request/issues/100)
277295

296+
## Notes on Upgrading Older Versions
297+
298+
- Current naming convention changes
299+
- Incremental changes have been made to the current version and will not affect previous versions.
300+
- The `openapi-ts` command can be deprecated to use `openapi`
301+
302+
### The configuration follows the naming convention of the old version as follows
303+
304+
```typescript
305+
import type { APIDataType } from 'openapi-ts-request/dist/generator/type';
306+
import {
307+
genDefaultFunctionName,
308+
resolveFunctionName,
309+
stripDot,
310+
} from 'openapi-ts-request/dist/generator/util';
311+
312+
export default {
313+
hook: {
314+
customFunctionName(data: APIDataType, prefix: string) {
315+
if (data.operationId)
316+
return resolveFunctionName(stripDot(data.operationId), data.method);
317+
return data.method + genDefaultFunctionName(data.path, prefix);
318+
},
319+
},
320+
};
321+
```
322+
278323
## Contribute
279324

280325
### Development Environment

README.md

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
<!-- TODO:需要修改文档, 添加参数, 添加apifox的配置支持 -->
2+
13
## 介绍
24

35
[![GitHub Repo stars](https://img.shields.io/github/stars/openapi-ui/openapi-ts-request?style=social)](https://github.com/openapi-ui/openapi-ts-request) [![npm (scoped)](https://img.shields.io/npm/v/openapi-ts-request)](https://www.npmjs.com/package/openapi-ts-request) ![GitHub tag](https://img.shields.io/github/v/tag/openapi-ui/openapi-ts-request?include_prereleases)
@@ -13,6 +15,7 @@
1315
- react-query/vue-query
1416
- 类型字段翻译
1517
- JSON Schemas
18+
- Apifox
1619

1720
文档:[使用手册](https://github.com/openapi-ui/openapi-ts-request/issues/100)
1821

@@ -25,6 +28,7 @@
2528
- 支持通过 tags 过滤生成结果
2629
- 支持 JSON/YAML 定义文件
2730
- 支持将中文 tag 名称翻译为英文 tag 名称
31+
- 支持直接配置`apifox``token``projectId`直接生成
2832

2933
## 使用
3034

@@ -181,8 +185,10 @@ $ openapi --help
181185
182186
Options:
183187
-V, --version output the version number
184-
-i, --input <string> OpenAPI specification, can be a path, url (required)
185-
-o, --output <string> output directory (required)
188+
-i, --input <string> OpenAPI specification, can be a path, url
189+
-o, --output <string> output directory
190+
-cfn, --configFileName <string> config file name
191+
-cfp, --configFilePath <string> config file path
186192
--requestLibPath <string> custom request lib path, for example: "@/request", "node-fetch" (default: "axios")
187193
--enableLogging <boolean> open the log (default: false)
188194
--priorityRule <string> priority rule, include/exclude/both (default: "include")
@@ -205,6 +211,7 @@ $ openapi --help
205211
--isOnlyGenTypeScriptType <boolean> only generate typescript type (default: false)
206212
--isCamelCase <boolean> camelCase naming of controller files and request client (default: true)
207213
--isSupportParseEnumDesc <boolean> parse enum description to generate enum label (default: false)
214+
-f, --full full replacement
208215
-h, --help display help for command
209216
```
210217

@@ -243,6 +250,8 @@ openapi --i ./spec.json --o ./apis
243250
| isCamelCase || boolean | true | 小驼峰命名文件和请求函数 |
244251
| isSupportParseEnumDesc || boolean | false | 解析枚举描述生成枚举标签,格式参考:`系统用户角色:User(普通用户)=0,Agent(经纪人)=1,Admin(管理员)=2` |
245252
| hook || [Custom Hook](#Custom-Hook) | - | 自定义 hook |
253+
| apifoxConfig || [Apifox Config](#Apifox-Config) | - | apifox 配置 |
254+
| full || boolean | false | 是否全量替换 |
246255

247256
## 自定义 Hook
248257

@@ -255,6 +264,17 @@ openapi --i ./spec.json --o ./apis
255264
| customType | ({<br>schemaObject: SchemaObject \| ReferenceObject,<br>namespace: string,<br>originGetType:(schemaObject: SchemaObject \| ReferenceObject, namespace: string, schemas?: ComponentsObject['schemas']) => string,<br>schemas?: ComponentsObject['schemas'],<br>}) => string | 自定义类型 <br> _返回非字符串将使用默认方法获取type_ |
256265
| customFileNames | (<br>operationObject: OperationObject,<br>apiPath: string,<br>apiMethod: string,<br>) => string[] | 自定义生成的请求客户端文件名称,可以返回多个文件名称的数组(表示生成多个文件). <br> _返回为空,则使用默认的方法获取_ |
257266

267+
## Apifox-Config
268+
269+
| 属性 | 类型 | 说明 | 必填 |
270+
| --- | --- | --- | --- |
271+
| projectId | string | 项目id | true |
272+
| local | string | 语言(默认:zh-CN) | false |
273+
| apifoxVersion | string | 默认: 2024-03-28, [获取当前版本](https://api.apifox.com/v1/versions) | false |
274+
| includeTags | \* 或 string[] | 默认: \* | false |
275+
| excludeTags | string[] | 默认: [] | false |
276+
| apifoxToken | string | [获取](https://docs.apifox.com/doc-5723694) | true |
277+
258278
## JSON Schemas
259279

260280
- 默认生成 [components.schemas](https://spec.openapis.org/oas/latest.html#components-object) 下面的 JSON Schemas,[paths](https://spec.openapis.org/oas/latest.html#paths-object) 对应的 JSON Schemas 目前需自行解析
@@ -275,6 +295,33 @@ export declare function patchSchema<T extends object>(
275295

276296
适配 uniapp 推荐采用自定义 request 函数的方式,你也可以使用 `@uni-helper/axios-adapter` 适配器,详情见 [【使用手册 2.2】](https://github.com/openapi-ui/openapi-ts-request/issues/100)
277297

298+
## 旧版本升级注意事项
299+
300+
- 当前命名规范修改
301+
- 当前版本已完成增量修改, 不会影响以前
302+
- 可以弃用`openapi-ts`命令, 直接使用`openapi`
303+
304+
### 沿用旧版本命名规范配置如下
305+
306+
```typescript
307+
import type { APIDataType } from 'openapi-ts-request/dist/generator/type';
308+
import {
309+
genDefaultFunctionName,
310+
resolveFunctionName,
311+
stripDot,
312+
} from 'openapi-ts-request/dist/generator/util';
313+
314+
export default {
315+
hook: {
316+
customFunctionName(data: APIDataType, prefix: string) {
317+
if (data.operationId)
318+
return resolveFunctionName(stripDot(data.operationId), data.method);
319+
return data.method + genDefaultFunctionName(data.path, prefix);
320+
},
321+
},
322+
};
323+
```
324+
278325
## 贡献
279326

280327
### 环境要求

package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
"lint": "eslint ./src --report-unused-disable-directives --max-warnings=0",
3232
"lint:fix": "eslint ./src --report-unused-disable-directives --max-warnings=0 --fix",
3333
"test": "rm -rf ./test/apis/ ./test/mocks && npm run build && cd ./test && node ./test.js && cd ..",
34+
"test:new": "npm run build && cd ./test && node ./test.js && cd ..",
3435
"test:windows": "rimraf ./test/apis/ ./test/mocks && npm run build && cd ./test && node ./test.js && cd ..",
3536
"prepare": "husky",
3637
"openapi-ts-request": "openapi-ts"
@@ -56,6 +57,7 @@
5657
"rimraf": "^6.0.1",
5758
"swagger2openapi": "^7.0.8",
5859
"tiny-pinyin": "^1.3.2",
60+
"ts-morph": "^25.0.1",
5961
"tslib": "^2.6.3"
6062
},
6163
"devDependencies": {

pnpm-lock.yaml

Lines changed: 30 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/bin/cli.ts

Lines changed: 37 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,53 @@
11
#!/usr/bin/env node
22
import chalk from 'chalk';
3-
import { cosmiconfigSync } from 'cosmiconfig';
4-
import { TypeScriptLoaderSync } from 'cosmiconfig-typescript-loader';
3+
import { program } from 'commander';
54

65
import { GenerateServiceProps, generateService } from '../index';
6+
import { readConfig } from '../readConfig';
77

8-
const explorerSync = cosmiconfigSync('openapi-ts-request', {
9-
loaders: {
10-
'.ts': TypeScriptLoaderSync(),
11-
},
12-
});
8+
program
9+
.option('-u, --unique-key <uniqueKey>', '唯一标识 uniqueKey')
10+
.option('-fn, --fileName <fileName>', '文件名 fileName')
11+
.option('-fp, --filePath <filePath>', '文件路径 filePath');
1312

14-
const config = explorerSync.search()?.config as
15-
| GenerateServiceProps
16-
| GenerateServiceProps[];
13+
program.parse();
14+
const options = program.opts();
1715

1816
async function run() {
17+
const config = await readConfig<
18+
GenerateServiceProps | GenerateServiceProps[]
19+
>({
20+
fallbackName: 'openapi-ts-request',
21+
filePath: options.filePath as string,
22+
fileName: options.fileName as undefined,
23+
});
24+
1925
try {
26+
const tasks = [];
2027
if (config) {
21-
const configs: GenerateServiceProps[] = Array.isArray(config)
28+
let configs: GenerateServiceProps[] = Array.isArray(config)
2229
? config
2330
: [config];
24-
31+
if (options.uniqueKey) {
32+
configs = configs.filter(
33+
(config) => config.uniqueKey === options.uniqueKey
34+
);
35+
}
2536
for (const config of configs) {
26-
await generateService(config);
37+
tasks.push(generateService(config));
38+
}
39+
const results = await Promise.allSettled(tasks);
40+
const errors: PromiseRejectedResult[] = results.filter(
41+
(result) => result.status === 'rejected'
42+
);
43+
let errorMsg = '';
44+
for (let i = 0; i < errors.length; i++) {
45+
const error = errors[i];
46+
const cnf = configs[i];
47+
errorMsg += `${cnf.uniqueKey}${cnf.uniqueKey && ':'}${error.reason}\n`;
48+
}
49+
if (errorMsg) {
50+
throw new Error(errorMsg);
2751
}
2852
} else {
2953
throw new Error('config is not found');

0 commit comments

Comments
 (0)