-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
247 lines (208 loc) · 7 KB
/
main.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import * as fs from "fs/promises";
import axios from "axios";
const primitives = [
"base64Binary",
"boolean",
"canonical",
"code",
"date",
"dateTime",
"decimal",
"id",
"instant",
"integer",
"integer64",
"markdown",
"oid",
"positiveInt",
"string",
"time",
"unsignedInt",
"uri",
"url",
"uuid",
];
const types = "intrface Reference<T> { resourceType: T, id: string }";
const box = axios.create({
baseURL: 'http://localhost:8765',
auth: {
username: 'root',
password: 'secret',
},
});
const getZenSymbolDef = async (symbol : string) => {
const resp = await box.post("/rpc", {
method: "aidbox.zen/symbol",
params: { name: symbol },
});
const result = resp.data.result;
return result;
}
const getZenSymbolDefsByTag = async(tag: string) => {
const resp = await box.post("/rpc", {
method: "aidbox.zen/tagged-symbols",
params: { tag: tag }
});
const result = resp.data.result;
return result;
}
const findSymbolDeps = (symbol: any) => {
let deps:any = [];
const finder = (reducedSymbol : any) => {
if (reducedSymbol.confirms) {
deps = deps.concat(reducedSymbol.confirms);
}
Object.values(reducedSymbol).map( (val: any) => {
if (Array.isArray(val)) {
return val.map(finder);
} else if (val === null) {
return;
} else if (typeof val === "object") {
return finder(val);
}
})
};
finder(symbol);
return [... new Set(deps)];
}
const collectSymbolDeps = async (symbols: any) => {
let collected = symbols;
let deps: any = Object.values(symbols).map(findSymbolDeps);
deps = [... new Set(deps.flat())];
deps = deps.filter((dep:any) => !collected[dep]);
if(deps.length === 0) {
return collected;
}
for (const dep of deps) {
const symbol = await getZenSymbolDef(dep);
collected[dep] = symbol;
}
collectSymbolDeps(collected);
}
const getFhirTypeFromSymbol = (symbol:string) => {
if (symbol.startsWith('zen.fhir')) {
return symbol.split('/')[1];
}
const ns = symbol.split('/')[0];
const nsParts = ns.split('.')
const type = nsParts[nsParts.length - 1];
return type;
}
const generateInterface = (symbolName:any, symbolDef:any) => {
const type = getFhirTypeFromSymbol(symbolName);
if (symbolDef.type == "zen/map") {
let str = `export interface ${type} { \n`;
const fields = symbolDef.keys;
for (const key of Object.keys(fields)) {
str = str + `${key}: `
if (fields[key].confirms) {
str = str + fields[key].confirms.map(getFhirTypeFromSymbol).join(" & ")
str = str + ';\n'
} else if (fields[key].type === 'zen/vector') {
str = str + `Array<`;
str = str + fields[key].every.confirms.map(getFhirTypeFromSymbol).join(" & ");
str = str + `>;\n`;
}
}
console.log(str)
}
}
const getSchemas = async () => {
let zsd = await getZenSymbolDefsByTag('zen.fhir/base-schema');
await collectSymbolDeps(zsd);
generateInterface('hl7-fhir-r4-core.Patient/schema', zsd['hl7-fhir-r4-core.Patient/schema'])
const res3 = await box.post("/rpc", {
method: "aidbox.zen/tagged-symbols",
params: { tag: "zen.fhir/structure-schema" },
});
const zenPrimitives = Object.values(res3.data.result).filter((item: any) => {
return primitives.some((i) => item["zen.fhir/type"] === i) && !item.confirms;
});
const res = await box.post("/rpc", {
method: "aidbox.zen/tagged-symbols",
params: { tag: "zen.fhir/base-schema" },
});
// console.dir(test, { depth: 10 });
// console.log(test.length);
// const response = res.data.result.map((item: any) => item["zen.fhir/type"]);
// console.dir(response, { depth: 10 });
//
// const res2 = await box.post("/rpc", {
// method: "aidbox.zen/tagged-symbols",
// params: { tag: "zen.fhir/profile-schema" },
// });
//
// const response2 = res2.data.result.map((item: any) => item["zen.fhir/type"]);
// console.dir(response2, { depth: 10 });
const response = Object.values(res.data.result).find((item: any) => item["zen.fhir/type"] === "Patient");
// console.dir(response, { depth: 10 });
const str = `export interface Patient { ${Object.entries(parseSchema(response.keys))
.map(([key, value]) => `${key}: ${value}`)
.join(",/n")} }`;
fs.writeFile("./test-types.ts", str);
};
const parseSchema = (keys: any) => {
if (!keys) return undefined;
const item = Object.entries(keys).map(([key, value]: any) => {
return parseSingleAttribute(key, value);
});
return item.reduce((acc: any, i: any) => ({ ...acc, ...i }), {});
};
const zenPrimitivesToTS = {
"hl7-fhir-r4-core.boolean/schema": "boolean",
};
const parseSingleAttribute = (name: string, value: any) => {
name === "active" && true; // console.log(value.confirms);
const primitive = value.confirms?.map((i: string) => zenPrimitivesToTS[i]).shift();
name === "active" && true; // console.log(primitive);
if (primitive) {
return { [name]: primitive };
}
if (value.confirms?.includes("zen.fhir/Reference")) {
return { [name]: mapReferenceToType(value) };
}
//
// if (value.confirms?.includes("hl7-fhir-r4-core.CodeableConcept/schema")) {
// return { [name]: "hl7-fhir-r4-core.CodeableConcept/schema" };
// }
//
// if (value.confirms?.includes("hl7-fhir-r4-core.Identifier/schema")) {
// return { [name]: "hl7-fhir-r4-core.Identifier/schema" };
// }
//
// if (value.confirms?.includes("hl7-fhir-r4-core.ContactPoint/schema")) {
// return { [name]: "hl7-fhir-r4-core.ContactPoint/schema" };
// }
//
// if (value.confirms?.includes("hl7-fhir-r4-core.Address/schema")) {
// return { [name]: "hl7-fhir-r4-core.ContactPoint/schema" };
// }
//
// if (value.type === "zen/vector") {
// return { [name]: parseVectorAttribute(parseSchema(value.every.keys)) };
// }
};
const parseVectorAttribute = (attribute: any) => {
return `Array<${JSON.stringify(attribute)}>`;
};
const mapReferenceToType = (reference: any) => {
const names = reference["zen.fhir/reference"].refers;
return names.map((i: string) => `Reference<${i}>`).join(" | ");
};
if (require.main === module) {
const start = Date.now();
if (!process.env.USE_CACHE) {
console.log(
"Cache is disabled. Use `make generate-aidbox-types USE_CACHE=1` to cache aidbox requests and speed up types generation",
);
}
console.log("Generating types…");
getSchemas();
// main()
// .then(() => {
// console.log(`Done in ${Date.now() - start}ms`);
// })
// .catch((err) => {
// console.error(err?.isAxiosError ? err.response.data : err);
// });
}