forked from lantanagroup/FHIR.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvertToJs.ts
478 lines (421 loc) · 17.7 KB
/
convertToJs.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
import * as convert from 'xml-js';
import {ParseConformance} from './parseConformance';
import {XmlHelper} from './xmlHelper';
import {ParsedProperty} from "./model/parsed-property";
import {Constants} from "./constants";
import {XmlElement} from "./convertToXml";
export class ConvertToJs {
private parser: ParseConformance;
constructor(parser?: ParseConformance) {
this.parser = parser || new ParseConformance(true);
}
/**
* Converts the specified XML resource to a JS object, storing arbitrary-length decimals as strings since FHIR spec requires arbitrary precision.
* @param {string} xml Resource XML string
* @returns {FHIR.Resource} A Resource object converted from the XML Resource. Decimals stored as strings.
*/
public convert(xml) {
const xmlObj = convert.xml2js(xml);
const firstElement = xmlObj.elements.find((element) => element.type === 'element');
if (firstElement) {
return this.resourceToJS(firstElement, null);
}
}
/**
* Converts the specified XML resource to JSON,
* turning arbitrary-length decimals into JSON numbers as per the FHIR spec.
* @param {string} xml Resource XML string
* @returns {string} JSON with Numbers potentially too large for normal JavaScript & JSON.parse
*/
public convertToJSON(xml) {
const xmlObj = convert.xml2js(xml);
if (xmlObj.elements.length !== 1) {
return
}
/* Decimals are converted into an object with a custom
toJSON function that wraps them with 'DDDD's of a length
greater than any length of Ds in the JSON */
const surroundDecimalsWith = {};
const jsObj = this.resourceToJS(xmlObj.elements[0], surroundDecimalsWith);
const maxDLength = this.maxLengthOfDs(jsObj);
let rpt = '';
for (let i = 0; i < maxDLength + 5; i++) {
rpt += 'D';
}
surroundDecimalsWith['str'] = rpt;
const json = JSON.stringify(jsObj, null, '\t');
const replaceRegex = new RegExp('"?' + surroundDecimalsWith['str'] + '"?', 'g');
// console.log("replaceRegex", replaceRegex)
const json2 = json.replace(replaceRegex, '');
return json2
}
private maxLengthOfDs(obj) {
/**
* get length of longest sequence of 'D' characters in a string
* @param {string} str
*/
function maxSubstringLengthStr(str) {
const matches = str.match(/DDDD+/g);
if (!matches) {
return 0;
}
const ret = matches
.map((substr) => {
return substr.length
})
.reduce((p, c) => {
return Math.max(p, c)
}, 0);
return ret;
}
/**
* look through object to find longest sequence of 'D' characters
* so we can safely wrap decimals
*/
function maxSubstringLength(currentMax, obj) {
let ret;
if (typeof (obj) === 'string') {
ret = Math.max(currentMax, maxSubstringLengthStr(obj));
} else if (typeof (obj) === 'object') {
ret = Object.keys(obj)
.map((k) => {
return Math.max(maxSubstringLengthStr(k), maxSubstringLength(currentMax, obj[k]))
})
.reduce((p, c) => {
return Math.max(p, c)
}, currentMax);
} else {
ret = currentMax;
}
return ret;
}
return maxSubstringLength(0, obj);
}
/**
* @param xmlObj
* @returns {*}
* @private
*/
private resourceToJS(xmlObj, surroundDecimalsWith) {
const typeDefinition = this.parser.parsedStructureDefinitions[xmlObj.name];
const resource = {
resourceType: xmlObj.name
};
if (!typeDefinition) {
throw new Error('Unknown resource type: ' + xmlObj.name);
}
typeDefinition._properties.forEach((property) => {
this.propertyToJS(xmlObj, resource, property, surroundDecimalsWith);
});
return resource;
}
/**
* Finds a property definition based on a reference to another type. Should be a BackboneElement or Element
* @param relativeType {string} Example: "#QuestionnaireResponse.item"
*/
private findReferenceType(relativeType) {
if (!relativeType || !relativeType.startsWith('#')) {
return;
}
const resourceType = relativeType.substring(1, relativeType.indexOf('.')); // Assume starts with #
const path = relativeType.substring(resourceType.length + 2);
const resourceDefinition = this.parser.parsedStructureDefinitions[resourceType];
const pathSplit = path.split('.');
if (!resourceDefinition) {
throw new Error('Could not find resource definition for ' + resourceType);
}
let current = <ParsedProperty><any>resourceDefinition;
for (let i = 0; i < pathSplit.length; i++) {
const nextPath = pathSplit[i];
current = current._properties.find((property) => property._name === nextPath);
if (!current) {
return;
}
}
return JSON.parse(JSON.stringify(current));
}
/**
* @param xmlObj
* @param obj
* @param property
* @private
*/
private propertyToJS(xmlObj, obj, property, surroundDecimalsWith) {
const xmlElements = [];
if (xmlObj.elements) {
for (let element of xmlObj.elements) {
if (element.name === property._name) {
xmlElements.push(element);
}
}
}
const xmlAttributes = [];
if (xmlObj.attributes) {
const attributeKeys = Object.keys(xmlObj.attributes);
for (let attributeKey of attributeKeys) {
if (attributeKey === property._name) {
xmlAttributes.push({
name: attributeKey,
type: 'attribute',
attributes: {value: xmlObj.attributes[attributeKey]}
});
}
}
}
const xmlProperty = xmlElements.concat(xmlAttributes);
if (!xmlProperty || xmlProperty.length === 0) {
return;
}
// If this is a reference type then f
if (property._type && property._type.indexOf('#') === 0) {
const relativeType = this.findReferenceType(property._type);
if (!relativeType) {
throw new Error('Could not find reference to element definition ' + relativeType);
}
relativeType._name = property._name;
relativeType._multiple = property._multiple;
relativeType._required = property._required;
property = relativeType;
}
const addExtra = (element, index) => {
const hasId = element.attributes && element.attributes.id;
const hasExtensions = !!(element.elements || []).find((next) => next.name === 'extension');
if (hasId || hasExtensions) {
if (!obj['_' + property._name]) {
obj['_' + property._name] = obj[property._name] instanceof Array ? [] : {};
}
}
const dest = obj['_' + property._name];
if (hasId || hasExtensions) {
if (dest instanceof Array) {
// Fill in previous element indexes with null
if (dest.length < index + 1) {
for (let i = 0; i < index; i++) {
if (!dest[i]) {
dest[i] = null;
}
}
}
dest[index] = {};
}
}
if (hasId) {
if (dest instanceof Array) {
dest[index].id = element.attributes.id;
} else {
dest.id = element.attributes.id;
}
}
if (hasExtensions) {
const extensionProperty = {
_name: 'extension',
_type: 'Extension',
_multiple: true,
_required: false
};
this.propertyToJS(element, dest instanceof Array ? dest[index] : dest, extensionProperty, surroundDecimalsWith);
}
};
const pushValue = (value, index) => {
if (!value) return;
switch (property._type) {
case 'string':
case 'base64Binary':
case 'code':
case 'id':
case 'markdown':
case 'uri':
case 'url':
case 'canonical':
case 'oid':
case 'date':
case 'dateTime':
case 'time':
case 'instant':
addExtra(value, index);
if (value.attributes && value.attributes['value']) {
if (obj[property._name] instanceof Array) {
obj[property._name].push(value.attributes['value'])
} else {
obj[property._name] = value.attributes['value'];
}
}
break;
case 'decimal':
addExtra(value, index);
if (value.attributes['value']) {
if (obj[property._name] instanceof Array) {
obj[property._name].push(convertDecimal(value.attributes['value'], surroundDecimalsWith))
} else {
obj[property._name] = convertDecimal(value.attributes['value'], surroundDecimalsWith)
}
}
break;
case 'boolean':
addExtra(value, index);
if (value.attributes['value']) {
if (obj[property._name] instanceof Array) {
obj[property._name].push(toBoolean(value.attributes['value']))
} else {
obj[property._name] = toBoolean(value.attributes['value'])
}
}
break;
case 'integer':
case 'unsignedInt':
case 'positiveInt':
addExtra(value, index);
if (value.attributes && value.attributes['value']) {
if (obj[property._name] instanceof Array) {
obj[property._name].push(toNumber(value.attributes['value']))
} else {
obj[property._name] = toNumber(value.attributes['value'])
}
}
break;
case 'xhtml':
if (value.elements && value.elements.length > 0) {
const div = convert.js2xml({elements: [XmlHelper.escapeInvalidCharacters(value)]});
if (obj[property._name] instanceof Array) {
obj[property._name].push(div);
} else {
obj[property._name] = div;
}
}
break;
case 'Element':
case 'BackboneElement':
const newValue = {};
for (let x in property._properties) {
const nextProperty = property._properties[x];
this.propertyToJS(value, newValue, nextProperty, surroundDecimalsWith);
}
if (obj[property._name] instanceof Array) {
obj[property._name].push(newValue);
} else {
obj[property._name] = newValue;
}
break;
case 'Resource':
if (value.elements.length === 1) {
if (obj[property._name] instanceof Array) {
obj[property._name].push(this.resourceToJS(value.elements[0], surroundDecimalsWith))
} else {
obj[property._name] = this.resourceToJS(value.elements[0], surroundDecimalsWith);
}
}
break;
default:
const nextType = this.parser.parsedStructureDefinitions[property._type];
if (!nextType) {
console.log('do something');
} else {
const newValue = {};
nextType._properties.forEach(nextProperty => {
this.propertyToJS(value, newValue, nextProperty, surroundDecimalsWith);
});
if (obj[property._name] instanceof Array) {
obj[property._name].push(newValue);
} else {
obj[property._name] = newValue;
}
}
break;
}
}
function toBoolean(value) {
if (value === "true") {
return true;
} else if (value === "false") {
return false;
} else {
throw new Error("Value should be a boolean but got: " + value)
}
}
function toNumber(value) {
if (/^-?\d+$/.test(value) == false) {
throw new Error("Value should be a number but got: " + value)
}
return parseInt(value, 10)
}
function convertDecimal(value, surroundDecimalsWith) {
// validation regex from http://hl7.org/fhir/xml.html
if (/^-?([0]|([1-9][0-9]*))(\.[0-9]+)?$/.test(value) == false) {
throw new Error("Value should be a decimal number but got: " + value)
}
if (surroundDecimalsWith) {
return {
value: value,
toJSON: function () {
// surrounding str used as a marker to remove quotes to turn this
// into a JSON number as per FHIR spec..
return surroundDecimalsWith.str + value + surroundDecimalsWith.str;
}
}
} else {
return value;
}
}
if (property._multiple) {
obj[property._name] = [];
}
for (let i = 0; i < xmlProperty.length; i++) {
let xmlCommentElements: XmlElement[];
let nextXmlComment;
const xmlPropertyIndex = xmlObj.elements.indexOf(xmlProperty[i]);
while (nextXmlComment != null || !xmlCommentElements) {
if (!xmlCommentElements) {
xmlCommentElements = [];
}
const nextIndex = xmlCommentElements.length + 1;
if ((xmlPropertyIndex - nextIndex) < 0)
break;
nextXmlComment = xmlPropertyIndex > 0 && xmlObj.elements[xmlPropertyIndex - nextIndex].type === 'comment' ?
xmlObj.elements[xmlPropertyIndex - nextIndex] :
null;
if (nextXmlComment) {
xmlCommentElements.push(nextXmlComment);
}
}
const extraPropertyName = '_' + property._name;
/*const xmlCommentElement = xmlPropertyIndex > 0 && xmlObj.elements[xmlPropertyIndex - 1].type === 'comment' ?
xmlObj.elements[xmlPropertyIndex - 1] :
null;
*/
pushValue(xmlProperty[i], i);
if (xmlCommentElements && xmlCommentElements.length > 0) {
if (Constants.PrimitiveTypes.indexOf(property._type) >= 0) {
if (property._multiple) {
if (!obj[extraPropertyName]) {
obj[extraPropertyName] = [];
}
if (!obj[extraPropertyName][i]) {
obj[extraPropertyName][i] = {};
}
obj[extraPropertyName][i].fhir_comments = xmlCommentElements.reverse().map(c => c.comment.trim());
} else {
if (!obj[extraPropertyName]) {
obj[extraPropertyName] = {};
}
obj[extraPropertyName].fhir_comments = xmlCommentElements.reverse().map(c => c.comment.trim());
}
} else {
if (property._multiple) {
if (!obj[property._name]) {
obj[property._name] = [];
}
if (!obj[property._name][i]) {
obj[property._name][i] = {};
}
obj[property._name][i].fhir_comments = xmlCommentElements.reverse().map(c => c.comment.trim());
} else {
if (!obj[property._name]) {
obj[property._name] = {};
}
obj[property._name].fhir_comments = xmlCommentElements.reverse().map(c => c.comment.trim());
}
}
}
}
}
}