使用Firebase云功能从firebase发送推送通知
我通过以下方式发送推送通知:
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数据库结构是像这样的:如果在聊天室下添加任何子节点(如检测路径),如何发送推送
回答如下:onWrite
是一个数据库触发器,因此每次在指定的位置添加数据时都会触发它。
现在,如果你想获得id,你可以这样做:
export.sendPushNotification=functions.database.ref('/chat_rooms/{PerticularChatRoomid}/{id}').onWrite(event => {
console.log(event);
const chatroomid=event.params.PerticularChatRoomid;
}
这样您就可以从数据库中获取PerticularChatRoomid
。
要获取通配符{id}
的值,请始终使用event.params
更多信息在此链接:https://firebase.google/docs/functions/database-events