0
votes

I have a Cloud Function setup on Firebase that involved checking different parts of the Firestore Database and then sending a message via Cloud Messaging

Below is the JavaScript for the function in question:

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

admin.initializeApp(functions.config().Firebase);
var db = admin.firestore();
exports.newMemberNotification = functions.firestore
.document('Teams/{teamId}/Waitlist/{userId}').onDelete((snap, context) => {
  // get the user we want to send the message to
  const newValue = snap.data();
  const teamidno = context.params.teamId;
  const useridno = newValue.userID;

  //start retrieving Waitlist user's messaging token to send them a message
  var tokenRef = db.collection('Users').doc(useridno);
  tokenRef.get()
  .then(doc => {
    if (!doc.exists) {
      console.log('No such document!');
    } else {
      const data = doc.data();
      //get the messaging token
      var token = data.messaging_token;
      console.log("token: ", token);
      //reference for the members collection
      var memberRef = db.collection('Teams/'+teamidno+'    /Members').doc(useridno);
      memberRef.get()
      .then(doc => {
        if (!doc.exists){
          console.log('user was not added to team. Informing them');
          const negPayload = {
            data: {
              data_type:"team_rejection",
              title:"Request denied",
              message: "Your request to join the team has been denied",
            }
          };
          return admin.messaging().sendToDevice(token, negPayload)
          .then(function(response){
            console.log("Successfully sent rejection message:", response);
            return 0;
          })
          .catch(function(error){
            console.log("Error sending rejection message: ", error);
          });
        } else {
          console.log('user was added to the team. Informing them')
          const payload = {
            data: {
              data_type: "team_accept",
              title: "Request approved",
              message: "You have been added to the team",
            }
          };
          return admin.messaging().sendToDevice(token, payload)
          .then(function(response){
            console.log("Successfully sent accept message:", response);
            return 0;
          })
          .catch(function(error){
            console.log("Error sending accept message: ", error);
          });
        }
      })
      .catch(err => {
        console.log('Error getting member', err);
      });
    }
    return 0;
    })
    .catch(err => {
      console.log('Error getting token', err);
    });
    return 0;
});

The issues I have with this are:

  • The code runs and only sometimes actually checks for the token or sends a message.
  • the logs show this error when the function runs: "Function returned undefined, expected Promise or value " but as per another Stack Oveflow posts, I have added return 0; everywhere a .then ends.

I am VERY new to node.js, javascript and Cloud Functions so I am unsure what is going wrong or if this is an issue on Firebase's end. Any help you can give will be greatly appreciated

1
You can't just return 0 everywhere. For Firestore triggers (and all other background triggers), you have to return a promise that resolves when all the background work is complete. firebase.google.com/docs/functions/database-events - Doug Stevenson
As an absolute newbie, I thank you from the bottom of my heart. I looked up Promises and tried it and of course it worked. The cloud functions are executing faster and without fail now. - Stephen Giles

1 Answers

1
votes

As Doug said, you have to return a promise at each "step" and chain the steps:

the following code should work:

exports.newMemberNotification = functions.firestore
.document('Teams/{teamId}/Waitlist/{userId}').onDelete((snap, context) => {
    // get the user we want to send the message to
    const newValue = snap.data();
    const teamidno = context.params.teamId;
    const useridno = newValue.userID;

    //start retrieving Waitlist user's messaging token to send them a message
    var tokenRef = db.collection('Users').doc(useridno);
    tokenRef.get()
        .then(doc => {
            if (!doc.exists) {
                console.log('No such document!');
                throw 'No such document!';
            } else {
                const data = doc.data();
                //get the messaging token
                var token = data.messaging_token;
                console.log("token: ", token);
                //reference for the members collection
                var memberRef = db.collection('Teams/' + teamidno + '/Members').doc(useridno);
                return memberRef.get()
            }
        })
        .then(doc => {
            let payload;
            if (!doc.exists) {
                console.log('user was not added to team. Informing them');
                payload = {
                    data: {
                        data_type: "team_rejection",
                        title: "Request denied",
                        message: "Your request to join the team has been denied",
                    }
                };
            } else {
                console.log('user was added to the team. Informing them')
                payload = {
                    data: {
                        data_type: "team_accept",
                        title: "Request approved",
                        message: "You have been added to the team",
                    }
                };
            }
            return admin.messaging().sendToDevice(token, payload);
        })
        .catch(err => {
            console.log(err);
        });
});