Ahryman40k / typescript-fhir-types

Typescript / Javascript object model for FHIR standard
MIT License
126 stars 27 forks source link

Help using the package. #36

Closed alokshriram closed 3 years ago

alokshriram commented 3 years ago

Hi, I just started using this package, and I am running into some issues that I was hoping you could help me with. I am pulling a FHIR patient resource from an end point, and getting the patient structure back that I want to leverage

import { R4 } from '@ahryman40k/ts-fhir-types'
import * as either from "fp-ts/lib/Either";

const fhir_patient = R4.RTTI_Patient.decode(patient_data) // patient_data is coming from an end_point
// I now have a either.Validation<R4.IPatient>  for fhir_patient

The question I have is how do I now extract the R4.RTTI_Patient from it. The documentation on the site says that we should do

const  obs: R4.IPatient = either.isRight(fhir_patient);

but as I understand it isRight returns a bool, so cannot be cast to R4.IPatient

Am I missing something ? Or is there a different way of doing this with the current version of the package. Thanks for any help that you can provide.

alokshriram commented 3 years ago

A small update. I was able to get something working.. but I am not sure if this is the best way to do this operation.

import { R4 } from '@ahryman40k/ts-fhir-types'
import * as io from 'io-ts'
import { pipe } from 'fp-ts/function'
import { fold } from 'fp-ts/Either'

function parseError(errors: io.Errors) {
    return null
}

function parseUser(user: R4.IPatient) : R4.IPatient {
    return user
}

let user = pipe(R4.RTTI_Patient.decode(patient_data), fold(parseError, parseUser))

gets me back the IPatient type. I imagine, we can inline the two functions.. so make this code a little bit cleaner to read.

Would this be the correct way of parsing inputs out. If so let me know and I am happy to update the readme.md file with the new instructions.

Ahryman40k commented 3 years ago

Hi @alokshriram,

Thank you for contacting me. You can find help about either in fp-ts library used by io-ts. io-ts is the library used to make type checking at runtime.

decode() return an alias of Either<Left, Right>. It means if something goes wrong you get a Left object, Right otherwise. isLeft or isRight are type guards that safely tell you what kind of object you've got.

Either type leads you into functional programing, see a small introduction here , but it isn't mandatory to use FP if you are not ready.

Consider the small example below:

import { R4 } from '@ahryman40k/ts-fhir-types'
import { either as E } from 'fp-ts'

const json = {
    "resourceType":"Patient"   
 };

const  validationResult = R4.RTTI_Patient.decode(json)

if ( E.isLeft( validationResult) ) {
    console.log(validationResult.left)
}

if ( E.isRight( validationResult) ) {
    console.log(validationResult.right)
}

Hope it helps.