0

I am sending push notification by the following way:

exports.sendPushNotification = 
functions.database.ref('/chat_rooms/{id}').onWrite(event => {

console.log(event);
const original = event.data.val();
const reciverId = original['receiverID'];
const text = original['text'];
const senderName = original['senderName'];
var path = 'fcmToken/' + reciverId;

const payload = {
notification: {

title :senderName,
body: text,
badge:'7',
sound:'default',

    }
};
return admin.database().ref(path).once('value').then(allToken => {
    if (allToken.val()){
      var firebaseReceiverID = allToken.val();
      var firebaseToken = firebaseReceiverID['firebaseToken'];

     return admin.messaging().sendToDevice(firebaseToken,payload).then(response => {
     });
      };
   });
 });

My firebase database structure isenter image description here like this: how to send push if any child is added under chatroom(to detect the path)

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
Saurabh pandey
  • 260
  • 1
  • 11
  • is the current push notification being sent? what are you getting here `console.log(event);`? – Peter Haddad Dec 19 '17 at 11:25
  • when new chat_rooms is added then it execute otherwise it is not executed I want to execute when msg is added uder chatroom – Saurabh pandey Dec 20 '17 at 07:40
  • yes thats correct, so what is the problem? Thats the purpose of onWrite it get triggered when anything is added at that location. Where is msg, in the database? – Peter Haddad Dec 20 '17 at 07:44
  • Hi peter thanks, the problem is that how to get the latest msg added under chat room I thin the structure should be like this functions.database.ref('/chat_rooms/{PerticularChatRoom_id}/{id}').onWrite(event => { } here how to fetch Perticular chat room id where msg is added – Saurabh pandey Dec 20 '17 at 08:05
  • functions.database.ref('/chat_rooms/{PerticularChatRoom_id}/‌​{id}').onWrite(event => { } here perticular chat room id how to get it – Saurabh pandey Dec 20 '17 at 08:58

1 Answers1

2

onWrite is a database trigger, so everytime you add data under the location that you specify it will be triggered.

Now if you want to get the id you can do this:

export.sendPushNotification=functions.database.ref('/chat_rooms/{PerticularChatRoomid}/‌​‌​{id}').onWrite(eve‌​nt => { 

console.log(event);
const chatroomid=event.params.PerticularChatRoomid;

}

This way you will be able to get the PerticularChatRoomid from the database.

To get the values of the wildcards {id}, always use event.params

More info in this link: https://firebase.google.com/docs/functions/database-events

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134