/
model.ts
90 lines (80 loc) · 2.29 KB
/
model.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
import * as t from '@umijs/bundler-utils/compiled/babel/types';
import { readFileSync } from 'fs';
import { join } from 'path';
import { IApi } from 'umi';
import { winPath } from 'umi/plugin-utils';
import { ModelUtils } from './utils/modelUtils';
import { withTmpPath } from './utils/withTmpPath';
export default (api: IApi) => {
api.describe({
config: {
schema({ zod }) {
return zod
.object({
extraModels: zod.array(zod.string()),
})
.partial();
},
},
enableBy: api.EnableBy.config,
});
api.onGenerateFiles(async () => {
const models = await getAllModels(api);
// model.ts
api.writeTmpFile({
path: 'model.ts',
content: ModelUtils.getModelsContent(models),
});
// index.tsx
const indexContent = readFileSync(
join(__dirname, '../libs/model.tsx'),
'utf-8',
).replace('fast-deep-equal', winPath(require.resolve('fast-deep-equal')));
api.writeTmpFile({
path: 'index.tsx',
content: indexContent,
});
// runtime.tsx
api.writeTmpFile({
path: 'runtime.tsx',
content: `
import React from 'react';
import { Provider } from './';
import { models as rawModels } from './model';
function ProviderWrapper(props: any) {
const models = React.useMemo(() => {
return Object.keys(rawModels).reduce((memo, key) => {
memo[rawModels[key].namespace] = rawModels[key].model;
return memo;
}, {});
}, []);
return <Provider models={models} {...props}>{ props.children }</Provider>
}
export function dataflowProvider(container, opts) {
return <ProviderWrapper {...opts}>{ container }</ProviderWrapper>;
}
`,
});
});
api.addTmpGenerateWatcherPaths(() => {
return [join(api.paths.absSrcPath, 'models')];
});
api.addRuntimePlugin(() => {
return [withTmpPath({ api, path: 'runtime.tsx' })];
});
};
async function getAllModels(api: IApi) {
const extraModels = await api.applyPlugins({
key: 'addExtraModels',
type: api.ApplyPluginsType.add,
initialValue: [],
});
return new ModelUtils(api, {
astTest({ node }) {
return t.isArrowFunctionExpression(node) || t.isFunctionDeclaration(node);
},
}).getAllModels({
sort: {},
extraModels: [...extraModels, ...(api.config.model.extraModels || [])],
});
}