When using the cloud functions on firebase, with the onUpdate trigger, how do I retrieve the record that has been updated (in other words, the record that triggers the function)? I am using JavaScript to interface with the Firebase database.
Asynchronous listeners: Data stored in a Firebase Realtime Database is retrieved by attaching an asynchronous listener to a database reference. The listener is triggered once for the initial state of the data and again anytime the data changes. An event listener may receive several different types of events.
Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now and your app will be connected to Firebase.
Set the event handler Functions let you handle Realtime Database events at two levels of specificity; you can listen for specifically for only creation, update, or deletion events, or you can listen for any change of any kind to a path.
The first argument passed your onUpdate handler function is a Change object. This object has two properties, before
and after
, both DataSnapshot objects. These DataSnapshot objects describe the contents of the database before and after the change that triggered the function.
exports.foo = functions.database.ref('/location-of-interest')
.onUpdate((change) => {
const before = change.before // DataSnapshot before the change
const after = change.after // DataSnapshot after the change
})
per https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder#onUpdate
onUpdate(handler) => function(functions.Change containing non-null functions.database.DataSnapshot, optional non-null functions.EventContext)
So I'm guessing that you just need to pass a callback function into the onUpdate(callback)
trigger. Per the documentation, the record of that has been updated would seem to be passed in as the first argument. I would start by logging the arguments object inside the callback function.
The example inside the docs is:
// Listens for new messages added to /messages/:pushId/original and creates an
// uppercase version of the message to /messages/:pushId/uppercase
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const original = snapshot.val();
console.log('Uppercasing', context.params.pushId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database returns a Promise.
return snapshot.ref.parent.child('uppercase').set(uppercase);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With