Skip to main content

dhis2@4.0.3

Functions

attr(attribute, value)
configMigrationHelper(state)
create(resourceType, data, [options], [callback])
destroy(resourceType, path, [data], [options], [callback])
discover(httpMethod, endpoint)
dv(dataElement, value)
findAttributeValue(trackedEntityInstance, attributeDisplayName)
get(resourceType, query, [options], [callback])
patch(resourceType, path, data, [options], [callback])
request(configuration, axiosRequest)
selectId(resourceType)
update(resourceType, path, data, [options], [callback])
upsert(resourceType, query, data, [options], [callback])

The following functions are exported from the common adaptor:

alterState()
dataPath()
dataValue()
dateFns()
each()
field()
fields()
fn()
http()
lastReferenceValue()
merge()
sourceValue()

attr

attr(attribute, value) ⇒ object

Converts an attribute ID and value into a DSHI2 attribute object

ParamTypeDescription
attributestringA tracked entity instance (TEI) attribute ID.
valuestringThe value for that attribute.

Example

attr('w75KJ2mc4zz', 'Elias')

configMigrationHelper

configMigrationHelper(state) ⇒ object

Migrates apiUrl to hostUrl if hostUrl is blank. For OpenFn.org users with the old-style configuration.

ParamTypeDescription
stateobjectthe runtime state

Example

configMigrationHelper(state)

create

create(resourceType, data, [options], [callback]) ⇒ Operation

Create a record

ParamTypeDescription
resourceTypestringType of resource to create. E.g. trackedEntityInstances, programs, events, ...
dataDhis2DataObject which defines data that will be used to create a given instance of resource. To create a single instance of a resource, data must be a javascript object, and to create multiple instances of a resources, data must be an array of javascript objects.
[options]ObjectOptional options to define URL parameters via params (E.g. filter, dimension and other import parameters), request config (E.g. auth) and the DHIS2 apiVersion.
[callback]functionOptional callback to handle the response

Example (a program)

create('programs', {
name: 'name 20',
shortName: 'n20',
programType: 'WITHOUT_REGISTRATION',
});

Example (an event)

create('events', {
program: 'eBAyeGv0exc',
orgUnit: 'DiszpKrYNg8',
status: 'COMPLETED',
});

Example (a trackedEntityInstance)

create('trackedEntityInstances', {
orgUnit: 'TSyzvBiovKh',
trackedEntityType: 'nEenWmSyUEp',
attributes: [
{
attribute: 'w75KJ2mc4zz',
value: 'Gigiwe',
},
]
});

Example (a dataSet)

create('dataSets', { name: 'OpenFn Data Set', periodType: 'Monthly' });

Example (a dataSetNotification)

create('dataSetNotificationTemplates', {
dataSetNotificationTrigger: 'DATA_SET_COMPLETION',
notificationRecipient: 'ORGANISATION_UNIT_CONTACT',
name: 'Notification',
messageTemplate: 'Hello',
deliveryChannels: ['SMS'],
dataSets: [],
});

Example (a dataElement)

create('dataElements', {
aggregationType: 'SUM',
domainType: 'AGGREGATE',
valueType: 'NUMBER',
name: 'Paracetamol',
shortName: 'Para',
});

Example (a dataElementGroup)

create('dataElementGroups', {
name: 'Data Element Group 1',
dataElements: [],
});

Example (a dataElementGroupSet)

create('dataElementGroupSets', {
name: 'Data Element Group Set 4',
dataDimension: true,
shortName: 'DEGS4',
dataElementGroups: [],
});

Example (a dataValueSet)

create('dataValueSets', {
dataElement: 'f7n9E0hX8qk',
period: '201401',
orgUnit: 'DiszpKrYNg8',
value: '12',
});

Example (a dataValueSet with related dataValues)

create('dataValueSets', {
dataSet: 'pBOMPrpg1QX',
completeDate: '2014-02-03',
period: '201401',
orgUnit: 'DiszpKrYNg8',
dataValues: [
{
dataElement: 'f7n9E0hX8qk',
value: '1',
},
{
dataElement: 'Ix2HsbDMLea',
value: '2',
},
{
dataElement: 'eY5ehpbEsB7',
value: '3',
},
],
});

Example (an enrollment)

create('enrollments', {
trackedEntityInstance: 'bmshzEacgxa',
orgUnit: 'TSyzvBiovKh',
program: 'gZBxv9Ujxg0',
enrollmentDate: '2013-09-17',
incidentDate: '2013-09-17',
});

destroy

destroy(resourceType, path, [data], [options], [callback]) ⇒ Operation

Delete a record. A generic helper function to delete an object

ParamTypeDescription
resourceTypestringThe type of resource to be deleted. E.g. trackedEntityInstances, organisationUnits, etc.
pathstringCan be an id of an object or path to the nested object to delete.
[data]ObjectOptional. This is useful when you want to remove multiple objects from a collection in one request. You can send data as, for example, {"identifiableObjects": [{"id": "IDA"}, {"id": "IDB"}, {"id": "IDC"}]}. See more on DHIS2 API docs
[options]ObjectOptional options for del operation including params e.g. {preheatCache: true, strategy: 'UPDATE', mergeMode: 'REPLACE'}. Run discover or see DHIS2 documentation. Defaults to {operationName: 'delete', apiVersion: state.configuration.apiVersion, responseType: 'json'}
[callback]functionOptional callback to handle the response

Example (a tracked entity instance)

destroy('trackedEntityInstances', 'LcRd6Nyaq7T');

discover

discover(httpMethod, endpoint) ⇒ Operation

Discover DHIS2 api endpoint query parameters and allowed operators for a given resource's endpoint.

ParamTypeDescription
httpMethodstringThe HTTP to inspect parameter usage for a given endpoint, e.g., get, post,put,patch,delete
endpointstringThe path for a given endpoint. E.g. /trackedEntityInstances or /dataValueSets

Example (a list of parameters allowed on a given endpoint for specific http method)

discover('post', '/trackedEntityInstances')

dv

dv(dataElement, value) ⇒ object

Converts a dataElement and value into a DSHI2 dataValue object

ParamTypeDescription
dataElementstringA data element ID.
valuestringThe value for that data element.

Example

dv('f7n9E0hX8qk', 12)

findAttributeValue

findAttributeValue(trackedEntityInstance, attributeDisplayName) ⇒ string

Gets an attribute value by its case-insensitive display name

ParamTypeDescription
trackedEntityInstanceObjectA tracked entity instance (TEI) object
attributeDisplayNamestringThe 'displayName' to search for in the TEI's attributes

Example

findAttributeValue(state.data.trackedEntityInstances[0], 'first name')

get

get(resourceType, query, [options], [callback]) ⇒ Operation

Get data. Generic helper method for getting data of any kind from DHIS2.

  • This can be used to get DataValueSets,events,trackedEntityInstances,etc.

Returns: Operation - state

ParamTypeDescription
resourceTypestringThe type of resource to get(use its plural name). E.g. dataElements, trackedEntityInstances,organisationUnits, etc.
queryObjectA query object that will limit what resources are retrieved when converted into request params.
[options]ObjectOptional options to define URL parameters via params beyond filters, request configuration (e.g. auth) and DHIS2 api version to use.
[callback]functionOptional callback to handle the response

Example (all data values for the 'pBOMPrpg1QX' dataset)

get('dataValueSets', {
dataSet: 'pBOMPrpg1QX',
orgUnit: 'DiszpKrYNg8',
period: '201401',
fields: '*',
});

Example (all programs for an organization unit)

get('programs', { orgUnit: 'TSyzvBiovKh', fields: '*' });

Example (a single tracked entity instance by a unique external ID)

get('trackedEntityInstances', {
ou: 'DiszpKrYNg8',
filter: ['flGbXLXCrEo:Eq:124', 'w75KJ2mc4zz:Eq:John'],
});

patch

patch(resourceType, path, data, [options], [callback]) ⇒ Operation

Patch a record. A generic helper function to send partial updates on one or more object properties.

  • You are not required to send the full body of object properties.
  • This is useful for cases where you don't want or need to update all properties on a object.
ParamTypeDescription
resourceTypestringThe type of resource to be updated. E.g. dataElements, organisationUnits, etc.
pathstringThe id or path to the object to be updated. E.g. FTRrcoaog83 or FTRrcoaog83/{collection-name}/{object-id}
dataObjectData to update. Include only the fields you want to update. E.g. {name: "New Name"}
[options]ObjectOptional configuration, including params for the update ({preheatCache: true, strategy: 'UPDATE', mergeMode: 'REPLACE'}). Defaults to {operationName: 'patch', apiVersion: state.configuration.apiVersion, responseType: 'json'}
[callback]functionOptional callback to handle the response

Example (a dataElement)

patch('dataElements', 'FTRrcoaog83', { name: 'New Name' });

request

request(configuration, axiosRequest) ⇒ Promise

The request client takes configuration from state and an axios request object then (1) logs the method and URL, (2) applies standard headers and auth before spreading the rest of the axios configuration, and (3) executes an axios request.

Returns: Promise - a promise that will resolve to either a response object or an error object.

ParamTypeDescription
configurationobjectconfiguration must have a username and password
axiosRequestobjectthe axiosRequest contains valid axios params: https://axios-http.com/docs/req_config

selectId

selectId(resourceType) ⇒ string

Determines the attribute name for a DHIS2 system ID given a resource type.

ParamType
resourceTypestring

update

update(resourceType, path, data, [options], [callback]) ⇒ Operation

Update data. A generic helper function to update a resource object of any type. Updating an object requires to send all required fields or the full body

ParamTypeDescription
resourceTypestringThe type of resource to be updated. E.g. dataElements, organisationUnits, etc.
pathstringThe id or path to the object to be updated. E.g. FTRrcoaog83 or FTRrcoaog83/{collection-name}/{object-id}
dataObjectData to update. It requires to send all required fields or the full body. If you want partial updates, use patch operation.
[options]ObjectOptional options to define URL parameters via params (E.g. filter, dimension and other import parameters), request config (E.g. auth) and the DHIS2 apiVersion.
[callback]functionOptional callback to handle the response

Example (a program)

update('programs', 'qAZJCrNJK8H', {
name: '14e1aa02c3f0a31618e096f2c6d03bed',
shortName: '14e1aa02',
programType: 'WITHOUT_REGISTRATION',
});

Example (an event)

update('events', 'PVqUD2hvU4E', {
program: 'eBAyeGv0exc',
orgUnit: 'Ngelehun CHC',
status: 'COMPLETED',
storedBy: 'admin',
dataValues: [],
});

Example (a trackedEntityInstance)

update('trackedEntityInstances', 'IeQfgUtGPq2', {
created: '2015-08-06T21:12:37.256',
orgUnit: 'TSyzvBiovKh',
createdAtClient: '2015-08-06T21:12:37.256',
trackedEntityInstance: 'IeQfgUtGPq2',
lastUpdated: '2015-08-06T21:12:37.257',
trackedEntityType: 'nEenWmSyUEp',
inactive: false,
deleted: false,
featureType: 'NONE',
programOwners: [
{
ownerOrgUnit: 'TSyzvBiovKh',
program: 'IpHINAT79UW',
trackedEntityInstance: 'IeQfgUtGPq2',
},
],
enrollments: [],
relationships: [],
attributes: [
{
lastUpdated: '2016-01-12T00:00:00.000',
displayName: 'Last name',
created: '2016-01-12T00:00:00.000',
valueType: 'TEXT',
attribute: 'zDhUuAYrxNC',
value: 'Russell',
},
{
lastUpdated: '2016-01-12T00:00:00.000',
code: 'MMD_PER_NAM',
displayName: 'First name',
created: '2016-01-12T00:00:00.000',
valueType: 'TEXT',
attribute: 'w75KJ2mc4zz',
value: 'Catherine',
},
],
});

Example (a dataSet)

update('dataSets', 'lyLU2wR22tC', { name: 'OpenFN Data Set', periodType: 'Weekly' });

Example (a dataSetNotification)

update('dataSetNotificationTemplates', 'VbQBwdm1wVP', {
dataSetNotificationTrigger: 'DATA_SET_COMPLETION',
notificationRecipient: 'ORGANISATION_UNIT_CONTACT',
name: 'Notification',
messageTemplate: 'Hello Updated,
deliveryChannels: ['SMS'],
dataSets: [],
});

Example (a dataElement)

update('dataElements', 'FTRrcoaog83', {
aggregationType: 'SUM',
domainType: 'AGGREGATE',
valueType: 'NUMBER',
name: 'Paracetamol',
shortName: 'Para',
});

Example (a dataElementGroup)

update('dataElementGroups', 'QrprHT61XFk', {
name: 'Data Element Group 1',
dataElements: [],
});

Example (a dataElementGroupSet)

update('dataElementGroupSets', 'VxWloRvAze8', {
name: 'Data Element Group Set 4',
dataDimension: true,
shortName: 'DEGS4',
dataElementGroups: [],
});

Example (a dataValueSet)

update('dataValueSets', 'AsQj6cDsUq4', {
dataElement: 'f7n9E0hX8qk',
period: '201401',
orgUnit: 'DiszpKrYNg8',
value: '12',
});

Example (a dataValueSet with related dataValues)

update('dataValueSets', 'Ix2HsbDMLea', {
dataSet: 'pBOMPrpg1QX',
completeDate: '2014-02-03',
period: '201401',
orgUnit: 'DiszpKrYNg8',
dataValues: [
{
dataElement: 'f7n9E0hX8qk',
value: '1',
},
{
dataElement: 'Ix2HsbDMLea',
value: '2',
},
{
dataElement: 'eY5ehpbEsB7',
value: '3',
},
],
});

Example (a single enrollment)

update('enrollments', 'CmsHzercTBa' {
trackedEntityInstance: 'bmshzEacgxa',
orgUnit: 'TSyzvBiovKh',
program: 'gZBxv9Ujxg0',
enrollmentDate: '2013-10-17',
incidentDate: '2013-10-17',
});

upsert

upsert(resourceType, query, data, [options], [callback]) ⇒ Operation

Upsert a record. A generic helper function used to atomically either insert a row, or on the basis of the row already existing, UPDATE that existing row instead.

Throws:

  • RangeError - Throws range error
ParamTypeDescription
resourceTypestringThe type of a resource to upsert. E.g. trackedEntityInstances
queryObjectA query object that allows to uniquely identify the resource to update. If no matches found, then the resource will be created.
dataObjectThe data to use for update or create depending on the result of the query.
[options]ObjectOptional configuration that will be applied to both the get and the create or update operations.
[callback]functionOptional callback to handle the response

Example (Example `expression.js` of upsert)

upsert('trackedEntityInstances', {
ou: 'TSyzvBiovKh',
filter: ['w75KJ2mc4zz:Eq:Qassim'],
}, {
orgUnit: 'TSyzvBiovKh',
trackedEntityType: 'nEenWmSyUEp',
attributes: [
{
attribute: 'w75KJ2mc4zz',
value: 'Qassim',
},
],
});