Faslu Rajan
Faslu Rajan

Reputation: 3

Using onWrite Trigger for Realtime database in Firebase function

I designed a flutter application using dart and firebase backend. I want to get triggered when a user creates, delete, or updates anything in the database. I understood onCreate,onRemoved, and onUpdate methods. I wrote a javascript code in the firebase cloud function. I need to send a notification when a trigger happens. I don't want to use 3 different triggers. I want to use onWrite trigger only.

This is my database.

enter image description here

There are four departments called comp, civil, elect, and mech. I want to get triggered when database changes happen in a single onWrite trigger!

My First question is, I want to differentiate whether it is created or delete or update from onWrite trigger. I know it will trigger for all 3 events. But how can I differentiate it?

This is my code for onCreate...

exports.noticeAddedComp = functions.database.ref('main/notices/comp/{id}').onCreate( async evt =>  {

var token = ['dxnfr3dq6_Y:APA91bHavtoP62l296qzVoBhzQJbMFA']
const payload = {
    notification:{
        title : 'Message from Cloud',
        body : 'This is your body',
        sound : 'default'
    },
    data:{
    message : 'Thi is new Push',
    click_action : 'FLUTTER_NOTIFICATION_CLICK',
    }
};
        await admin.messaging().sendToDevice(token,payload);

});

Above code is working. But it is for onCreate.

My second question is, Do I need to write four onWrite trigger codes for four departments?

Upvotes: 0

Views: 1655

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

You can use the change.before and change.after properties to determine whether the node was created, deleted, or updated in a onWrite handler:

exports.noticeAddedComp = functions.database.ref('main/notices/comp/{id}')
.onWrite( async (change, context) =>  {
  if (!change.before.exists()) console.log("New node: "+change.after.key);
  if (!change.after.exists()) console.log("Deleted node: "+change.before.key);
  if (change.before.exists() && change.after.exists()) console.log("Updated node: "+change.after.key)
  ...
});

You can attach a Cloud Function to all departments at once, by including another parameter into its path:

exports.noticeAddedComp = functions.database.ref('main/notices/{dept}/{id}')
.onWrite( async (change, context) =>  {
  console.log("Triggered for department: "+context.params.dept);
  ...
})

Upvotes: 2

SempaiLeo
SempaiLeo

Reputation: 344

You can check if evt.after.data().property; is either null or doesn't exist, meaning it is deleted.

EDIT:

Scenario when you create something (document or field) :

Creation of the field would mean that the field in "before" doesn't exist at all, and in "after" it exists, but can be null.

Scenario when you update something

Field in the "before" is not the same as the one in "after".

Upvotes: 0

Related Questions