Skip to content

Commit

Permalink
Create patient resource using a deterministic id (#183)
Browse files Browse the repository at this point in the history
* create patient resource using a deterministic id
* use sha256 for hash
  • Loading branch information
wi-y committed Apr 15, 2022
1 parent 6c2ca30 commit 0600d80
Showing 1 changed file with 26 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
// -------------------------------------------------------------------------------------------------

using System;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using EnsureThat;
using Hl7.Fhir.Model;
Expand Down Expand Up @@ -69,13 +71,36 @@ protected async Task<TResource> CreateResourceByIdentityAsync<TResource>(Model.I

propertySetter?.Invoke(resource, identifier);

return await FhirService.CreateResourceAsync(resource).ConfigureAwait(false);
// Generate id programatically and issue an update to FHIR service
// The resource will be created if the resource with the given id does not already exist.
resource.Id = ComputeSha256(identifier);
return await FhirService.UpdateResourceAsync<TResource>(resource).ConfigureAwait(false);
}

private static Model.Identifier BuildIdentifier(string value, string system)
{
var identifier = new Model.Identifier { Value = value, System = string.IsNullOrWhiteSpace(system) ? null : system };
return identifier;
}

private static string ComputeSha256(Model.Identifier identifier)
{
EnsureArg.IsNotNullOrWhiteSpace(identifier.Value, nameof(identifier.Value));

string plainTextSystemAndId = $"{identifier.System}_{identifier.Value}";

using (SHA256 hashAlgorithm = SHA256.Create())
{
byte[] bytes = hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(plainTextSystemAndId));

StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
sb.Append(bytes[i].ToString("x2"));
}

return sb.ToString();
}
}
}
}

0 comments on commit 0600d80

Please sign in to comment.