首页 > 解决方案 > Cloud Functions 无法从实时数据库中获取令牌

问题描述

我试图从函数发送消息,但它总是得到“提供给 sendToDevice() 的注册令牌必须是非空字符串或非空数组”,但这是我的令牌存储的地方:


这里是我的代码

    exports.mess = functions.database.ref('/path/{uid}')
        .onWrite(event => {
        var ref = admin.database().ref(`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);
        });

       });

标签: javascriptfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


我认为您正在尝试使用token触发云功能的用户的属性值。在这种情况下,您不需要附加单独的侦听器,因为该值已经在context参数中可用。

exports.mess = functions.database.ref('/path/{uid}')
.onWrite(event => {
    let token = event.after.child('token').val()
    const payload = {
        notification: {
            title: 'You have been invited to a trip.',
            body: 'Tap here to check it out!'
        }
    };

    return admin.messaging().sendToDevice(snapshot.val(), payload)
});

推荐阅读