使用Firebase云功能从firebase发送推送通知

时间:2017-12-19 11:04:49

标签: ios node.js firebase firebase-realtime-database firebase-cloud-messaging

我通过以下方式发送推送通知:

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 => {
     });
      };
   });
 });

我的firebase数据库结构是enter image description here,如下所示:     如果在聊天室下添加任何子节点(检测路径),如何发送推送

1 个答案:

答案 0 :(得分:2)

onWrite是一个数据库触发器,因此每当您在指定的位置添加数据时,它都会被触发。

现在,如果你想获得id,你可以这样做:

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

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

}

这样您就可以从数据库中获取PerticularChatRoomid

要获取通配符{id}的值,请始终使用event.params

此链接中的更多信息:https://firebase.google.com/docs/functions/database-events

相关问题