Functions

Functions are snipets of code executed when an API REST endpoint is called. They can also be called from other parts of the cloud code like triggers and jobs. They are useful to encapsulate business logic that you don't want into the devices.

Each function must contain a function main(params, callback)

Where:

params is the input of the function which can be a string, object, array,...

callback(error, result) is a function to be called when the function ends. Can contain a parameter string error if the funciton needs to report an error. If the error is null it can contain a result which will be returned as a response.

The execution of a function is limited to 20 seconds. If the execution takes longer, the server will end the sandbox. Note that if the function is called inside a trigger the execution time will be the 2 seconds of a trigger.

Calling a function

There are two ways to call a function, from the API REST and from the Cloud Code (jobs and triggers).

POST https://api.thethings.io/v2/things/:thingToken/code/function/:fname
{
    "params":   THE FUNCTION INPUT GOES HERE
}

To call the function from a trigger, a job or another function you can do:
thethingsAPI.cloudFunction(fname, params, callback)

  • fname: string The function name.
  • params: Any type The input.
  • callback: function(err,result) If the execution was successful err should be null.

The function input can be any valid type for JSON (Number, String, Boolean, Object, Array or null).

Examples

Here are some examples. Of course you can also do useful things like turning miles to kilometers with them.

Answer to the Ultimate Question of Life, the Universe, and Everything

When you need to know any answer you can simply do:

Generate events

You can generate events from inside the code. The following code generates a simple event which stores the value to an event called 'temperature'. To be later retrieved from a job:

The always errored function

This function is always returning errors:

Some asynchronous stuff

You may be wondering why you need to call a callback instead of the classical return. With callback you can do things like:

Learn more