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)
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).
"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).