forked from zhang740/openapi-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
129 lines (112 loc) · 3.31 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import * as fs from 'fs';
import * as path from 'path';
import { OpenAPIObject } from 'openapi3-ts';
import { s2o, fixSwagger, fixOpenAPI, requestData, CommonError } from './util';
import { ServiceGenerator, GenConfig } from './ServiceGenerator';
export class CliConfig extends GenConfig {
api?: string;
saveOpenAPIData?: boolean;
autoClear?: boolean = true;
/** 自动清除旧文件时忽略列表 */
ignoreDelete?: string[] = [];
}
export async function genSDK(cfg: string | CliConfig | CliConfig[]) {
let configs: CliConfig[] = [];
[].concat(cfg).forEach(c => {
if (typeof c === 'string') {
let cfgData = require(c);
if ((configs as any).__esModule) {
cfgData = (configs as any).default;
}
configs.push(...[].concat(cfgData));
} else if (typeof c === 'object') {
configs.push(c);
} else {
throw new CommonError(`fail load config: ${c}`);
}
});
return Promise.all(
configs.map(cfg => {
cfg = {
...new CliConfig(),
...cfg,
};
cfg.sdkDir = getAbsolutePath(cfg.sdkDir);
cfg.interfaceTemplatePath = getAbsolutePath(cfg.interfaceTemplatePath);
cfg.templatePath = getAbsolutePath(cfg.templatePath);
return genFromUrl(cfg);
})
);
}
export async function genFromData(config: CliConfig, data: OpenAPIObject) {
config = {
...new CliConfig(),
...config,
};
if (!data || !data.paths || !data.info) {
throw new CommonError(`数据格式不正确 ${config.api}`);
}
mkdir(config.sdkDir);
if (config.saveOpenAPIData) {
fs.writeFileSync(
path.join(config.sdkDir, 'origin.json'),
JSON.stringify(data, null, 2),
'utf8'
);
}
if (data.swagger === '2.0') {
data = await convertSwagger2OpenAPI(data);
} else {
fixOpenAPI(data);
}
if (!data.openapi || !data.openapi.startsWith('3.')) {
throw new CommonError('数据格式不正确,仅支持 OpenAPI 3.0/Swagger 2.0');
}
if (config.autoClear && fs.existsSync(config.sdkDir)) {
fs.readdirSync(config.sdkDir).forEach(file => {
if (
!['d.ts', '.ts', '.js'].some(ext => path.extname(file) === ext) ||
(config.requestLib && file.startsWith('base.'))
) {
return;
}
const absoluteFilePath = path.join(config.sdkDir, '/', file);
if ((config.ignoreDelete || []).indexOf(file) === -1 && absoluteFilePath !== file) {
fs.unlinkSync(absoluteFilePath);
}
});
}
if (config.saveOpenAPIData) {
fs.writeFileSync(path.join(config.sdkDir, 'oas.json'), JSON.stringify(data, null, 2), 'utf8');
}
const generator = new ServiceGenerator(config, data);
generator.genFile();
}
export async function convertSwagger2OpenAPI(data: OpenAPIObject) {
fixSwagger(data);
data = await s2o(data);
fixOpenAPI(data);
return data;
}
export async function genFromUrl(config: CliConfig) {
try {
const data = await JSON.parse(await requestData(config.api));
return genFromData(config, data);
} catch (error) {
console.warn(config.api, error);
throw error;
}
}
function getAbsolutePath(filePath: string) {
return filePath
? path.isAbsolute(filePath)
? filePath
: path.join(process.cwd(), filePath)
: filePath;
}
function mkdir(dir: string) {
if (!fs.existsSync(dir)) {
mkdir(path.dirname(dir));
fs.mkdirSync(dir);
}
}