Code package tutorials
JSON ADMIN API tutorials for using code packages
Tutorial on creating a JavaScript transform
This tutorial creates a transform that processes MQTT messages sent to the topic "robot1_temperature"
. The transform extracts a Celsius temperature from the JSON payload, converts it to Fahrenheit, and writes each temperature to the appropriate fields in the table "temperature_celsius"
and "temperature_fahrenheit"
. The transform also creates a status field named temperature_status
and populates it with information about the temperature, such as "cold"
and "normal"
.
Send an MQTT message
Send a message to the MQTT topic named "robot1_temperature"
.
{ "temperature": 21.111 }
When a record is inserted into an integration table, the source_payload
field contains JSON data, such as the following JSON object, which contains a Fahrenheit temperature.
Create JavaScript code
Use the following tutorial to convert a Fahrenheit temperature to Celsius
The following code extracts the "temperature_celsius"
property from the source_payload
field of the current record in an integration table. It converts the Celsius temperature to Fahrenheit and stores the result in the temperature_fahrenheit
field in the current record of an integration table. The temperature in Celsius is then stored in the temperature_celsius
field in the integration table.
record.temperature_celsius = record.source_payload.temperature record.temperature_fahrenheit = getFahrenheitFromCelsius(record.temperature_celsius) record.temperature_status = calculateTemperatureStatus(record.temperature_fahrenheit) function getFahrenheitFromCelsius(temperature_celsius){ return (temperature_celsius * 1.8) + 32; } function calculateTemperatureStatus(temperature_fahrenheit){ switch (true) { case (temperature_fahrenheit < 0): return "alert: too cold"; case (temperature_fahrenheit < 32): return "cold"; case (temperature_fahrenheit > 80): return "hot"; case (temperature_fahrenheit > 140): return "alert: too hot"; default: return "normal"; } }
Create a code package
Run the following "createCodePackage" action to create a JavaScript code package named "convertTemperature"
.
{ "authToken": "MyTokenHere", "api": "admin", "action": "createCodePackage", "params": { "databaseName": "faircom", "ownerName": "admin", "codeName": "convertTemperature", "codeLanguage": "javascript", "codeType": "transform", "codeStatus": "developing", "description": "1. Copies the value from the temperature property in source_payload to the temperature_fahrenheit field.\n2. Converts temperature_fahrenheit into Celsius and stores it in the temperature_celsius field.\n3. Stores alerts about temperature in temperature_status field.", "metadata": {}, "comment": "optional comment about the current version", "codeFormat": "utf8", "code": "// The server runs the following JavaScript code, which is registered in the server as a transform method.\nrecord.temperature_fahrenheit = record.source_payload.temperature\nrecord.temperature_celsius = getCelsiusFromFahrenheit(record.temperature_fahrenheit)\nrecord.temperature_status = calculateTemperatureStatus(record.temperature_fahrenheit)\n\nfunction getCelsiusFromFahrenheit(temperature_fahrenheit){\n return (temperature_fahrenheit - 32) / 1.8;\n}\n\nfunction calculateTemperatureStatus(temperature_fahrenheit){\n switch (true) {\n case (temperature_fahrenheit < 0):\n return \"alert: too cold\";\n case (temperature_fahrenheit < 32):\n return \"cold\";\n case (temperature_fahrenheit > 80):\n return \"hot\";\n case (temperature_fahrenheit > 140):\n return \"alert: too hot\";\n default:\n return \"normal\";\n }\n}" } }
Note that for the "code" value to be valid JSON, it must be a single string with no line breaks.
Create a transform
{ "authToken": "MyTokenHere", "api": "hub", "action": "createTransform", "params": { "transformName": "transformFahrenheitToCelsius", "transformActions": [ { "transformActionName": "transformStep-ConvertAndCategorizeTemperature", "transformService": "javascript", "inputFields": ["source_payload"], "outputFields": [ "temperature_celsius", "temperature_fahrenheit", "temperature_status" ], "transformParams": { "codeName": "convertTemperature", "databaseName": "ctreeSQL", "ownerName": "admin", "codePackagePoperties": {}, "outputFieldDefinitions": [ { "name": "temperature_celsius", "type": "double" }, { "name": "temperature_fahrenheit", "type": "double" }, { "name": "temperature_status", "type": "varchar", "length": 100 } ] } } ] } }
"codePackageProperties" is an optional parameter that lets the user add run-time properties and values to JavaScript before the server runs the code When the value is an object, it contains properties and values that the server adds to the JavaScript engine.
"codePackageProperties": { "myCustomProperty1": "a string that the JavaScript code will use", "myCustomProperty2": 42 },
Tutorial on creating a JavaScript transform
This tutorial creates a Code Package to use when retrieving records from JSON DB. The advantage of this method is that the data in the database is not affected. Use this method when you want to preserve the original data.
This tutorial assumes that you have already logged in using createSession
and have a valid authToken
.
Create a table to use this Code Package against
POST the following JSON to the FairCom endpoint:
{ "api": "db", "action": "createTable", "params": { "databaseName": "faircom", "tableName": "testTable", "fields": [ { "name": "numberField", "type": "double" }, { "name": "numberFieldRouonded", "type": "double" }, { "name": "stringField", "type": "varchar", "length": 50 }, { "name": "stringFieldTrimmed", "type": "varchar", "length": 50 } ] }, "authToken": "replaceWithAuthTokenFromCreateSession" }
Replace the authToken
with the one from your current session
Insert records into the table
POST the following JSON to the FairCom endpoint:
{ "api": "db", "action": "insertRecords", "params": { "databaseName": "faircom", "tableName": "testTable", "dataFormat": "objects", "sourceData": [ { "numberField": 1234.5678, "numberFieldRounded": 1234.5678, "stringField": " FairCom ", "stringFieldTrimmed": " FairCom " }, { "numberField": 8765.4321, "numberFieldRounded": 8765.4321, "stringField": " Edge ", "stringFieldTrimmed": " Edge " }, { "numberField": 2112.2112, "numberFieldRounded": 2112.2112, "stringField": " Rush ", "stringFieldTrimmed": " Rush " } ] }, "authToken": "replaceWithAuthTokenFromCreateSession" }
Note that each varchar
field has spaces around the record and that each double field has four digits after the decimal place.
Create JavaScript code
POST the following JSON to the FairCom endpoint:
{ "api": "admin", "action": "createCodePackage", "params": { "ownerName": "admin", "databaseName": "faircom", "codeName": "roundAndTrim", "codeLanguage": "javascript", "serviceName": "javascript", "codeType": "getRecordsTransform", "codeStatus": "active", "description": "Test transform for rounding a numeric field and trimming a string field", "codeFormat": "utf8", "comment": "Original code", "code": "transformedRecords.forEach( function( record ){ record.numberFieldRounded = parseFloat( record.numberFieldRounded.toFixed( 2 ) );record.stringFieldTrimmed = record.stringFieldTrimmed.trim(); } );\n" }, "authToken": "replaceWithAuthTokenFromCreateSession" }
Note that the actual code when formatted looks like this:
transformedRecords.forEach ( function( record ) { record.numberFieldRounded = parseFloat( record.numberFieldRounded.toFixed( 2 ) ); record.stringFieldTrimmed = record.stringFieldTrimmed.trim(); } );
Here is a pseudocode explanation for this Code Package:
For each record processed:
Modify the
numberFieldRounded
field to two fixed decimal placesModify the
stringFieldTrimmed
field by trimming leading and trailing whitespace
Retrieve records using the code package
POST the following JSON to the FairCom endpoint:
{ "api": "db", "action": "getRecordsByTable", "params": { "databaseName": "faircom", "tableName": "testTable", "transformCodeName": "roundAndTrim" }, "authToken": "replaceWithAuthTokenFromCreateSession" }
Note that this is a normal getRecordsByTable
request with one exception: the params block contains the "transformCodeName"
property, which is set to the name of our Code Package "roundAndTrim"
.
The response from that getRecordsByTable
will contain a data block that looks like this:
[ { "changeId": 1525, "id": 1, "numberField": 1234.5678, "numberFieldRounded": 1234.57, "stringField": " FairCom ", "stringFieldTrimmed": "FairCom" }, { "changeId": 1525, "id": 2, "numberField": 8765.4321, "numberFieldRounded": 8765.43, "stringField": " Edge ", "stringFieldTrimmed": "Edge" }, { "changeId": 1525, "id": 3, "numberField": 2112.2112, "numberFieldRounded": 2112.21, "stringField": " Rush ", "stringFieldTrimmed": "Rush" } ]
Note that the "numberFieldRounded"
fields have only two decimal places and all of the "stringFieldTrimmed"
fields have no leading or trailing whitespace.
You can confirm that the Code Package worked by calling getRecordsByTable
again, but without the "transformCodeName"
property:
{ "api": "db", "action": "getRecordsByTable", "params": { "databaseName": "faircom", "tableName": "testTable" }, "authToken": "replaceWithAuthTokenFromCreateSession" }
The response will contain a data block that looks like this:
[ { "changeId": 3362, "id": 1, "numberField": 1234.5678, "numberFieldRounded": 1234.5678, "stringField": " FairCom ", "stringFieldTrimmed": " FairCom " }, { "changeId": 3362, "id": 2, "numberField": 8765.4321, "numberFieldRounded": 8765.4321, "stringField": " Edge ", "stringFieldTrimmed": " Edge " }, { "changeId": 3362, "id": 3, "numberField": 2112.2112, "numberFieldRounded": 2112.2112, "stringField": " Rush ", "stringFieldTrimmed": " Rush " } ]
The "numberFieldRounded"
fields and the "stringFieldTrimmed"
fields show that the data in the database has not been affected by the Code Package.