Skip to content

Commit 2060103

Browse files
committed
refactor(generator): 重构生成器相关代码
- 将 modules 重命名为 documents,更准确地反映其含义 - 优化 Generator 类的结构和逻辑 - 更新 Logger 类的输出格式 - 调整 Printer 类,增加 nodeName 属性 - 更新相关类型定义
1 parent 63cd624 commit 2060103

File tree

6 files changed

+47
-35
lines changed

6 files changed

+47
-35
lines changed

src/cli.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,8 @@ const { defineConfig } = require('openapi-axios');
4343
* @ref https://github.com/FrontEndDev-org/openapi-axios
4444
*/
4545
module.exports = defineConfig({
46-
modules: {
47-
'.petStore3': 'https://petstore3.swagger.io/api/v3/openapi.json'
46+
documents: {
47+
'petStore3': 'https://petstore3.swagger.io/api/v3/openapi.json'
4848
},
4949
});`.trim()}\n`,
5050
);

src/generator/Generator.ts

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ export class Generator extends Emitter<GeneratorEmits> {
2222
static defaults: StrictGeneratorOptions = {
2323
cwd: process.cwd(),
2424
dest: '/src/apis',
25-
modules: {},
25+
documents: {},
2626
};
2727

2828
options: StrictGeneratorOptions;
@@ -32,7 +32,7 @@ export class Generator extends Emitter<GeneratorEmits> {
3232
}
3333

3434
async generate() {
35-
const entries = Object.entries(this.options.modules);
35+
const entries = Object.entries(this.options.documents);
3636
const count = entries.length;
3737
const payload: GeneratorPayload = { count };
3838
this.emit('start', payload);
@@ -41,7 +41,7 @@ export class Generator extends Emitter<GeneratorEmits> {
4141
let index = 0;
4242
for (const [name, module] of entries) {
4343
const openAPI: OpenAPIOptions = isString(module) ? { document: module } : module;
44-
await this.#generateOpenAPI(index, count, name, openAPI);
44+
await this.#generateOpenAPI({ index, count, name }, openAPI);
4545
index++;
4646
}
4747
}
@@ -54,12 +54,12 @@ export class Generator extends Emitter<GeneratorEmits> {
5454
this.emit('end', payload);
5555
}
5656

57-
async #generateOpenAPI(index: number, count: number, module: string, openAPIOptions: OpenAPIOptions) {
57+
async #generateOpenAPI({ index, count, name }: { index: number; count: number; name: string }, openAPIOptions: OpenAPIOptions) {
5858
const { cwd, dest, ...globalPrinter } = this.options;
59-
const { document, fileName = `${module}.ts`, ...scopePrinter } = openAPIOptions;
59+
const { document, fileName = `${name}.ts`, ...scopePrinter } = openAPIOptions;
6060
const mainFile = path.join(cwd, dest, fileName);
61-
const typeFile = path.join(cwd, dest, fileName.replace(/\.ts$/, '.type.ts'));
62-
const schemaFile = path.join(cwd, dest, fileName.replace(/\.ts$/, '.schema.ts'));
61+
const typeFile = mainFile.replace(/\.ts$/, '.type.ts');
62+
const schemaFile = mainFile.replace(/\.ts$/, '.schema.ts');
6363

6464
// 1. 参数合并
6565
const printerOptions = Object.assign({}, globalPrinter, scopePrinter);
@@ -69,11 +69,11 @@ export class Generator extends Emitter<GeneratorEmits> {
6969
dest,
7070
...printerOptions,
7171
};
72-
const makePayload = (step: GeneratingStage): GeneratingPayload => ({
72+
const makePayload = (stage: GeneratingStage): GeneratingPayload => ({
7373
index,
7474
count,
75-
module,
76-
stage: step,
75+
name,
76+
stage,
7777
options,
7878
file: mainFile,
7979
});
@@ -87,7 +87,7 @@ export class Generator extends Emitter<GeneratorEmits> {
8787
// 3. 输出
8888
this.emit('process', makePayload('printing'));
8989
const printer = new Printer(openAPIV3Document, printerOptions);
90-
const { type, main, schema } = printer.print({ module, cwd, mainFile, typeFile, schemaFile });
90+
const { type, main, schema } = printer.print({ document: name, cwd, mainFile, typeFile, schemaFile });
9191

9292
// 4. 写入
9393
this.emit('process', makePayload('writing'));

src/generator/Logger.ts

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,45 @@
11
/* eslint-disable no-console */
2-
import type { GeneratorEmits } from './types';
2+
import type { GeneratingStage, GeneratorEmits } from './types';
33
import path from 'node:path';
44
import chalk from 'chalk';
55

6+
const stateOrders: Record<GeneratingStage, number> = {
7+
reading: 1,
8+
printing: 2,
9+
writing: 3,
10+
generated: 4,
11+
};
12+
613
export class Logger {
714
pipeStartEvent(...[payload]: GeneratorEmits['start']) {
8-
console.log(chalk.greenBright('▶'), `即将处理 ${payload.count} 个 openAPI 文档`);
15+
console.log(chalk.magenta('▶'), `即将处理 ${payload.count} 个 openAPI 文档`);
916
}
1017

1118
pipeProcessEvent(...[payload]: GeneratorEmits['process']) {
1219
const width = payload.count.toString().length;
1320
const step = (payload.index + 1).toString().padStart(width, '0');
21+
const order = stateOrders[payload.stage];
1422

1523
console.log(
16-
chalk.cyanBright('▷'),
17-
chalk.yellowBright(`${step}/${payload.count}`),
18-
payload.module,
24+
chalk.magenta('▷'),
25+
chalk.yellow(`[${step}/${payload.count}]`),
26+
chalk.cyan(`<${payload.name}>`),
1927
payload.stage,
20-
payload.stage === 'generated' ? path.relative(payload.options.cwd, payload.file) : '',
28+
chalk.green(payload.stage === 'generated' ? path.relative(payload.options.cwd, payload.file) : ''),
2129
);
2230
}
2331

2432
pipeEndEvent(...[payload]: GeneratorEmits['end']) {
25-
console.log(chalk.greenBright('■'), '处理完成');
33+
console.log(chalk.magenta('■'), chalk.green('处理完成'));
2634
}
2735

2836
pipeErrorEvent(...[err]: GeneratorEmits['error']) {
29-
console.log(chalk.redBright('●'), '处理失败');
30-
console.log(chalk.redBright(err.message));
37+
console.log(chalk.magenta('●'), '处理失败');
38+
console.log(chalk.red(err.message));
3139
}
3240

3341
pipeConfigError(err: Error) {
34-
console.log(chalk.redBright('○'), '配置错误');
35-
console.log(chalk.redBright(err.message));
42+
console.log(chalk.magenta('○'), '配置错误');
43+
console.log(chalk.red(err.message));
3644
}
3745
}

src/generator/types.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,9 @@ export type GeneratorOptions = PrinterOptions & {
3535
prettierOptions?: Options;
3636

3737
/**
38-
* openapi 模块配置
38+
* openapi 文档配置
3939
*/
40-
modules: Record<string, OpenAPIOptions | string>;
40+
documents: Record<string, OpenAPIOptions | string>;
4141
};
4242
export type StrictGeneratorOptions = RequiredWith<GeneratorOptions, 'cwd' | 'dest'>;
4343

@@ -50,7 +50,7 @@ export interface GeneratorPayload {
5050
export interface GeneratingPayload {
5151
index: number;
5252
count: number;
53-
module: string;
53+
name: string;
5454
stage: GeneratingStage;
5555
options: GeneratingOptions;
5656
file: string;

src/printer/index.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ type WithId<T> = T & {
6565
nodeId: string;
6666
namedId?: string;
6767
};
68-
type SchemaInfo = WithId<{ position: 'root' | 'anchor'; schema: OpenApiLatest_Schema; typeName: string }>;
68+
type SchemaInfo = WithId<{ position: 'root' | 'anchor'; schema: OpenApiLatest_Schema; typeName: string; nodeName: string }>;
6969
type RequestBodyInfo = WithId<{ requestBody: OpenApiLatest_Request }>;
7070
type ParameterInfo = WithId<{ parameter: OpenApiLatest_Parameter }>;
7171
type ResponseInfo = WithId<{ response: OpenApiLatest_Response }>;
@@ -147,6 +147,7 @@ export class Printer {
147147
schema,
148148
nodeId,
149149
namedId,
150+
nodeName: name,
150151
};
151152
this.#tryRegisterAnchors({ namedId, nodeId, typeName }, schema);
152153

@@ -238,6 +239,7 @@ export class Printer {
238239
namedId: anchorNamedId,
239240
typeName: anchorTypeName,
240241
schema,
242+
nodeName: anchorId,
241243
};
242244

243245
this.named.setRefType(anchorId, anchorTypeName);
@@ -353,10 +355,11 @@ export class Printer {
353355
} = this.document.info;
354356
const { externalDocs } = this.document;
355357
const { name, email, url } = contact || {};
358+
356359
const jsDoc = new JsDoc();
357-
const { module } = this.configs;
358-
if (module)
359-
jsDoc.addComments({ module });
360+
const { document } = this.configs;
361+
document && jsDoc.addComments({ document });
362+
360363
const extDoc = JsDoc.printExternalDoc(externalDocs);
361364
jsDoc.addComments({
362365
title,
@@ -413,14 +416,15 @@ export class Printer {
413416
}
414417

415418
#printSchema(
416-
{ schema, nodeId, namedId, typeName }: SchemaInfo,
419+
{ schema, nodeId, nodeName, typeName }: SchemaInfo,
417420
) {
418421
if (isUndefined(typeName)) {
419422
throw new Error(`未发现 schema 引用:${nodeId}`);
420423
}
421424

422425
const { comments, type } = this.schemata.print(schema);
423426
const jsDoc = new JsDoc();
427+
jsDoc.addComments({ name: nodeName });
424428
jsDoc.addComments(comments);
425429
this.schemaVars.set(typeName, {
426430
position: 'component',
@@ -578,7 +582,7 @@ export class Printer {
578582

579583
const jsDoc = new JsDoc(this.document.tags);
580584
const comments = JsDoc.fromOperation(operation);
581-
const { module } = this.configs;
585+
const { document: module } = this.configs;
582586

583587
if (module)
584588
jsDoc.addComments({ module });

src/printer/types.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,9 +119,9 @@ export interface PrinterOptions {
119119

120120
export interface PrinterConfigs {
121121
/**
122-
* 表明当前 API 所在的模块
122+
* 文档名称
123123
*/
124-
module?: string;
124+
document?: string;
125125

126126
/**
127127
* file cwd

0 commit comments

Comments
 (0)