Enterprise FeatureThis feature is available only to customers with an enterprise Platform subscription. Contact us to discuss enabling it on your account.
Reactor lets you execute custom code in reaction to a supported event, such as when an action is created or a Thng's property value is changed. Every application can have a Reactor script attached, which is created the first time a script is uploaded, including any required dependencies.
Reactor scripts are written in Node.js and can use NPM packages through a conventional package.json
file. They're automatically provided with the latest version of evrythng-extended.js through a global EVT
object and app
(EVT.App
) scope for requests. You must not remove this basic dependency, or the script could fail to execute.
After they're configured configured, Reactor scripts run whenever an action is created, a Thng/product property changes value, or a scheduled event is triggered, depending on which callbacks appear in the script. This allows you to execute complex logic in the context of virtually any Platform resource update, driving rich integrations and experiences.
Scripts that make use of the async
/await
language features can be greatly simplified by using the reactor-runasync
helper function. See the async/await script example below for more details.
Reactor WalkthroughSee the Reactor Walkthrough for an in-depth walkthrough of the Reactor, including example use cases and patterns for implementation.
Legacy SDK VersionLegacy reactor scripts can use up to evrythng-extended.js v4.7.2. For new Reactor scripts, we recommend using the new evrythng.js SDK.
Node VersionsThe version of Node that a Reactor script uses depends on when the script was created, as new LTS versions are adopted. Use
process.version
to see which version is being used.\n\nCurrent version: Node v10.x\nUntil 9 January 2020: Node v8.12\nUntil 1 May 2019: Node v6.10.2\nUntil 13 April 2017: Node v4.3
API Status
General Availability:
/projects/:projectId/applications/:applicationId/reactor/script
/projects/:projectId/applications/:applicationId/reactor/script/status
/projects/:projectId/applications/:applicationId/reactor/schedules
/projects/:projectId/applications/:applicationId/reactor/schedules/:scheduleId
/projects/:projectId/applications/:applicationId/reactor/logs
/projects/:projectId/applications/:applicationId/reactor/script
/projects/:projectId/applications/:applicationId/reactor/script/status
/projects/:projectId/applications/:applicationId/reactor/schedules
/projects/:projectId/applications/:applicationId/reactor/schedules/:scheduleId
/projects/:projectId/applications/:applicationId/reactor/logs
Scripts
We provide two ways to upload Reactor scripts to EVRYTHNG Platform:
- The simple API allows a script file and an optional NPM dependencies descriptor file (
package.json
) to be uploaded in an update request body. - The bundle API lets you upload a full Node.js project as a
.zip
file.
We'll only consider the bundle API in detail here because the simple API comprises merely sending the script content or editing through the Dashboard on the Application Details page. You can update the script through the API or through the Dashboard.
Bundle Structure
Bundled scripts are provided in the form of a .zip
file with the following structure:
package.json
is a standard NPM dependencies package.json file, and can specify any other dependencies of the Reactor script.
Notes
- By default we include
evrythng-extended
in thepackage.json
file when an application is first created. You must not remove this or the Reactor could stop working. We provide it to allow you to see which version you're using, and update if necessary. \n\n* You must not include anynode_modules
in the bundle. Thepackage.json
file can specify these dependencies. \n\n*devDependencies
inpackage.json
are ignored by the Reactor when a bundle is uploaded and installed.
If the file isn't provided or no dependency to evrythng-extended.js
is specified, the latest version of evrythng-extended.js
is automatically included. We strongly advise you to state which specific version of the library you want to use. This avoids problems when new versions are released.
evrythng-extended.js
is specified, the latest version of evrythng-extended.js
is automatically included. We strongly advise you to state which specific version of the library you want to use. This avoids problems when new versions are released.Event Types
This section lists the types of events that can trigger a Reactor script.
-
onActionCreated
- When an action is created. -
onProductPropertiesChanged
- When one or more properties of a product have changed. -
onThngPropertiesChanged
- When one or more properties of a Thng have changed. -
onScheduledEvent
- When a scheduled event has occurred. Iffunction
in the schedule uploaded is a custom function name, that name is invoked instead, but only if it has been exported from the script.
onActionCreated
This event occurs every time an action is created and is visible to the application. The event
supplied to the handler is:
Reactor Filters: thng.*
, product.*
, user.*
, time
, Time, action.*
, Location, place.*
.
See also: ActionDocument
ActionDocument
onProductPropertiesChanged
This event occurs every time the properties of a product have been changed. The event
supplied to the handler is shown below.
If multiple updates to a property are provided in one update request, the behavior changes slightly. See Multiple Property Updates for more information.
Reactor Filters: product.*
, time
, Property.
See also: ProductDocument
, ReactorPropertyChangeDocument
ProductDocument
, ReactorPropertyChangeDocument
onThngPropertiesChanged
This event occurs every time the properties of a Thng have been changed.
NoteIf the new value is the same as the old value, this event doesn't execute.
The event
supplied to the handler is shown below.
If multiple updates to a property are provided in one update request, the behavior changes slightly. See Multiple Property Updates for more information.
Reactor Filters: thng.*
, product.*
, time
, Property.
See also: ThngDocument
,
ReactorPropertyChangeDocument
ThngDocument
,
ReactorPropertyChangeDocument
onScheduledEvent
When a scheduled event occurs, the only argument provided to the callback is the event
that was specified in the Reactor schedule resource when it was created.
See also: ReactorScheduleDocument
ReactorScheduleDocument
ReactorPropertyChangeDocument Data Model
This object contains the changes that occurred as an object of keys, each containing the old and new values.
Multiple Property Updates
If an update request includes multiple changes to a particular Thng or product property when the onThngPropertiesChanged
or onProductPropertiesChanged
callback is invoked, an allChanges
property is included. This is an array containing all the updates for that property change request.
The oldValue
, newValue
and timestamp
properties at the changed key level reflect the latest property update by timestamp. An example is shown below:
Script API
Reactor scripts are packaged with the latest version of evrythng-extended.js
(unless you specify the version you want to use). It's pre-configured with the application's Trusted Application API Key.
The table below describes the global variables in the Reactor script context:
evrythng-extended.js
also forwards the X-Evrythng-Reactor
header, which protects you against inadvertently creating a recursive loop (see Limits: Recursion).
If you re-configure evrythng-extended.js
or use an alternate way to communicate with the API, be sure you forward this header to prevent recursive loops.
evrythng-extended.js
or use an alternate way to communicate with the API, be sure you forward this header to prevent recursive loops.Debugging
You can create log messages from the Reactor script. A logger
instance is globally defined in the Reactor script. Use the following functions available to create log messages of differing levels of severity.
NoteReactor log entries are available for up to seven days after they are generated.
Filters
In most cases, you don't want your Reactor scripts to be executed on every event (action creation or property change) but only if some conditions are met. For example, suppose you want to react to action creation of type scans
and ignore the others. One obvious solution is to use an if
construction within the Reactor script.
The problem with this example is that for non-scan
actions, the Reactor script is still executed but doing nothing useful. It isn't a good practice because the Reactor script execution cost is non-trivial.
The recommended solution is to use the Reactor filters annotation syntax. The example below runs the script only when the action's type
is scans
.
Reactor filters' functionality is limited compared to full JavaScript but they're evaluated on an earlier step before a script is executed and so are much less costly.
Syntax
Reactor filters are defined as JavaScript comments (both //
and /* */
styles are supported). The filter syntax is described on the Filters page. Filters can be defined anywhere in the script, but we recommend placing each directly above the corresponding callback function definition. If using the bundle
Reactor type, filters must be defined in main.js
file.
The templates for filtering the three main callback types are shown below.
If for any reason the filter definitions aren't extracted from your Reactor script, no error is thrown. Reactor script functions are executed as if the filter has not been defined.
Filter Parameters
This is a list of parameters that you can use in the Reactor filter body, although not all of them are available in any particular context. See the Event Types section to see which are available for which callback.
Thng
-
thng.id
The action Thng’s ID. -
thng.identifiers.{identifierName}
The action Thng’s identifiers. -
thng.name
The action Thng’s name. -
thng.customFields.{customFieldName}
The action Thng’s custom fields. -
thng.tags
The action Thng’s tags. Lists of tags match for any of the listed tags (an OR condition).
Product
-
product.id
The action product’s ID. -
product.identifiers.{identifierName}
The action product’s identifiers. -
product.name
The action product’s name. -
product.customFields.{customFieldName}
The action product’s custom fields. -
product.tags
The action product’s tags. Lists of tags match for any of the listed tags (an OR condition).
User
-
user.gender
The action user’s gender. -
user.age
The action user’s years of age. -
user.customFields.{customFieldName}
The action user’s custom fields. -
user.locale
The action user’s locale.
Time
-
time
Number of milliseconds elapsed since Epoch at the time the action occurred. -
timeOfDay
Number of milliseconds elapsed since midnight in the action’s timezone. -
dayOfWeek
Day of the week in the action’s timezone. Possible values aremon
,tue
,wed
,thu
,fri
,sat
,sun
. -
dayOfMonth
Day of the month in the action’s timezone. Possible values are 1 to 31. -
month
Month in the action’s timezone. Possible values are 1 to 12. -
year
Year in the action’s timezone.
Action
-
action.customFields.{customFieldName}
The action’s custom fields. -
action.type
The action type
Property
-
propertyChangeOld.{propertyKey}
The old value of the property that changed. -
propertyChangeNew.{propertyKey}
The new value of the property that changed.
Location
-
timezone
The timezone where the action occurred. See the list of possible timezones. -
location.lat
The location latitude in degrees where the action occurred. -
location.lon
The location longitude in degrees where the action occurred. -
country
ISO 3166-1 alpha-2 country code where the action occurred
Place
-
place.id
The place’s ID. -
place.tags
The place’s tags. -
place.customFields.{customFieldName}
The place’s custom fields. -
place.distance
The place's distance from the scan in meters.
Limits
Execution Timeout
When triggered, a Reactor script must complete within a certain amount of time. If this isn't the case, the execution is aborted. See below for time constraints.
Recursion
A Reactor script could trigger itself by performing an operation against the REST API. This causes the script to trigger again (directly or indirectly). We provide a mechanism to protect the user from inadvertently causing an infinite recursion loop.
For example, if a script is triggered by the creation of an action, and if that script creates an action during its execution, this triggers itself again, and so on.
We limit the depth of such recursive calls and the total time allowed for the execution since the original event.
Build Timeout
The time required to download and package all the dependencies must not exceed the Build Timeout (see below). The build time depends on a lot of external factors. The timeout here is provided for guidance only.
Script Size
The scripts before and after build are limited in size.
Reactor Script API
The Reactor Script API allows you to view and replace the Reactor script for an application through the REST API instead of through the application details page in the Dashboard. You can view the status of an upload in progress and view and replace the manifest declaring the script's dependencies.
Jump To↓
ReactorScriptDocument Data Model
Update the Reactor Script
To update a reactor script, send a PUT request to the /projects/applications/reactor/script endpoint with the projectId
and applicationId
in the path and a new ReactorScriptDocument in the body.
Simple Request
Bundle Request
Response
Read the Reactor Script
Read the Reactor script associated with an application.
ReactorScriptStatusDocument Data Model
Read the Reactor Script Status
Read the status of a Reactor script update in progress.
Reactor Scheduler API
Jump To ↓
Create a Reactor Schedule Read all Reactor Schedules Read a Single Reactor Schedule Update a Reactor Schedule Delete a Reactor Schedule
Besides the three standard event entry points into a Reactor script, you can schedule any developer-defined function to be called at a later time. When the function is called, it's passed a predefined event object assigned at the time of scheduling.
The scheduled event can be a one-time execution (delayed, scheduled, or immediate), or it can be a repetitive event, defined by a cron
expression. The format of this expression is:
"cron": "* * * * * *"
| | | | | |
| | | | | day of the week (1 - 7)
| | | | month of the year (1 - 12)
| | | day of the month (1 - 31)
| | hour of the day (0 - 23)
| minute past the hour (0 - 59)
second past the minute (0 - 59)
See this tutorial for more format details and special options available. The list below shows some sample cron expressions for common scenarios:
-
"0 0 12 * * ?"
Run at 12 noon every day, every month, regardless of the day of the week. -
"0 0/30 * * * ?"
Run at 0 and 30 minutes past the hour, every hour, every day, every month, regardless of the day of the week. -
"0 0 0 1 * ?"
Run at midnight on the first day of the month, every month, regardless of the day of the week.
ReactorScheduleDocument Data Model
Notes
- Only one of
executeAt
orcron
is allowed, or none.\n\n* We can only guarantee minute-precision invocation forexecuteAt
, but smaller granularities usually execute as required. \n\n* IfexecuteAt
isn't in the future, the event is executed immediately.\n\n* We perform some validation of cron expressions and allow the lowest granularity of 2 minutes. Cron time is in UTC.\n\n* By default, we assume thefunction
name isonScheduledEvent
. We export anonScheduledEvent
function if it's defined in the script. If you're using another function, it must be explicitly exported.\n\n* If you overridemodule.exports
and omit your schedule function handler (including the defaultonScheduledEvent
), the handler isn't called.
Create a Reactor Schedule
To create a Reactor schedule, send a POST request to the projects/applications/reactor/schedules endpoint with the projectId
and applicationId
in the path and a ReactorScheduleDocument
in the body describing how it should behave.
Read all Reactor Schedules
To get all the current schedules of the specified application, send a GET request to the projects/applications/reactor/schedules endpoint with the projectId
and applicationId
in the path.
Read a Single Reactor Schedule
To get a single Reactor schedule, send a GET request to the projects/applications/reactor/schedules endpoint with the projectId
, applicationId
, and scheduleId
in the path.
Update a Reactor Schedule
To update the fields of an existing Reactor schedule document, send a PUT request to the projects/applications/reactor/schedules endpoint with the projectId
, applicationId
, and scheduleId
in the path and the ReactorScheduleDocument in the body.
Delete a Reactor Schedule
To delete a Reactor schedule, send a DELETE request to the projects/applications/reactor/schedules endpoint with the projectId
, applicationId
, and scheduleId
in the path.
NoteA one-time scheduled event (using
executeAt
instead ofcron
) is deleted after it has elapsed.
Reactor Logs API
Jump To ↓
ReactorLogEntryDocument Data Model Read the Reactor Logs Delete the Reactor Logs
The Reactor logs created by using the logger
object in the script itself can be read through the EVRYTHNG API. The Reactor logs are created automatically after execution of the Reactor script, as long as done()
was called to mark the end of script execution. If done
isn't called, logs aren't created.
NoteReactor log entries are available for up to seven days after they're generated.
ReactorLogEntryDocument Data Model
Read the Reactor Logs
To get the Reactor logs, send a GET request to the projects/applications/reactor/logs endpoint with the projectId
and applicationId
in the path.
You can use a filtered query to get logs of a specific level:
Delete the Reactor Logs
To delete the Reactor logs, send a DELETE request to the projects/applications/reactor/logs endpoint with the projectId
and applicationId
in the path.
To delete the Reactor logs of a specific log level, you can use a filtered query like in example Read the Reactor Logs.
Testing Scripts Locally
To test the Reactor script on your computer, we provide the reactor-testing
GitHub repository. This repository lets you mock up all types of events to test how the script executes and behaves locally before using it on the Platform. To get started, follow the instructions in the repository's README.md
file.
reactor-testing
GitHub repository. This repository lets you mock up all types of events to test how the script executes and behaves locally before using it on the Platform. To get started, follow the instructions in the repository's README.md
file.Example Scripts
Starter Script Example
The example script below contains sample implementations the four possible callback types and serves as a good starting point for any Reactor script.
Async/await Script Example
If your script is running with Node 8 or newer (see the note about Node versions at the top of this page), you can take advantage of async
/await
language features to delegate safely calling done()
and catching errors using the reactor-runasync
helper function package. For example:
Twilio Example
Send a message using Twilio as a result of action creation.
Global Reactor Rules
Global Reactor rules can be used when Reactor is to run outside a project. This means they are run for every action created and Thng/product property updated in the entire account. Global Reactor rules run as an Operator, not as a Trusted Application. Therefore, a global operator
SDK scope object is available to use.
Creating the Global Rules Project
By default, the global rules project is not created in the account. To create a global rules project, send a GET request to the projects API and use the account ID as the project ID parameter:
Operator Context
Global rules work exactly the same as project scoped reactor rules except that the rules have an Operator context available.