Cloud Functions as triggers in the Cloud Database

Cloud Functions as trigger on the Cloud Database

Cloud Functions are an incredibly flexible tool. Fetch any kind of data from the net, process it, store it in your Cloud Database or return it to your mobile application – Cloud Functions cover all requirements.

Did you know that Cloud Functions can be executed as triggers on collections?

Just tell that you want to attach the function to a collection as a trigger. Cloud Functions can be executed on update and insert for documents in any collection in your Cloud Database. The servers will automatically run your Cloud Function for each record sent in a request.

A Cloud Database insert API call can post multiple records at the same time. Your Cloud Function will be executed for each record in the request.

The Cloud Functions documentation explain that all parameters sent to a function are stored in the $params variable, available within the body of your Cloud Function. When a function is executed as a trigger the document data from the Cloud Database is sent to the Cloud Function using the same array.

If the request was an insert the “inserted” property of the array will contain the new record received by the data APIs. In the case of an update the “updated” property will be populated and will contain two sub-object: old, and new – each object will contain the document before and after it was updated.

For example you could create a Cloud Function sending a signal to a PubNub or Pusher real time channel when data is received.

Cloud Functions can also be scheduled for execution or called on-demand from your mobile application. How are you planning to use them?