1

我正在尝试制作向给定用户发送推送通知的云端功能。使用云端功能发送推送通知用于Firebase

用户进行一些更改,并在Firebase数据库中的节点下添加/更新数据(该节点表示用户标识)。在这里我想触发一个向用户发送推送通知的函数。

我对DB中的用户具有以下结构。

Users 

- UID 
- - email 
- - token 

- UID 
- - email 
- - token 

直到现在我有这样的功能:

exports.sendNewTripNotification = functions.database.ref('/{uid}/shared_trips/').onWrite(event=>{ 
const uuid = event.params.uid; 

console.log('User to send notification', uuid); 

var ref = admin.database().ref('Users/{uuid}'); 
ref.on("value", function(snapshot){ 
     console.log("Val = " + snapshot.val()); 
     }, 
    function (errorObject) { 
     console.log("The read failed: " + errorObject.code); 
}); 

当我得到的回调,则snapshot.val()返回null。任何想法如何解决这个问题?也许以后如何发送推送通知?

+0

uuid的console.log是否显示正确的值? –

+0

是的,uuid是正确的。 –

+0

使用back-ticks在你的ref:'admin.database()。ref(\'Users/$ {uuid} \')'中替换'uuid'的值。你也应该使用'once()'而不是'on()'。 'on()'离开监听器;不是你想要的云功能。 –

回答

0

返回此函数调用。

return ref.on("value", function(snapshot){ 
     console.log("Val = " + snapshot.val()); 
     }, 
    function (errorObject) { 
     console.log("The read failed: " + errorObject.code); 
}); 

这将使云功能保持活动状态,直到请求完成。了解更多关于返回承诺的信息,请参阅Doug在评论中给出的链接。

+0

谢谢大家的回答。结合他们帮助我实现我想要的! –

+0

我的荣幸,请接受答案,如果它帮助你的问题。 @TudorLozba –

2

我设法使这项工作。以下是使用适用于我的云功能发送通知的代码。

exports.sendNewTripNotification = functions.database.ref('/{uid}/shared_trips/').onWrite(event=>{ 
const uuid = event.params.uid; 

console.log('User to send notification', uuid); 

var ref = admin.database().ref(`Users/${uuid}/token`); 
return ref.once("value", function(snapshot){ 

    const payload = { 
      notification: { 
      title: 'You have been invited to a trip.', 
      body: 'Tap here to check it out!' 
      } 
     }; 

     admin.messaging().sendToDevice(snapshot.val(), payload) 

     }, 
    function (errorObject) { 
     console.log("The read failed: " + errorObject.code); 
}); 
}) 
+0

是否有任何方式使用Firebase云功能将消息发送到主题? –

相关问题