Work with adapter.js

adapter.js is the integration point between the adapter andItential Platform. It defines the methods available toItential Platform andItential Platform Automation Studio, formats request data for the adapter runtime libraries, and returns results toItential Platform. Each adapter should have a CALLS.md file listing its specific API calls.

Generic methods

These methods are available toItential Platform or to you as an adapter developer. Additional internal-only methods exist that are not listed here.

Method signatureDescriptionWorkflow task?
connect()Runs when the adapter is first loaded byItential Platform. Validates that required properties have been provided correctly.No
healthCheck(callback)Confirms the adapter can communicate with the external system. The specific call used is defined in the adapter properties and the .system entity’s action.json.No
refreshProperties(properties)Accepts updated property values without requiring an adapter restart.No
encryptProperty(property, technique, callback)Encrypts a property value using the specified technique. Use this to store credential passwords in adapterProps in encrypted form so they do not need to be stored in plain text. The adapter decrypts the value as needed.No
iapUpdateAdapterConfiguration(configFile, changes, entity, type, action, callback)Updates adapter configuration from withinItential Platform — including actions, schemas, mock data, and other configuration files.Yes
iapFindAdapterPath(apiPath, callback)Checks whether a specific API path is supported by the adapter.Yes
iapSuspendAdapter(mode, callback)Suspends the adapter. Incoming requests are either rejected or queued until the adapter is resumed.Yes
iapUnsuspendAdapter(callback)Resumes a suspended adapter. Any queued requests are processed before new requests are accepted.Yes
iapGetAdapterQueue(callback)Returns the requests currently waiting in the throttle queue, if throttling is enabled.Yes
iapTroubleshootAdapter(props, persistFlag, adapter, callback)Checks adapter performance by running connectivity, health check, and basic GET calls.Yes
iapRunAdapterHealthcheck(adapter, callback)Returns the results of a health check.Yes
iapRunAdapterConnectivity(callback)Returns the results of a connectivity check.Yes
iapRunAdapterBasicGet(callback)Returns the results of running basic GET API calls.Yes
iapMoveAdapterEntitiesToDB(callback)Pushes the adapter configuration from the entities directory into the database defined in the adapter service instance configuration inItential Platform Admin Essentials.Yes
genericAdapterRequest(uriPath, restMethod, queryData, requestBody, addlHeaders, callback)Calls a specified path on the external system. Useful for incorporating paths not yet built into the adapter. You must know the endpoint and input format specific to the actions you want to perform.Yes
genericAdapterRequestNoBasePath(uriPath, restMethod, queryData, requestBody, addlHeaders, callback)The same as genericAdapterRequest, but does not prepend base_path or version to the path.Yes
iapHasAdapterEntity(entityType, entityId, callback)Verifies the adapter has the specified entity.No
iapVerifyAdapterCapability(entityType, actionType, entityId, callback)Verifies the adapter can perform the specified action on the specified entity.No
iapUpdateAdapterEntityCache()Updates the entity cache.No

Constructor

The constructor instantiates the AdapterBase superclass. If you need to reference your own custom properties, capture them here. Custom properties must be defined in propertiesSchema.json.

1constructor(prongid, properties) {
2 // Instantiate the AdapterBase super class
3 super(prongid, properties);
4
5 // Uncomment if you have things to add to the constructor, such as using your own properties.
6 // Otherwise the constructor in adapterBase will be used.
7 // Capture custom properties - they need to be defined in propertiesSchema.json
8 if (this.allProps && this.allProps.myownproperty) {
9 mypropvariable = this.allProps.myownproperty;
10 }
11}

Adapter broker methods

These methods integrate the adapter withItential Platform brokers.

Method signatureDescriptionWorkflow task?
hasEntities(entityType, entityList, callback)Used by theItential Platform Device Broker to determine whether the adapter has a specific entity and item.No
getDevice(deviceName, callback)Returns the details of the requested device.Yes
getDevicesFiltered(options, callback)Returns the list of devices matching the criteria in the options filter.Yes
isAlive(deviceName, callback)Returns whether a device’s status is active.Yes
getConfig(deviceName, format, callback)Returns the configuration for the selected device.Yes
iapGetDeviceCount(callback)Returns the total count of devices.Yes

Specific adapter methods

Each method that calls the external system follows the same four-part structure in adapter.js. The sections below describe each part and show an example.

Part 1: Parameters and logging

Define the method parameters and set the origin string used for trace logging and error handling. The number and type of parameters vary depending on what data the external system requires — a method can take zero or more parameters in addition to callback.

1sampleAPIcall(param1, param2, callback) {
2 const meth = 'adapter-sampleAPIcall';
3 const origin = `${this.id}-${meth}`;
4 log.trace(origin);

Part 2: Data validation

Validate required parameters before building the request. Use formatErrorObject to produce consistently formatted errors. The parameters to formatErrorObject are the error origin, a key from error.json (used as a display string if no matching key is found), an array of variables to populate the message, the error code from the external system, the raw response, and the stack trace or exception.

1/* HERE IS WHERE YOU VALIDATE DATA */
2if (param1 === undefined || param1 === null || param1 === '') {
3 const errorObj = this.requestHandlerInst.formatErrorObject(
4 this.id, meth, 'Missing Data', ['param1'], null, null, null
5 );
6 log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
7 return callback(null, errorObj);
8}

Part 3: Construct the request object

Build the reqObj that will be passed to the adapter libraries. Most fields are optional — include only what the specific call requires.

1/* HERE IS WHERE YOU SET THE DATA TO PASS INTO REQUEST */
2// Format and prepare parameters as needed before building the object.
3
4const reqObj = {
5 payload: bodyToSendOnCall, // formatted based on requestDatatype
6 uriPathVars: pathVariablesArray, // array of path variable values
7 uriQuery: queryParams, // JSON object of query parameters
8 uriOptions: optionParams, // JSON object of option parameters
9 addlHeaders: callSpecificAdditionalHeaders, // JSON object of additional headers
10 authData: dynamicAuthenticationBodyData, // JSON object for dynamic auth data
11 callProperties: dynamicCallProps, // JSON object matching property structure
12 filter: dynamicResponseFilter, // JSONQuery string to filter the response
13 priority: 1, // number corresponding to a defined priority
14 event: eventname // event to trigger when data is returned
15};

Part 4: Call to the adapter libraries

Pass the reqObj to identifyRequest. The entity must match the name of the entity directory, and action must match the name of the action in action.json. The returnDataFlag controls whether the adapter libraries return the full response payload (true) or just a success/fail result (false).

You can customize error handling and modify the returned data in the callback before passing it back toItential Platform. When possible, define translation in the schema and let the adapter libraries handle it rather than transforming data in the callback.

1// identifyRequest(entity, action, requestObj, returnDataFlag, callback)
2return this.requestHandlerInst.identifyRequest('entity', 'action', reqObj, true, (irReturnData, irReturnError) => {
3
4 // Return any error from the libraries
5 if (irReturnError) {
6 /* HERE IS WHERE YOU CAN ALTER THE ERROR MESSAGE */
7 return callback(null, irReturnError);
8 }
9
10 // Return an error if the response has no data
11 if (!Object.hasOwnProperty.call(irReturnData, 'response')) {
12 const errorObj = this.requestHandlerInst.formatErrorObject(
13 this.id, meth, 'Invalid Response', ['action'], null, null, null
14 );
15 log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
16 return callback(null, errorObj);
17 }
18
19 /* HERE IS WHERE YOU CAN ALTER THE RETURN DATA */
20 return callback(irReturnData, null);
21});