• This repository has been archived on 08/Oct/2024
  • Stars
    star
    425
  • Rank 102,094 (Top 3 %)
  • Language
    JavaScript
  • Created over 10 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JavaScript client for FHIR

fhir.js

npm version

Build Status

Gitter chat

JavaScript client for FHIR

Goals:

  • Support FHIR CRUD operations
  • Friendly and expressive query syntax
  • Support for adapters that provide idiomatic interfaces in angular, jQuery, extjs, etc
  • Support for access control (HTTP basic, OAuth2, Cookies)
  • ...

Development

Node.js is required for build.

We recommend installing Node.js using nvm

Build & test:

git clone https://github.com/FHIR/fhir.js
cd fhir.js
npm install

# build fhir.js
npm run-script build

# run tests in node
npm run-script test

# run tests in phantomjs
npm run-script integrate

API

Create instance of the FHIR client

To communicate with concrete FHIR server, you can create instance of the FHIR client, passing a configuration object & adapter object. Adapters are implemented for concrete frameworks/libs (see below).

var config = {
  // FHIR server base url
  baseUrl: 'http://myfhirserver.com',
  auth: {
     bearer: 'token',
     // OR for basic auth
     user: 'user',
     pass: 'secret'
  },
  // Valid Options are 'same-origin', 'include'
  credentials: 'same-origin',
  headers: {
    'X-Custom-Header': 'Custom Value',
    'X-Another-Custom': 'Another Value',
  }
}

myClient = fhir(config, adapter)

Config Object

The config object is an object that is passed through the middleware chain. Any values in the config object that are not mutated by middleware will be available to the adapter.

Because middleware mutates the config, it is strongly recommended when implementing an adapter to not directly rely on config passed in.

baseUrl

This is the full url to your FHIR server. Resources will be appended to the end of it.

auth

This is an object representing your authentication requirements. Possible options include:

bearer

This is your Bearer token when provided, it will add an Authorization: Bearer <token> header to your requests.

user

This is your Basic auth Username.

When you provide both user name and password, basic auth will be used.

pass

This is your basic auth password.

When you provide both user name and password, basic auth will be used.

credentials

This option controls the behaviour of sending cookies to the remote server. Refer to the table below for how to configure the option for your desired adapter.

Adapter credentials Result
Native 'same-origin' Cookies are sent to the server, if it is on the same host as the origin sender
Native 'include' Send cookies to all hosts
jQuery 'same-origin' ignored
jQuery 'include' Send cookies to all hosts
yui 'same-origin' ignored
yui 'include' Send cookies to all hosts
angular 'same-origin' ignored
angular 'include' ignored
node 'same-origin' ignored
node 'include' ignored
headers

A key:value object that represents headers. This object is passed through to you configured adapter.

If you choose to add custom headers to your requests, you should ensure that the server that you are talking to supplies the appropriate headers. Further reading on Allowed Headers: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

const config = {
  headers: {
    'X-Custom-Header': 'Custom Value',
    'X-Another-Custom': 'Another Value',
  }
}

Adapter implementation

Currently each adapter must implement an http(requestObj) function:

Structure of requestObj:

  • method - http method (GET|POST|PUT|DELETE)
  • url - url for request
  • headers - object with headers (i.e. {'Category': 'term; scheme="sch"; label="lbl"'}

and return promise (A+)

http(requestObj).then(success, error)

where: success - success callback, which should be called with (data, status, headersFn, config)

  • data - parsed body of responce
  • status - responce HTTP status
  • headerFn - function to get header, i.e. headerFn('Content')
  • config - initial requestObj passed to http

error - error callback, which should be called with (data, status, headerFn, config)

Here are implementations for:

Conformance & Profiles

Resource's CRUD

Create Resource

To create a FHIR resource, call myClient.create(entry, callback, errback), passing an object that contains the following properties:

  • resource (required) - resource in FHIR json
  • tags (optional) - list of categories (see below)

In case of success,the callback function will be invoked with an object that contains the following attributes:

  • id - url of created resource
  • content - resource json
  • category - list of tags
var entry = {
  category: [{term: 'TAG term', schema: 'TAG schema', label: 'TAG label'}, ...]
  resource: {
    resourceType: 'Patient',
    //...
  }
}

myClient.create(entry,
 function(entry){
    console.log(entry.id)
 },
 function(error){
   console.error(error)
 }
)

Get resource

To get one specific object from a resource (usually by id), call fhir.read({type: resourceType}). To specify the patient identifier, call fhir.read({type: resourceType, patient: patientIdentifier})

Examples:

fhir.read({type: 'Patient', patient: '8673ee4f-e2ab-4077-ba55-4980f408773e'})

Search Resource

To search a resource, call fhir.search({type: resourceType, query: queryObject}), where queryObject syntax fhir.js adopts mongodb-like query syntax (see):

{name: 'maud'}
//=> name=maud

{name: {$exact: 'maud'}}
//=> name:exact=maud

{name: {$or: ['maud','dave']}}
//=> name=maud,dave

{name: {$and: ['maud',{$exact: 'dave'}]}}
//=> name=maud&name:exact=Dave

{birthDate: {$gt: '1970', $lte: '1980'}}
//=> birthDate=gt1970&birthDate=lte1980

{subject: {$type: 'Patient', name: 'maud', birthDate: {$gt: '1970'}}}
//=> subject:Patient.name=maud&subject:Patient.birthDate=gt1970

{'subject.name': {$exact: 'maud'}}
//=> subject.name:exact=maud

Update Resource

To update a resource, call fhir.update({type: resourceType, id: identifier, resource: resourceObject}). In case of success,the callback function will be invoked.

Example:

 	this.fhirClient.update({
            type: "Patient",
            id: 1,
            resource: {
		name: 'New Name'
            }
        }).catch(function(e){
            console.log('An error happened while updating patient: \n' + JSON.stringify(e));
            throw e;
        }).then(function(bundle){
            console.log('Updating patient successed');
            return bundle;
        });

Delete Resource

To update a resource, call fhir.delete({type: resourceType, id: identifier}).

For more information see tests

AngularJS adapter: ng-fhir

AngularJS adapter after npm run-script build can be found at dist/ngFhir.js

Usage:

angular.module('app', ['ng-fhir'])
  .config(['$fhirProvider', function ($fhirProvider) {
    $fhirProvider.baseUrl = 'http://try-fhirplace.hospital-systems.com';
    $fhirProvider.auth = {
      user: 'user',
      pass: 'secret'
    };
    $fhirProvider.credentials = 'same-origin'
  }])
  .controller('mainCtrl', ['$scope', '$fhir', function ($scope, $fhir) {
    $fhir.search(
      {
        type: 'Patient',
        query: {name: 'emerald'}
      }).then(
      function (successData) {
        $scope.patients = successData.data.entry;

      },
      function (failData) {
        $scope.error = failData;
      }
    );
  }]);  

jQuery adapter: jqFhir

jQuery build can be found at dist/jqFhir.js

Example app

Usage:

<script src="./jquery-???.min.js"> </script>
<script src="./jqFhir.js"> </script>
// create fhir instance
var fhir = jqFhir({
    baseUrl: 'https://ci-api.fhir.me',
    auth: {user: 'client', pass: 'secret'}
})

fhir.search({type: 'Patient', query: {name: 'maud'}})
.then(function(bundle){
  console.log('Search patients', bundle)
})

Node.js adapter: npm install fhir.js

Via NPM you can npm install fhir.js. (If you want to work on the source code, you can compile coffee to js via npm install, and use ./lib/adapters/node as an entrypoint.)

var mkFhir = require('fhir.js');

var client = mkFhir({
    baseUrl: 'http://try-fhirplace.hospital-systems.com'
});

client
    .search( {type: 'Patient', query: { 'birthdate': '1974' }})
    .then(function(res){
        var bundle = res.data;
        var count = (bundle.entry && bundle.entry.length) || 0;
        console.log("# Patients born in 1974: ", count);
    })
    .catch(function(res){
        //Error responses
        if (res.status){
            console.log('Error', res.status);
        }

        //Errors
        if (res.message){
            console.log('Error', res.message);
        }
    });

YUI adapter: yuiFhir

YUI build can be found at dist/yuiFhir.js

NOTE: The current implementation creates a YUI sandbox per request which is expensive.

Usage:

<script src="./yui-???.min.js"> </script>
<script src="./yuiFhir.js"> </script>
// create fhir instance
var fhir = jqFhir({
    baseUrl: 'https://ci-api.fhir.me',
    auth: {user: 'client', pass: 'secret'}
})

fhir.search(type: 'Patient', query: {name: 'maud'}, success: function(bundle) {}, error: function() {})

Native adapter: npm install fhir.js

The Native adapter is part of fhir.js npm module. The adapter can be consumed in a few ways, the simplest is documented below.

Usage

This assumes use of browserify or similar bundler.

  1. npm install fhir.js
  2. In your js somewhere use the following snippet.
// Include the adapter
var nativeFhir = require('fhir.js/src/adapters/native');

// Create fhir instance
var fhir = nativeFhir({
    baseUrl: 'https://ci-api.fhir.me',
    auth: {user: 'client', pass: 'secret'}
});

// Execute the search
fhir.search({type: 'Patient', query: {name: 'maud'}}).then(function(response){
    //manipulate your data here.
});

For Developers

FHIR.js is built on top of middleware concept. What is middleware? This is a high order function of shape:

var mw  = function(next){
   return function(args){
     if (...) // some logic{
        return next(args); //next mw in chain
     } else {
        return promise; //short circuit chain
     }
  }
}

Using function Middleware(mw) you can get composable middle-ware (with .and(mw) method):

mwComposition = Middleware(mw).and(anotherMw).and(anotherMw);

Every API function is built as chain of middlewares with end handler in the end:

conformance = $GET.and(BaseUrl.slash("metadata")).end(http)
create =  $POST.and($resourceTypePath).and($ReturnHeader).and($JsonData).end(http),

Release Notes

release 0.1

API changes history is split into 3 fns:

  • fhir.history
  • fhir.typeHistory
  • fhir.resourceHistory

TODO

  • npm package
  • bower package

Contribute

Join us by github issues or pull-requests

License

Released under the MIT license.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

sushi

SUSHI (aka "SUSHI Unshortens Short Hand Inputs") is a reference implementation command-line interpreter/compiler for FHIR Shorthand (FSH).
TypeScript
144
star
2

sql-on-fhir-v2

This project provides the source for the SQL on FHIR v2.0 Implementation Guide
JavaScript
97
star
3

sql-on-fhir

SQL on FHIR Proposal
78
star
4

documents

Documents that support FHIR - tutorials, presentations, analysis documents + old ballot records
XSLT
68
star
5

auto-ig-builder

Implementation Guide builder
JavaScript
47
star
6

sample-ig

A sample, template-driven implementation guide that provides instruction on creating IGs
HTML
42
star
7

fhir-test-cases

Shared test cases across multiple FHIR reference implementations / validators
HTML
40
star
8

GoFSH

GoFSH is a FHIR Shorthand (FSH) decompiler, able to convert formal FHIR definitions from JSON/XML to FSH.
TypeScript
35
star
9

ig-registry

Registry of published implementation guides
JavaScript
30
star
10

packages

Useful FHIR packages to support implementation: fhir.tx.support and fhir.test.data
CSS
29
star
11

genomics-operations

A public reference implementation of HL7 FHIR Genomics Operations (http://build.fhir.org/ig/HL7/genomics-reporting/operations.html)
Python
28
star
12

Ucum-java

FHIR Java library providing UCUM Services
Java
23
star
13

vscode-fsh

A Visual Studio Code language extension for FHIR Shorthand (FSH)
JavaScript
17
star
14

interversion

Maps and scripts for converting between different FHIR versions
JavaScript
15
star
15

cda-examples-to-fhir

Converting cda examples to fhir
Ruby
13
star
16

ig-guidance

An implementation guide that explains how to create FHIR implementation guides - including examples of how to do various things
Batchfile
13
star
17

fhir-terminology

SPA for FHIR valuesets
CoffeeScript
11
star
18

Gravity-SDOH-Exchange-RI

Reference implementation for the Gravity SDOH IG
Java
11
star
19

FSHOnline

A Web Playground for FHIR Shorthand
JavaScript
8
star
20

FSHSchool

Hugo source files for the FSHSchool site
Batchfile
5
star
21

fhir-candle

fhir-candle - A FHIR development and test server implemented in C#
C#
4
star
22

fhir-impl-guidelines

4
star
23

snomed-ig

Implementation Guide for using SNOMED CT with FHIR
CSS
4
star
24

Gravity-Patient-App-RI

Gravity Your Health Mobile App RI
TypeScript
3
star
25

latest-ig-publisher

Release path for the latest version of the FHIR IG Publisher
HTML
3
star
26

bower-fhir

JavaScript
3
star
27

devices.fhir.org

Source for http://devices.fhir.org
HTML
2
star
28

MADFSH

TypeScript
2
star
29

MimicImporter

Java
2
star
30

FSHOnline-Examples

Jupyter Notebook
2
star
31

fhir-tools-ig

This FHIR Implementation Guide documents the extensions used by the FHIR tooling internally
Batchfile
2
star
32

fhir-package-loader

An NPM module and simple CLI for downloading FHIR packages
TypeScript
1
star
33

r5-invariant-test-cases

Test cases for invariants in FHIR R5
1
star
34

hl7-ig-template

Test HL7 template
HTML
1
star
35

terminology-service-liveness-monitor

C#
1
star
36

test-template

this template is the test template for the FHIR IG publisher
CSS
1
star
37

davinci-pdex-plan-net

Da Vinci Payor Data Exchange - Plan Network (Provider, Organization and Location registry) reference implementation
Ruby
1
star