Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase: Checking for 'write or delete' for onWrite Events

Tags:

I have the following functions that listens to an onWrite event for a database trigger like so:

exports.sendNotifications = functions.database.ref('/events/{eventId}/registered')         .onWrite(event => {              ...          }); 

The above function is called regardless whether the node is deleted or added. How do I check if the onWrite event is a 'delete' event for that particular node, or a 'add' event, such that this function only gets called when it is a 'add' event.

like image 596
Koh Avatar asked Jun 17 '17 07:06

Koh


2 Answers

If you want to only trigger this function for an add event, the onCreate() trigger would be the way to go.

However, you can also detect if it is an add event inside your onWrite() using the before and after properties of the Change object:

exports.sendNotifications = functions.database.ref('/events/{eventId}/registered')   .onWrite((change, context) => {     if (change.before.exists()) {       //update event       return null;     } else if (!change.after.exists()) {       //delete event       return null;     } else {       //add event       //do stuff     }    }); 

Find more details in the documentation:

https://firebase.google.com/docs/functions/database-events#handle_event_data

like image 128
Sourobrata Sarkar Avatar answered Sep 27 '22 22:09

Sourobrata Sarkar


The event that is passed into the function contains both the previous data and the new data for the location that triggered the function. With these two pieces of information, you can deduct whether it was a new write, an update, or a delete.

From the Firebase documentation for database functions:

exports.makeUppercase = functions.database.ref('/messages/{pushId}/original') .onWrite(event => {   // Only edit data when it is first created.   if (event.data.previous.exists()) {     return;   }   // Exit when the data is deleted.   if (!event.data.exists()) {     return;   } 
like image 45
Frank van Puffelen Avatar answered Sep 27 '22 23:09

Frank van Puffelen