2
votes

This is the code that I am using to fetch the senderName and messageText from my database. In my logs, I am getting an error saying "Function returned undefined, expected Promise or value". I am using this function to send notifications to the recevier of the message. The notification is being sent appropriately.

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


exports.sendPushNotification = functions.database.ref('/messages/{messageId}').onWrite(event => {


var db = admin.database();

var messageText;
var senderName;
var receiverId;
var senderId;

var messageId = event.params.messageId;


var messageTextRef = db.ref('/messages/' + messageId + '/text');
var senderIdRef = db.ref('/messages/' + messageId + '/fromId');
var receiverIdRef = db.ref('/messages/' + messageId + '/toId');

messageTextRef.once("value", function(data) {

        messageText = data.val();

senderIdRef.once("value", function(data) {

        senderId = data.val();


receiverIdRef.once("value", function(data) {

        receiverId = data.val();


 var senderNameRef = db.ref('/users/' + senderId + '/name');

senderNameRef.once("value", function(data) {

        senderName = data.val();

        console.log(senderName);
        console.log(messageText);



const payload = {

    notification : {
        title: String(senderName),
        body: String(messageText),
        badge: "1",
        sound: 'default',
    }

};

     return admin.database().ref('fcmToken').once('value').then(allToken => {
        if (allToken.val()) {
            const token = Object.keys(allToken.val());
        return admin.messaging().sendToTopic(receiverId, payload).then(response => {

            });

         };



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


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


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



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


});                                                                               
});
1

1 Answers

2
votes

You have a monster function there. If you return the outermost Promise when you are getting all the database values that should fix the issue, and also ensure that your function is not stopped before all computation is complete. In your case this is on line ~25:

...

return messageTextRef.once("value", function(data) {

...