-
Notifications
You must be signed in to change notification settings - Fork 238
/
Copy pathindex.ts
171 lines (160 loc) · 4.57 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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import { join } from 'path';
import { IApi } from 'umi';
import rimraf from 'rimraf';
import serveStatic from 'serve-static';
import { generateService, getSchema } from '@umijs/openapi';
import { existsSync, mkdirSync, writeFileSync } from 'fs';
export default (api: IApi) => {
api.describe({
key: 'openAPI',
config: {
schema(joi) {
const itemSchema = joi.object({
requestLibPath: joi.string(),
schemaPath: joi.string(),
mock: joi.boolean(),
projectName: joi.string(),
apiPrefix: joi.alternatives(joi.string(), joi.function()),
namespace: joi.string(),
hook: joi.object({
customFunctionName: joi.function(),
customClassName: joi.function(),
}),
});
return joi.alternatives(joi.array().items(itemSchema), itemSchema);
},
},
enableBy: api.EnableBy.config,
});
const { absNodeModulesPath, absTmpPath } = api.paths;
const openAPIFilesPath = join(absNodeModulesPath!, 'umi_open_api');
try {
if (existsSync(openAPIFilesPath)) {
rimraf.sync(openAPIFilesPath);
}
mkdirSync(join(openAPIFilesPath));
} catch (error) {
// console.log(error);
}
// 增加中间件
api.addMiddewares(() => {
return serveStatic(openAPIFilesPath);
});
api.onGenerateFiles(() => {
const openAPIConfig = api.config.openAPI;
const arrayConfig = api.utils.lodash.flatten([openAPIConfig]);
const config = arrayConfig?.[0]?.projectName;
api.writeTmpFile({
path: join('plugin-openapi', 'openapi.tsx'),
content: `
// This file is generated by Umi automatically
// DO NOT CHANGE IT MANUALLY!
import { useEffect, useState } from 'react';
import { SwaggerUIBundle } from 'swagger-ui-dist';
import 'swagger-ui-dist/swagger-ui.css';
const App = () => {
const [value, setValue] = useState("${config || 'openapi'}" );
useEffect(() => {
SwaggerUIBundle({
url: \`/umi-plugins_$\{value}.json\`,
dom_id: '#swagger-ui',
});
}, [value]);
return (
<div
style={{
padding: 24,
}}
>
<select
style={{
position: "fixed",
right: "16px",
top: "8px",
}}
onChange={(e) => setValue(e.target.value)}
>
${arrayConfig
.map((item) => {
return `<option value="${item.projectName || 'openapi'}">${
item.projectName || 'openapi'
}</option>`;
})
.join('\n')}
</select>
<div id="swagger-ui" />
</div>
);
};
export default App;
`,
});
});
if (api.env === 'development') {
api.modifyRoutes((routes) => {
return [
{
path: '/umi/plugin/openapi',
component: api.utils.winPath(
join(absTmpPath!, 'plugin-openapi', 'openapi.tsx'),
),
},
...routes,
];
});
}
const genOpenAPIFiles = async (openAPIConfig: any) => {
const openAPIJson = await getSchema(openAPIConfig.schemaPath);
writeFileSync(
join(
openAPIFilesPath,
`umi-plugins_${openAPIConfig.projectName || 'openapi'}.json`,
),
JSON.stringify(openAPIJson, null, 2),
);
};
api.onDevCompileDone(async () => {
try {
const openAPIConfig = api.config.openAPI;
if (Array.isArray(openAPIConfig)) {
openAPIConfig.map((item) => genOpenAPIFiles(item));
return;
}
genOpenAPIFiles(openAPIConfig);
} catch (error) {
console.error(error);
}
});
const genAllFiles = async (openAPIConfig: any) => {
const pageConfig = require(join(api.cwd, 'package.json'));
const mockFolder = openAPIConfig.mock ? join(api.cwd, 'mock') : undefined;
const serversFolder = join(api.cwd, 'src', 'services');
// 如果mock 文件不存在,创建一下
if (mockFolder && !existsSync(mockFolder)) {
mkdirSync(mockFolder);
}
// 如果mock 文件不存在,创建一下
if (serversFolder && !existsSync(serversFolder)) {
mkdirSync(serversFolder);
}
await generateService({
// projectName处理package.json没有name的情况
projectName: pageConfig?.name?.split('/')?.pop() || '/',
...openAPIConfig,
serversPath: serversFolder,
mockFolder,
});
api.logger.info('[openAPI]: execution complete');
};
api.registerCommand({
name: 'openapi',
fn: async () => {
const openAPIConfig = api.config.openAPI;
if (Array.isArray(openAPIConfig)) {
openAPIConfig.map((item) => genAllFiles(item));
return;
}
genAllFiles(openAPIConfig);
},
});
};