-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (58 loc) · 1.52 KB
/
index.js
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
const schemaUtil = require('schema-util');
const { compile } = require('json-schema-to-typescript');
function walk(json, opts = {}) {
opts.visitor(json, { isRoot: !opts.isNotRoot });
const props = json.properties;
if (props) {
for (const k in props) {
walk(props[k], {
...opts,
isNotRoot: true,
});
}
}
if (json.items && json.items.type === 'object') {
walk(json.items, {
...opts,
isNotRoot: true,
});
}
}
module.exports = async (schema, opts = {
exportName: 'ISchemaProps',
}) => {
const json = schemaUtil.schema(schema);
// walk props
walk(json, {
visitor(obj, { isRoot }) {
// 不支持的 type, fallback 为 string
if (obj.type && [
// ref: https://yuque.antfin-inc.com/morpho/developer/hy548b#X2OtG
// 已支持但不在 ts 类型范围内的类型
'color',
'image',
'url',
'date',
// 降级为 string 的类型
'text',
'richText',
].includes(obj.type)) {
obj.type = 'string';
}
// schema-utils 生成的 array 类型不规范
// ref: https://json-schema.org/understanding-json-schema/reference/array.html
if (obj.type === 'array') {
obj.items = {
type: 'object',
properties: obj.properties,
};
delete obj.properties;
}
// 非 root 无需 unknown props
if (!isRoot) {
obj.additionalProperties = false;
}
},
});
return await compile(json, opts.exportName);
}