Skip to content

Commit e932466

Browse files
perf: perf docs and code style
1 parent eef0119 commit e932466

File tree

9 files changed

+66
-41
lines changed

9 files changed

+66
-41
lines changed

.changeset/smooth-lights-greet.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
'openapi-ts-request': minor
33
---
44

5-
新增增量修改,方法命名规范,合并openapi-ts和openapi命令
5+
feat: 新增增量修改,方法命名规范,合并openapi-ts和openapi命令

README-en_US.md

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +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
16+
- Apifox Config
1717

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

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

3131
## Usage
3232

@@ -187,7 +187,9 @@ $ openapi --help
187187
-o, --output <string> output directory
188188
-cfn, --configFileName <string> config file name
189189
-cfp, --configFilePath <string> config file path
190+
-u, --uniqueKey <string> unique key
190191
--requestLibPath <string> custom request lib path, for example: "@/request", "node-fetch" (default: "axios")
192+
-f, --full <boolean> full replacement (default: true)
191193
--enableLogging <boolean> open the log (default: false)
192194
--priorityRule <string> priority rule, include/exclude/both (default: "include")
193195
--includeTags <(string|RegExp)[]> generate code from include tags
@@ -209,7 +211,6 @@ $ openapi --help
209211
--isOnlyGenTypeScriptType <boolean> only generate typescript type (default: false)
210212
--isCamelCase <boolean> camelCase naming of controller files and request client (default: true)
211213
--isSupportParseEnumDesc <boolean> parse enum description to generate enum label (default: false)
212-
-f, --full full replacement
213214
-h, --help display help for command
214215
```
215216

@@ -226,6 +227,7 @@ openapi -i ./spec.json -o ./apis
226227
| schemaPath | yes | string | - | Swagger2/OpenAPI3 URL |
227228
| serversPath | no | string | './src/apis' | the folder path for the run results |
228229
| requestLibPath | no | string | 'axios' | custom request lib path, for example: '@/request', 'node-fetch' |
230+
| full | no | boolean | true | full replacement |
229231
| enableLogging | no | boolean | false | open the log |
230232
| priorityRule | no | string | 'include' | priority rule, include/exclude/both |
231233
| includeTags | no | (string\|RegExp)[] | - | generate code from include tags, priorityRule=include required |
@@ -242,14 +244,13 @@ openapi -i ./spec.json -o ./apis
242244
| isGenJsonSchemas | no | boolean | false | generate JSON Schemas |
243245
| mockFolder | no | string | - | mock file path, for example: './mocks' |
244246
| authorization | no | string | - | docs authorization |
247+
| apifoxConfig | no | [Apifox Config](#Apifox-Config) | - | apifox configs |
245248
| nullable | no | boolean | false | null instead of optional |
246249
| isTranslateToEnglishTag | no | boolean | false | translate chinese tag name to english tag name |
247250
| isOnlyGenTypeScriptType | no | boolean | false | only generate typescript type |
248251
| isCamelCase | no | boolean | true | camelCase naming of controller files and request client |
249252
| isSupportParseEnumDesc | no | boolean | false | parse enum description to generate enum label, format example: `UserRole:User(Normal User)=0,Agent(Agent)=1,Admin(Administrator)=2` |
250253
| hook | no | [Custom Hook](#Custom-Hook) | - | custom hook |
251-
| apifoxConfig | no | [Apifox Config](#Apifox-Config) | - | apifox configs |
252-
| full | no | boolean | false | full replacement |
253254

254255
## Custom Hook
255256

README.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
- react-query/vue-query
1616
- 类型字段翻译
1717
- JSON Schemas
18-
- Apifox
18+
- Apifox Config
1919

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

@@ -189,7 +189,9 @@ $ openapi --help
189189
-o, --output <string> output directory
190190
-cfn, --configFileName <string> config file name
191191
-cfp, --configFilePath <string> config file path
192+
-u, --uniqueKey <string> unique key
192193
--requestLibPath <string> custom request lib path, for example: "@/request", "node-fetch" (default: "axios")
194+
-f, --full <boolean> full replacement (default: true)
193195
--enableLogging <boolean> open the log (default: false)
194196
--priorityRule <string> priority rule, include/exclude/both (default: "include")
195197
--includeTags <(string|RegExp)[]> generate code from include tags
@@ -211,7 +213,6 @@ $ openapi --help
211213
--isOnlyGenTypeScriptType <boolean> only generate typescript type (default: false)
212214
--isCamelCase <boolean> camelCase naming of controller files and request client (default: true)
213215
--isSupportParseEnumDesc <boolean> parse enum description to generate enum label (default: false)
214-
-f, --full full replacement
215216
-h, --help display help for command
216217
```
217218

@@ -228,6 +229,7 @@ openapi --i ./spec.json --o ./apis
228229
| schemaPath || string | - | Swagger2/OpenAPI3 地址 |
229230
| serversPath || string | './src/apis' | 运行结果文件夹路径 |
230231
| requestLibPath || string | 'axios' | 自定义请求方法路径,例如:'@/request'、'node-fetch' |
232+
| full || boolean | true | 是否全量替换 |
231233
| enableLogging || boolean | false | 是否开启日志 |
232234
| priorityRule || string | 'include' | 模式规则,可选include/exclude/both |
233235
| includeTags || (string\|RegExp)[] | - | 根据指定的 tags 生成代码, priorityRule=include则必填 |
@@ -244,14 +246,13 @@ openapi --i ./spec.json --o ./apis
244246
| isGenJsonSchemas || boolean | false | 是否生成 JSON Schemas |
245247
| mockFolder || string | - | mock文件路径,例如:'./mocks' |
246248
| authorization || string | - | 文档权限凭证 |
249+
| apifoxConfig || [Apifox Config](#Apifox-Config) | - | apifox 配置 |
247250
| nullable || boolean | false | 使用 null 代替可选 |
248251
| isTranslateToEnglishTag || boolean | false | 将中文 tag 名称翻译成英文 tag 名称 |
249252
| isOnlyGenTypeScriptType || boolean | false | 仅生成 typescript 类型 |
250253
| isCamelCase || boolean | true | 小驼峰命名文件和请求函数 |
251254
| isSupportParseEnumDesc || boolean | false | 解析枚举描述生成枚举标签,格式参考:`系统用户角色:User(普通用户)=0,Agent(经纪人)=1,Admin(管理员)=2` |
252255
| hook || [Custom Hook](#Custom-Hook) | - | 自定义 hook |
253-
| apifoxConfig || [Apifox Config](#Apifox-Config) | - | apifox 配置 |
254-
| full || boolean | false | 是否全量替换 |
255256

256257
## 自定义 Hook
257258

src/bin/cli.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ import { GenerateServiceProps, generateService } from '../index';
66
import { readConfig } from '../readConfig';
77

88
program
9-
.option('-u, --unique-key <uniqueKey>', '唯一标识 uniqueKey')
10-
.option('-fn, --fileName <fileName>', '文件名 fileName')
11-
.option('-fp, --filePath <filePath>', '文件路径 filePath');
9+
.option('-cfn, --configFileName <string>', 'config file name')
10+
.option('-cfp, --configFilePath <string>', 'config file path')
11+
.option('-u, --uniqueKey <string>', 'unique key');
1212

1313
program.parse();
1414
const options = program.opts();
@@ -28,24 +28,29 @@ async function run() {
2828
let configs: GenerateServiceProps[] = Array.isArray(config)
2929
? config
3030
: [config];
31+
3132
if (options.uniqueKey) {
3233
configs = configs.filter(
3334
(config) => config.uniqueKey === options.uniqueKey
3435
);
3536
}
37+
3638
for (const config of configs) {
3739
tasks.push(generateService(config));
3840
}
41+
3942
const results = await Promise.allSettled(tasks);
4043
const errors: PromiseRejectedResult[] = results.filter(
4144
(result) => result.status === 'rejected'
4245
);
4346
let errorMsg = '';
47+
4448
for (let i = 0; i < errors.length; i++) {
4549
const error = errors[i];
4650
const cnf = configs[i];
4751
errorMsg += `${cnf.uniqueKey}${cnf.uniqueKey && ':'}${error.reason}\n`;
4852
}
53+
4954
if (errorMsg) {
5055
throw new Error(errorMsg);
5156
}

src/bin/openapi.ts

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,19 +13,16 @@ const params = program
1313
.name('openapi')
1414
.usage('[options]')
1515
.version(pkg.version)
16-
// .requiredOption(
17-
// '-i, --input <string>',
18-
// 'OpenAPI specification, can be a path, url (required)'
19-
// )
20-
// .requiredOption('-o, --output <string>', 'output directory (required)')
2116
.option('-i, --input <string>', 'OpenAPI specification, can be a path, url')
2217
.option('-o, --output <string>', 'output directory')
23-
.option('-cfn, --configFileName <configFileName>', 'config file name')
24-
.option('-cfp, --configFilePath <configFilePath>', 'config file path')
18+
.option('-cfn, --configFileName <string>', 'config file name')
19+
.option('-cfp, --configFilePath <string>', 'config file path')
20+
.option('-u, --uniqueKey <string>', 'unique key')
2521
.option(
2622
'--requestLibPath <string>',
2723
'custom request lib path, for example: "@/request", "node-fetch" (default: "axios")'
2824
)
25+
.option('-f, --full <boolean>', 'full replacement', true)
2926
.option('--enableLogging <boolean>', 'open the log', false)
3027
.option(
3128
'--priorityRule <string>',
@@ -94,8 +91,6 @@ const params = program
9491
'parse enum description to generate enum label',
9592
false
9693
)
97-
.option('-u, --unique-key <uniqueKey>', 'unique key')
98-
.option('-f, --full <boolean>', 'full replacement', false)
9994
.parse(process.argv)
10095
.opts();
10196

@@ -116,6 +111,7 @@ const baseGenerate = (_params_: OptionValues): GenerateServiceProps => {
116111
schemaPath: input,
117112
serversPath: output,
118113
requestLibPath: _params_.requestLibPath as string,
114+
full: JSON.parse(_params_.full as string) === true,
119115
enableLogging: JSON.parse(_params_.enableLogging as string) === true,
120116
priorityRule: _params_.priorityRule as IPriorityRule,
121117
includeTags: _params_.includeTags as string[],
@@ -141,6 +137,7 @@ const baseGenerate = (_params_: OptionValues): GenerateServiceProps => {
141137
isSupportParseEnumDesc:
142138
JSON.parse(_params_.isSupportParseEnumDesc as string) === true,
143139
};
140+
144141
return options;
145142
};
146143

@@ -155,33 +152,40 @@ async function run() {
155152
);
156153
process.exit(0);
157154
}
155+
158156
const cnf = await readConfig<GenerateServiceProps | GenerateServiceProps[]>({
159157
fallbackName: 'openapi-ts-request',
160158
filePath: params.configFilePath as string,
161159
fileName: params.configFileName as undefined,
162160
});
161+
163162
try {
164163
if (cnf) {
165164
const tasks = [];
166165
let configs: GenerateServiceProps[] = Array.isArray(cnf) ? cnf : [cnf];
166+
167167
if (params.uniqueKey) {
168168
configs = configs.filter(
169169
(config) => config.uniqueKey === params.uniqueKey
170170
);
171171
}
172+
172173
for (const config of configs) {
173174
tasks.push(generateService(config));
174175
}
176+
175177
const results = await Promise.allSettled(tasks);
176178
const errors: PromiseRejectedResult[] = results.filter(
177179
(result) => result.status === 'rejected'
178180
);
179181
let errorMsg = '';
182+
180183
for (let i = 0; i < errors.length; i++) {
181184
const error = errors[i];
182185
const cnf = configs[i];
183186
errorMsg += `${cnf.uniqueKey}${cnf.uniqueKey && ':'}${error.reason}\n`;
184187
}
188+
185189
if (errorMsg) {
186190
logError(errorMsg);
187191
process.exit(1);
@@ -193,6 +197,7 @@ async function run() {
193197
);
194198
process.exit(1);
195199
}
200+
196201
const options = baseGenerate(params);
197202
await generateService(
198203
pickBy(

src/generator/serviceGenarator.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -781,6 +781,7 @@ export default class ServiceGenerator {
781781
...params,
782782
});
783783
let mergerProps: MergeOption = {} as MergeOption;
784+
784785
if (existsSync(destPath)) {
785786
mergerProps = {
786787
srcPath: destPath,
@@ -790,10 +791,13 @@ export default class ServiceGenerator {
790791
source: '',
791792
};
792793
}
794+
793795
if (this.config.full) {
794796
return writeFile(this.config.serversPath, fileName, destCode);
795797
}
798+
796799
const merger = new Merger(mergerProps);
800+
797801
return writeFile(
798802
this.config.serversPath,
799803
fileName,

src/index.ts

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,10 @@ export type GenerateServiceProps = {
3939
* 方式二: import request from '@/request';
4040
*/
4141
requestLibPath?: string;
42+
/**
43+
* 是否全量替换, 默认: true, 如果为false, 则进行增量替换
44+
*/
45+
full?: boolean;
4246
/**
4347
* 开启日志
4448
*/
@@ -117,6 +121,10 @@ export type GenerateServiceProps = {
117121
* 文档权限凭证
118122
*/
119123
authorization?: string;
124+
/**
125+
* apifox 配置
126+
*/
127+
apifoxConfig?: GetSchemaByApifoxProps;
120128
/**
121129
* 默认为false,true时使用null代替可选值
122130
*/
@@ -146,9 +154,13 @@ export type GenerateServiceProps = {
146154
*/
147155
templatesFolder?: string;
148156
/**
149-
* apifox 配置
157+
* 请求超时时间
150158
*/
151-
apifoxConfig?: GetSchemaByApifoxProps;
159+
timeout?: number;
160+
/**
161+
* 多网关唯一标识
162+
*/
163+
uniqueKey?: string;
152164
/**
153165
* 自定义 hook
154166
*/
@@ -222,18 +234,6 @@ export type GenerateServiceProps = {
222234
apiMethod: string
223235
) => string[] | null;
224236
};
225-
/**
226-
* 请求超时时间
227-
*/
228-
timeout?: number;
229-
/**
230-
* 唯一标识
231-
*/
232-
uniqueKey?: string;
233-
/**
234-
* 是否全量替换
235-
*/
236-
full?: boolean;
237237
};
238238

239239
export async function generateService({
@@ -248,16 +248,17 @@ export async function generateService({
248248
timeout = 60_000,
249249
reactQueryMode = ReactQueryMode.react,
250250
apifoxConfig,
251-
full,
252251
...rest
253252
}: GenerateServiceProps) {
254253
if (!schemaPath && !apifoxConfig) {
255254
return;
256255
}
256+
257257
let openAPI: OpenAPIObject | null = null;
258258
if (apifoxConfig) {
259259
openAPI = (await getOpenAPIConfigByApifox(apifoxConfig)) as OpenAPIObject;
260260
}
261+
261262
if (schemaPath) {
262263
openAPI = (await getOpenAPIConfig(
263264
schemaPath,
@@ -275,7 +276,6 @@ export async function generateService({
275276
}
276277

277278
const requestImportStatement = getImportStatement(requestLibPath);
278-
279279
const serviceGenerator = new ServiceGenerator(
280280
{
281281
schemaPath,
@@ -306,7 +306,7 @@ export async function generateService({
306306
isOnlyGenTypeScriptType: false,
307307
isCamelCase: true,
308308
isSupportParseEnumDesc: false,
309-
full,
309+
full: true,
310310
...rest,
311311
},
312312
openAPI

src/readConfig.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@ export const readConfig = async <T = unknown>({
1010
}: ReadConfigOptions): Promise<T | undefined> => {
1111
try {
1212
let _fileName_: string | undefined = fileName;
13+
1314
if (!_fileName_ && !filePath) {
1415
_fileName_ = fallbackName;
1516
}
17+
1618
const explorerSync = cosmiconfigSync(_fileName_ || fallbackName, {
1719
loaders: {
1820
'.ts': TypeScriptLoader(),

0 commit comments

Comments
 (0)