获取快照值的“未定义”

时间:2017-05-06 21:35:46

标签: node.js firebase push-notification firebase-cloud-messaging google-cloud-functions

log result

inside of the log error 我目前正在设置我的Firebase云功能,以便每次有新邮件添加到“邮件”时,用户都可以向用户发送推送通知。对于每个用户,在该结构“/ User / UID / Token”中的节点中存储通知。但是,在我的Firebase控制台日志中,返回的值是“未定义”。这是我第一次使用Node.js,所以一切都很新。任何帮助,将不胜感激。这是函数内部的内容

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

// Listens for new messages added to messages/:pushId
exports.messageWritten =     functions.database.ref('/messages/{pushId}').onWrite( event => {

console.log('Push notification event triggered');

//  Grab the current value of what was written to the Realtime   Database.
var valueObject = event.data.val();
console.log(valueObject.text,valueObject.toId);

return admin.database().ref(`/Users/${valueObject.toId}`).once('value').then(snapshot =>{
    console.log('the users name',snapshot.name)
    console.log('the users token',snapshot.token)
})


// Create a notification
const payload = {
    notification: {
        title:snapshot.name +' sent you a message', 
        body: valueObject.text,
        sound: "default"
    },
};

 //Create an options object that contains the time to live for the  notification and the priority
const options = {
    priority: "high",
    timeToLive: 60 * 60 * 24
};


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

1 个答案:

答案 0 :(得分:0)

您的函数中有两个return语句。第一个返回语句(发送消息)之后的代码不会被运行。

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

// Listens for new messages added to messages/:pushId
exports.messageWritten = functions.database.ref('/messages/{pushId}').onWrite(event => {

    console.log('Push notification event triggered');

    //  Grab the current value of what was written to the Realtime   Database.
    var valueObject = event.data.val();
    console.log(valueObject.text, valueObject.toId);

    return admin.database().ref(`/Users/${valueObject.toId}`).once('value').then(snapshot => {
        console.log('the users name', snapshot.val().name)
        console.log('the users token', snapshot.val().token)

        // Create a notification
        const payload = {
            notification: {
                title: snapshot.val().name + ' sent you a message',
                body: valueObject.text,
                sound: "default"
            },
        };

        //Create an options object that contains the time to live for the  notification and the priority
        const options = {
            priority: "high",
            timeToLive: 60 * 60 * 24
        };

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