This repository has been archived by the owner on Feb 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
SyntheaReferenceResolver.cs
98 lines (84 loc) · 3.04 KB
/
SyntheaReferenceResolver.cs
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
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace FhirLoader
{
///<summary>
/// Utility class for resolving Synthea bundle references
///</summary>
public class SyntheaReferenceResolver
{
///<summary>
/// Resolves all UUIDs in Synthea bundle
///</summary>
public static void ConvertUUIDs(JObject bundle)
{
ConvertUUIDs(bundle, CreateUUIDLookUpTable(bundle));
}
private static void ConvertUUIDs(JToken tok, Dictionary<string, IdTypePair> idLookupTable)
{
switch (tok.Type)
{
case JTokenType.Object:
case JTokenType.Array:
foreach (var c in tok.Children())
{
ConvertUUIDs(c, idLookupTable);
}
return;
case JTokenType.Property:
JProperty prop = (JProperty)tok;
if (prop.Value.Type == JTokenType.String &&
prop.Name == "reference" &&
idLookupTable.TryGetValue(prop.Value.ToString(), out var idTypePair))
{
prop.Value = idTypePair.ResourceType + "/" + idTypePair.Id;
}
else
{
ConvertUUIDs(prop.Value, idLookupTable);
}
return;
case JTokenType.String:
case JTokenType.Boolean:
case JTokenType.Float:
case JTokenType.Integer:
case JTokenType.Date:
return;
default:
throw new NotSupportedException($"Invalid token type {tok.Type} encountered");
}
}
private static Dictionary<string, IdTypePair> CreateUUIDLookUpTable(JObject bundle)
{
Dictionary<string, IdTypePair> table = new Dictionary<string, IdTypePair>();
JArray entry = (JArray)bundle["entry"];
if (entry == null)
{
throw new ArgumentException("Unable to find bundle entries for creating lookup table");
}
try
{
foreach (var resourceWrapper in entry)
{
var resource = resourceWrapper["resource"];
var fullUrl = (string)resourceWrapper["fullUrl"];
var resourceType = (string)resource["resourceType"];
var id = (string)resource["id"];
table.Add(fullUrl, new IdTypePair { ResourceType = resourceType, Id = id });
}
}
catch
{
Console.WriteLine("Error parsing resources in bundle");
throw;
}
return table;
}
private class IdTypePair
{
public string Id { get; set; }
public string ResourceType { get; set; }
}
}
}