Saurabh pandey
Saurabh pandey

Reputation: 250

Send push notification From firebase by using Firebase cloud Functions

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)

Upvotes: 0

Views: 546

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80944

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

Upvotes: 2

Related Questions