3.13.1 • Published 5 days ago

fhirpath v3.13.1

Weekly downloads
1,616
License
SEE LICENSE in LI...
Repository
github
Last release
5 days ago

fhirpath.js

Build Status

FHIRPath implementation in JavaScript.

Demo

Try it out on the demo page.

Installation:

Server-side (Node.js)

npm install --save fhirpath
const fhirpath = require('fhirpath');
// For FHIR model data (choice type support) pull in the model file:
const fhirpath_r4_model = require('fhirpath/fhir-context/r4');

Web-browser:

Download the zip file from the releases page. It contains a JavaScript file, fhirpath.min.js, which defines a global "fhirpath" variable, which you can then use as shown below. Note that this file is UTF-8 encoded, and the script needs to be loaded as such. For an example, see the browser-build/test/index.html file, which sets the page to be UTF-8.

For FHIR-specific features (e.g. handling of choice type fields), you will also want to include a second file with the desired FHIR version model data, e.g. fhirpath.r4.min.js for pulling in the R4 model. (At the moment, those files are small, but it would not be surprising if they grew as more support for FHIR type handling is added, so they are kept seperate from the main FHIRPath file.) These will define additional global variables like "fhirpath_dstu2_model", "fhirpath_stu3_model" or "fhirpath_r4_model".

API Usage

Evaluating FHIRPath:

evaluate(resourceObject, fhirPathExpression, environment, model, options);

Note: The resource will be modified by this function to add type information.

Basic example:

fhirpath.evaluate({"resourceType": "Patient", ...}, 'Patient.name.given');

Environment variables can be passed in as third argument as a hash of name/value pairs:

fhirpath.evaluate({}, '%a - 1', {a: 5});

To include FHIR model data (for support of choice types), pass in the model data object as the fourth argument:

fhirpath.evaluate({"resourceType": "Observation", "valueString": "green"},
                  'Observation.value', null, fhirpath_r4_model);

If the first parameter is a part of a resource, the second parameter should be an object with properties "base" and "expression": base - the path in the resource that represents the partial resource being used as the context, expression - fhirpath expression relative to base.

fhirpath.evaluate({ "answer": { "valueQuantity": ...}},
                  { "base": "QuestionnaireResponse.item",
                    "expression": "answer.value = 2 year"},
                  null, fhirpath_r4_model);                  

Precompiling fhirpath - result can be reused against multiple resources:

const path = fhirpath.compile('Patient.name.given', fhirpath_r4_model);
var res = path({"resourceType": "Patient", ...}, {a: 5, ...});

If you are going to use the above "precompile" option with a part of a resource, the first parameter should be an object with properties "base" and "expression": base - the path in the resource that represents the partial resource being used as the context, expression - fhirpath expression relative to base.

const path = fhirpath.compile({ "base": "QuestionnaireResponse.item",
                                "expression": "answer.value = 2 year"},
                              fhirpath_r4_model);
var res = path({ "answer": { "valueQuantity": ...}, {a: 5, ...});

During expression evaluation, some values or parts of values may have internal data types (e.g. FP_DateTime, FP_Time, FP_Quantity). By default, all of these values are converted to standard JavaScript types, but if you need to use the result of evaluation as a context variable for another FHIRpath expression, it would be best to preserve the internal data types. To do this you can use the option "resolveInternalTypes" = false:

const contextVariable = fhirpath.evaluate(
  resource, expression, context, model, {resolveInternalTypes: false}
);

This option may also be passed to compile function:

const path = fhirpath.compile(
  expression, model, {resolveInternalTypes: false}
);

If at some point you decide to convert all values which have internal types to standard JavaScript types you can use the special function "resolveInternalTypes":

const res = fhirpath.resolveInternalTypes(value);

Also, there is a special API function to get the type of each element in FHIRPath result array which was obtained from evaluate() (unless you resolve the internal types). This function returns an array of strings. In the next example, res will have a value like this: 'FHIR.dateTime', 'FHIR.string', ....

const res = fhirpath.types(
  fhirpath.evaluate(resource, expression, context, model, {resolveInternalTypes: false})
);

If you want to capture evaluations of the trace method, you can include that in the options object.

let tracefunction = function (x, label) {
  console.log("Trace output [" + label + "]: ", x);
};

const res = fhirpath.evaluate(contextNode, path, environment, fhirpath_r4_model, { traceFn: tracefunction });

User-defined functions

You can also replace any existing functions or define new ones. To do this you need to include a user invocation table in the options object. The user invocation table has the following structure:

{
  <function name>: {
    fn: <function implementation>,
    arity: {
      <allowed number of parameters>: <array of parameter types>,
      ...
    },
    [nullable: <boolean, false by default>],
    [internalStructures: <boolean, false by default>]
  },
  ...
}

An example of defining a function for raising a number to a specified power (by default to a power of 2):

const userInvocationTable = {
  pow: {fn: (inputs,exp=2)=>inputs.map(i => Math.pow(i, exp)), arity: {0: [], 1: ["Integer"]}},
};
const res = fhirpath.evaluate({"a": [5,6,7]}, "a.pow()", null, null, { userInvocationTable });

Where pow is the name of the function, userInvocationTable.pow.fn is the implementation of the pow function, userInvocationTable.pow.arity is a hash table describing the mapping between the allowed number of possible parameters and their types.

A function implementation (e.g. userInvocationTable.pow.fn) is a function whose first parameter is an array of resource node values or an array of values on which the function is executed, and subsequent parameters are the parameters passed to the FHIRPath function (e.g. pow).

Available parameter types:

  • Expr - means that a FHIRPath expression passed to the function will be converted to a javascript function which will be passed as a parameter to fn. This javascript function expects one parameter which will be used as $this for the expression.
  • AnyAtRoot - a FHIRPath expression passed to the function will be evaluated before it is passed to fn with $this from the parent expression, or, if $this is not defined for the parent expression, then $this will point to the root node of the resource for which the expression is evaluated.

    For example, for the expression Patient.name.first().subsetOf($this.name): Patient.name.first() is the parent of $this.name. $this.name will be evaluated before it is passed to subsetOf, with $this pointing to the Patient.

  • Identifier - currently not in use.

  • TypeSpecifier - expects a type specifier to be converted to an instance of the TypeInfo class (see src/types.js) before it will be passed to fn.
  • Any - FHIRPath expression passed to the function will be evaluated before it will be passed to fn.
  • Integer - a value will be passed to fn if it is an integer, otherwise an exception will be thrown.
  • Boolean - a value will be passed to fn if it is a boolean, otherwise an exception will be thrown.
  • Number - a value will be passed to fn if it is a number, otherwise an exception will be thrown.
  • String - a value will be passed to fn if it is a string, otherwise an exception will be thrown.

The optional nullable flag means propagation of an empty result, i.e. instead of calling fn, if one of the parameters is empty, empty is returned.

If access to internal structures such as ResourceNode (see class ResourceNode in src/types.js) is desired (e.g. for path information), then you can set a flag internalStructures to true. In this case, each parameter of a function implementation (e.g. userInvocationTable.pow.fn) can be an array of ResourceNodes. To ensure that you get the value from the ResourceNode or the value as is, you can use the fhirpath.util.valData or fhirpath.util.valDataConverted function (see src/utilities.js).

fhirpath CLI

bin/fhirpath is a command-line tool for experimenting with FHIRPath.

curl http://www.hl7.org/fhir/patient-example-a.json  > pt.json

fhirpath --expression 'Patient.name.given' --resourceFile pt.json

> fhirpath(Patient.name.family) =>
> [
>  "Donald"
> ]

Instead of passing a filename containing the resource, the string of JSON representing the resource can be passed directly via --resourceJSON (useful if the JSON is brief).

fhirpath --expression 'a.b + 2' --resourceJSON '{"a": {"b": 1}}'

> fhirpath(a.b + 2) =>
> [
>  3
> ]

Environment variables can be passed via --variables followed by the JSON for an object with variable names as keys.

fhirpath --expression '%v + 2' --resourceJSON '{}' --variables '{"v": 5}'

> fhirpath(%v + 2) =>
> [
>  7
> ]

FHIR model data can be included via --model and the FHIR release version (in lower case, e.g., 'dstu2', 'stu3' or 'r4').

fhirpath --expression 'Observation.value' --resourceJSON '{"resourceType": "Observation", "valueString": "Green"}' --model r4

Also, you can pass in a filename or a string of JSON representing a part of the resource. In that case, you should pass in the base path from which this part of the resource was extracted.

fhirpath --basePath QuestionnaireResponse.item --expression 'answer.value' --model r4 --resourceFile questionnaire-part-example.json

> fhirpath(answer.value) =>
> [
>  "2 year"
> ]

If given just the FHIRPath expression, the utility will print the parsed tree:

fhirpath --expression 'Patient.name.given'

> ... will print fhirpath ast in yaml

Implementation Status

We are currently working on implementing version 2.0.0 of FHIRPath; some behavior may still be following the previous version, STU1.

The core parser was generated from the FHIRPath ANTLR grammar.

Completed sections:

  • 3 (Path selection)
  • 5.1 (Existence)
  • 5.2 (Filtering and Projection) "ofType"
  • 5.3 (Subsetting)
  • 5.4 (Combining)
  • 5.5 (Conversion)
  • 5.6 (String Manipulation)
  • 5.7 (Tree Navigation)
  • 5.8 (Utility Functions)
  • 6.1 (Equality)
  • 6.2 (Comparison)
  • 6.3 (Types)
  • 6.4 (Collections)
  • 6.5 (Boolean logic)
  • 6.6 (Math)
  • 6.8 (Operator Precedence) - handled by ANTLR parser
  • 7 (Aggregates)
  • 8 (Lexical Elements) - handled by ANTLR parser
  • 9 (Environment Variables)

Supported additional functions from FHIR:

  • extension(url : string) : collection
  • hasValue() : Boolean

Development Notes

This section is for people doing development on this package (as opposed to using the package).

If you need to regenerate the parser from the ANTLR4 grammar (which is in parser/FHIRPath.g4), first download the ANTLR4 library from http://www.antlr.org/download/antlr-4.7.1-complete.jar into the root of the project directory, and then run "npm run generateParser".

Building the demo page

npm install && npm run build
cd demo
npm install && npm run build && npm run start

open browser on localhost:8080

Updating the FHIR module on a FHIR release

  • Download the FHIR StructureDefinitions (into the fhir-context directory - don't check these in)
    > wget http://hl7.org/fhir/profiles-types.json -O profiles-types.json
    > wget http://hl7.org/fhir/profiles-others.json -O profiles-others.json
    > wget http://hl7.org/fhir/profiles-resources.json -O profiles-resources.json
  • Create the new folder for the version you are importing
    > mkdir r5
  • Run the script with NodeJS
    > node ./extract-model-info.js --outputDir r5 --fhirDefDir .
  • Compare the output files in the new folder to those of the last release (looking for issues that might be due to changes in the StructureDefinition format)
  • Copy the index.js file from the last release into the new folder
    > cp ../r4/index.js r5
  • Update the /index.d.ts file to include the new module as an export
    declare module "fhirpath/fhir-context/r5" {
      export const {
        choiceTypePaths,
        pathsDefinedElsewhere,
        type2Parent,
        path2Type
      }: Model;
    }

Credits

This implemention of the FHIRPath specification was developed as a joint project between the U.S. National Library of Medicine (NLM) and Health Samurai, and was then donated to HL7. Current maintenance and additional development is being performed by NLM, but we welcome contributions from others. (For anything substantial, we recommend raising an issue first to coordinate with us.)

A complete list of contributors can be found at https://github.com/HL7/fhirpath.js/graphs/contributors

3.13.1

5 days ago

3.13.0

25 days ago

3.11.0

1 month ago

3.10.5

2 months ago

3.10.4

2 months ago

3.10.1

3 months ago

3.10.0

4 months ago

3.9.1

4 months ago

3.9.0

6 months ago

3.8.0

7 months ago

3.8.1

7 months ago

3.7.1

7 months ago

3.7.0

8 months ago

3.6.1

9 months ago

3.6.0

10 months ago

3.4.0

1 year ago

3.5.0

1 year ago

3.3.2

1 year ago

3.2.0

1 year ago

3.3.1

1 year ago

3.3.0

1 year ago

3.1.0

2 years ago

3.0.0

2 years ago

2.14.7

2 years ago

2.14.5

2 years ago

2.14.6

2 years ago

2.14.4

2 years ago

2.14.3

2 years ago

2.14.2

2 years ago

2.13.0

2 years ago

2.14.1

2 years ago

2.14.0

2 years ago

2.11.0

2 years ago

2.12.0

2 years ago

2.10.2

2 years ago

2.10.1

3 years ago

2.10.0

3 years ago

2.9.1

3 years ago

2.9.0

3 years ago

2.8.0

3 years ago

2.7.4

3 years ago

2.7.3

3 years ago

2.7.2

3 years ago

2.7.1

4 years ago

2.7.0

4 years ago

2.6.2

4 years ago

2.6.1

4 years ago

2.6.0

4 years ago

2.5.0

4 years ago

2.4.0

4 years ago

2.3.0

4 years ago

2.2.2

4 years ago

2.2.1

4 years ago

2.2.0

4 years ago

2.1.5

4 years ago

2.1.4

4 years ago

2.1.3

4 years ago

2.1.2

4 years ago

2.1.1

4 years ago

2.1.0

4 years ago

2.0.0

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago

0.17.5

4 years ago

0.17.4

5 years ago

0.17.2

5 years ago

0.17.0

5 years ago

0.16.2

5 years ago

0.16.0

5 years ago

0.15.0

5 years ago

0.14.0

5 years ago

0.13.0

5 years ago

0.12.2

5 years ago

0.12.1

5 years ago

0.12.0

5 years ago

0.11.0

5 years ago

0.10.3

5 years ago

0.10.2

5 years ago

0.10.1

5 years ago

0.10.0

5 years ago

0.9.2

5 years ago

0.9.1

5 years ago

0.9.0

6 years ago

0.8.2

6 years ago

0.8.1

6 years ago

0.8.0

6 years ago

0.7.0

6 years ago

0.6.0

6 years ago

0.5.1

6 years ago

0.5.0

6 years ago

0.4.3

6 years ago

0.4.2

6 years ago

0.4.1

6 years ago

0.4.0

6 years ago

0.3.0

6 years ago

0.2.3

6 years ago

0.2.2

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago