arvidurs
arvidurs

Reputation: 3033

Firestore function with Promises.all takes very long to complete

So I am new to javascript, and I am pretty sure the code is less than ideal. I am running into some issues getting the data from Firestore.

The personalMessage function takes around 50 seconds to complete, and I a have no idea why it takes so long. This code in swift will return from the database under 1000ms.

Also any pointers in code style is recommended.

enter image description here

function sendMessageToDevice(token, payload, options) {
  admin.messaging().sendToDevice(token, payload, options)
    .then(response => {
      console.log('Successfully sent message:', response, response.results[0].error);
      return response
    })
    .catch(error =>  console.log('Error sending message:', error));
}

function getUser(userId) {
    return admin.firestore().collection('users').doc(userId).get()
        .then(snapshot => {
            if (!snapshot.exists) {
                console.log('No such document!');
                return null;
            }
            return snapshot.data()
        })

        .catch(err => {
            console.log('Error getting document', err);
            return err;
        });
}


exports.personalMessage = functions.firestore
    .document('/messages/{id}')
    .onCreate((snapshot, context) => {
      var messageData = snapshot.data();
      var userId = messageData.user;
      var fromId = messageData.from;

      Promise.all([getUser(userId), getUser(fromId)])

      .then(([dataA, dataB]) => {
          console.log(dataA.fcmToken, dataB.name);


          var payload = {
             notification: {
                 title: dataB.name + ' messaged you.',
                 body: 'Go check it out it',
                 clickAction: 'NEW_PERSONAL_MESSAGE'},
             data: {
                 messageId: context.params.id}
             };

          var options = {
              contentAvailable: false,
              priority: 'high'
          }

          return sendMessageToDevice(dataA.fcmToken, payload, options);
      })



      .catch(error =>  console.log('Error sending message:', error));

      return Promise.resolve('success');
});

Upvotes: 0

Views: 89

Answers (1)

ToraCode
ToraCode

Reputation: 432

As Doug talk about the incorrect promises. I change a little in your code. However, the message may be not come immediately for some reason like network,...

function sendMessageToDevice(token, payload, options) {
    return admin.messaging().sendToDevice(token, payload, options)

}

function getUser(userId) {
    return admin.firestore().collection('users').doc(userId).get()

}


exports.personalMessage = functions.firestore
    .document('/messages/{id}')
    .onCreate((snapshot, context) => {
      var messageData = snapshot.data();
      var userId = messageData.user;
      var fromId = messageData.from;

      return Promise.all([getUser(userId), getUser(fromId)])
      .then(result=> {

            if (!result[0].exists || !result[1].exists) {
                console.log('No such document!');
                return null;
            }
            return [result[0].data(),result[1].data()]
        }) 
      .then(([dataA, dataB]) => {
          console.log(dataA.fcmToken, dataB.name);


          var payload = {
             notification: {
                 title: dataB.name + ' messaged you.',
                 body: 'Go check it out it',
                 clickAction: 'NEW_PERSONAL_MESSAGE'},
             data: {
                 messageId: context.params.id}
             };

          var options = {
              contentAvailable: false,
              priority: 'high'
          }

          return sendMessageToDevice(dataA.fcmToken, payload, options);
      })
      .then(response => {
          console.log('Successfully sent message:', response, 
               response.results[0].error);
          return Promise.resolve('success');
      }) 
      .catch(error =>  console.log('Error sending message:', error));

});

Upvotes: 1

Related Questions