# FHIR Validator實作
目前FHIR Validation相關Package在官網已經改名為”Hl7.Fhir.Validation.Legacy”,顧名思義可知,這是一個即將被淘汰的package,但由於新的Package尚未發表,預期應該還可以使用一段日子。另外,從開發的角度來看,預期基本流程應該不會有太大改變,因此了解這一版FHIR Validation的做法還是有其必要性。
FHIR Validation的目的在於根據標準,驗證FHIR Data的正確性。因此,我們必須實作一個FHIR Resolver,解析FHIR 標準。一般而言,需要參考的標準會不只一份,以TW Core IG為例,一份正確的FHIR Data必須同時滿足FHIR Resource R4與TW Core IG。換句話說,Resolver必須能解析多個FHIR標準。
---
FHIR Validation主要步驟如下:
1. 匯入Package與namespace
```
#r "nuget:hl7.fhir.validation.legacy.r4"
#r "nuget:hl7.fhir.specification.data.r4"
#r "nuget:hl7.fhir.r4"
using Hl7.Fhir.Serialization;
using Hl7.Fhir.Specification.Source;
using static Hl7.Fhir.Specification.Source.ZipSource;
using Hl7.Fhir.Validation;
using Hl7.Fhir.Model;
using System.IO;
```
2. 產生解析FHIR標準的Resolver。如前所述,resolver需要同時處理多個FHIR 標準。Specification.zip為FHIR Resource R4所定義的profile標準,TW Core IG相關的profile則是解壓縮後存放在profile目錄下。
```
IResourceResolver resolver = new CachedResolver(
// create a multi-resolver, which can resolve resources from more than one source
new MultiResolver(
ZipSource.CreateValidationSource(“..\\profile\\specification.zip”),
// create the directory source resolver, which points to our profiles directory
new DirectorySource("..\\profile", new DirectorySourceSettings()
{
IncludeSubDirectories = true,
})
)
);
```
3. 根據Resolver產生validator
```
Validator validator = new Validator(new ValidationSettings()
{
ResourceResolver = resolver
}
);
```
4. 讀取FHIR Data並使用Validator驗證其正確性
```
var patient = File.ReadAllText("..\\data\\Patient-pat-example.json");
var patientResource = new FhirJsonParser().Parse<Patient>(patient);
var outcome = validator.Validate(patientResource);
Console.WriteLine(outcome.ToString());
```
嚴格來說,程式架構並不複雜,花最多時間的地方反而是在相關檔案的配對。TW Core IG的Package與FHIR Resource R4所需要的specification.zip可從以下網址下載。另外,壓縮檔與目錄所對應的Source物件不同,壓縮檔需要使用ZipSource,一般目錄則是對應DirectorySource。由於官網文件對相關的說明並不多,因此實作過程花了許多時間try and error。
> TW.GOV.MOHW.TWCORE\定義與範例檔下載 - FHIR v4.0.1
> firely-net-sdk/src/Hl7.Fhir.Specification.Data.R4 at develop · FirelyTeam/firely-net-sdk (github.com)