· 4 years ago · Aug 31, 2021, 02:14 PM
1const fs = require('fs');
2const path = require('path');
3
4const args = process.argv.slice(2);
5
6const schemaInputPath = args[0];
7const schemaOutputPath = args[1];
8
9if (!schemaInputPath) throw new Error('Schema input path is required');
10if (!schemaOutputPath) throw new Error('Schema output path is required');
11
12// eslint-disable-next-line import/no-dynamic-require
13const schema = require(path.resolve(process.cwd(), schemaInputPath));
14
15/**
16 * Выпиливаем Public api, мы им не пользуемся, а они ломают генерацию
17 */
18for (const key in schema.components.schemas) {
19 if (key.includes('.Public.')) {
20 delete schema.components.schemas[key];
21 }
22}
23
24/**
25 * Делаем все поля required, чтобы они не были optional
26 * Было: field?: string | null
27 * Стало: field: string | null
28 */
29for (const key in schema.components.schemas) {
30 const subSchema = schema.components.schemas[key];
31
32 if (subSchema.type !== 'object' || !subSchema.properties) continue;
33
34 const properties = Object.keys(subSchema.properties);
35 subSchema.required = properties;
36}
37
38const schemaText = JSON.stringify(schema, null, 2);
39
40/**
41 * Выпиливаю артефакты вида:
42 * [[...]]
43 * `1
44 * @param text
45 */
46const removeBadSymbols = text => text.replace(/(\[\[.*\]\]|`1)/g, '');
47
48/**
49 * Выпиливаю дубликаты:
50 *
51 * Monq.Sm.Service.GatewayApi.ViewModels.WebUi.v1.Rsm.GateConfigItemEdgePutViewModel
52 * Monq.Sm.Service.GatewayApi.ViewModels.WebUi.v2.Rsm.GateConfigItemEdgePutViewModel
53 *
54 * Проблема в том, что генератор берёт лишь последнюю часть, отсюда дубликаты
55 */
56const removeDuplicates = text => text.replace(/"(.*\.)(v)([2-9])(\..*)"/g, '"$1$2$3$4V$3"');
57
58/**
59 * Делаем читаемое имя моделей
60 *
61 * Было: "Monq.Sm.Service.GatewayApi.ViewModels.WebUi.v1.AutomatonRules.GateAutomatonRuleScriptValidatePostViewModel"
62 * Стало: "GateAutomatonRuleScriptValidatePostViewModel"
63 *
64 * Было: "#/components/schemas/Monq.Sm.Service.GatewayApi.ViewModels.WebUi.v1.AutomatonRules.GateAutomatonRuleScriptValidatePostViewModel"
65 * Стало: "#/components/schemas/Monq.Sm.Service.GatewayApi.ViewModels.WebUi.v1.AutomatonRules.GateAutomatonRuleScriptValidatePostViewModel"
66 */
67const extractModelNames = text => text.replace(/"(#\/components\/schemas\/)?(Monq\.)(.*)(\.)(.*)"/g, '"$1$5"');
68
69Promise.resolve(schemaText)
70 .then(removeBadSymbols)
71 .then(removeDuplicates)
72 .then(extractModelNames)
73 .then(fixedSchemaText => {
74 fs.writeFile(path.resolve(process.cwd(), schemaOutputPath), fixedSchemaText, (err) => {
75 if (err) {
76 console.error(err);
77 process.exit(1);
78 }
79
80 console.log(`Fixed schema: ${schemaInputPath} > ${schemaOutputPath}`);
81 process.exit(0);
82 });
83 })
84 .catch(err => {
85 console.error(err);
86 process.exit(1);
87 });