I have a Firebase Cloud Function that monitors changes to my Realtime Database based on a sample provided in Firebase's documentation.
My function is working correctly and executes for every change as it was written to do.
With that said, and, as per Firebase's recommendation:
• Debouncing - when listening to realtime changes in Cloud Firestore, this solution is likely to trigger multiple changes. If these changes trigger more events than you want, manually debounce the Cloud Firestore events.
I would like to do just that.
Can anyone offer a good approach?
If we look at this function based on Firebase's example:
exports.onUserStatusChanged = functions.database.ref('/status/{uid}').onUpdate(
async (change, context) => {
// Get the data written to Realtime Database
const eventStatus = change.after.val();
// Create a reference to the corresponding Firestore document
const userStatusFirestoreRef = firestore.doc(`status/${context.params.uid}`);
// re-read the current data and compare the timestamps.
const statusSnapshot = await change.after.ref.once('value');
const status = statusSnapshot.val();
// If the current timestamp for this data is newer than
// the data that triggered this event, we exit this function.
if (status.last_changed > eventStatus.last_changed) {
return null;
}
// Otherwise, we convert the last_changed field to a Date
eventStatus.last_changed = new Date(eventStatus.last_changed);
// write it to Firestore
userStatusFirestoreRef.get().then((user: any) => {
user.forEach((result: any) => {
result.ref.set(eventStatus, { merge: true })
});
});
return;
});
How should i attempt to debounce its execution?
Can i attempt to debounce the .onUpdate()
event?
I originally thought the following would suffice:
functions.database.ref('/status/{uid}').onUpdate(
debounce(async(change:any, context:any) => {
...
}, 10000, {
leading: true,
trailing: false
})
);
But, thanks to @doug-stevenson for pointing out that attempting to debounce the onUpdate event in this way will not work for the following reason:
"That's not going to work because each invocation of the function might happen in a completely different server instance with no shared context."