Saturday 6 May 2017

Get "Undefined" for snapshot values

I am currently in the process of setting up my Firebase Cloud functions to have a user to user push notification everytime there is a new child added to "Messages". For each user, there is a notification stored in a node in this structure "/User/UID/Token". However, in my logs in the Firebase console it turns up that values being returned is "Undefined". This is my first time working with Node.js so everything is very new. Any help would be appreciated. Here is what is inside of function

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



via oneQuestionAsker

No comments:

Post a Comment