11

I return transaction promise which should wait for transaction to finish before stopping the function. The transaction executes fine, but the promise seems to never resolve.

I see in the Firebase console that this function always times out after 60s.

const functions = require('firebase-functions');
const admin = require("firebase-admin");
const db = admin.database();


export let countFollowers = functions.database.ref('followers/{followee}/{follower}').onWrite(event => {
    const followee = event.params.followee;
    let path = `posts/${followee}/cnt_foll`;
    const countRef = db.ref(path);
    let out = countRef.transaction(current => {
        if (event.data.exists() && !event.data.previous.exists()) {
            return (parseInt(current) || 0) + 1;
        } else if (!event.data.exists() && event.data.previous.exists()) {
            return (parseInt(current) || 0) - 1;
        }
    });

    return out;
});

EDIT:

I solve the problem with the following "hack", I create a promise myself, because whatever .transaction is returning is not working:

return new Promise(function(resolve, reject) {
    countRef.transaction(current => {
        if (event.data.exists() && !event.data.previous.exists()) {
            return (parseInt(current) || 0) + 1;
        } else if (!event.data.exists() && event.data.previous.exists()) {
            return (parseInt(current) || 0) - 1; 
        }
    }, () => resolve(null));
});
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Alex Peterson
  • 361
  • 2
  • 12

1 Answers1

4

There was a known issue with older versions of the firebase-admin SDK where Firebase Database references and snapshots couldn't be JSON serialized and thus couldn't be used in return values for Cloud Functions. This includes transaction return values since they also have snapshots.

Your hack works around the bug; you should also get the fix if you update your version of firebase-admin.

Thomas Bouldin
  • 3,707
  • 19
  • 21
  • OK, will try to update to the latest `firebase-admin` at `4.1.4`, I am using version `4.1.3` BTW – Alex Peterson Apr 03 '17 at 15:56
  • 1
    I'm having the same issue with the latest version 4.1.4. I was following the example provided: https://github.com/firebase/functions-samples/blob/master/child-count/functions/index.js – dardub Apr 04 '17 at 05:52
  • I can confirm that it's still an issue with `firebase-admin` `4.1.4` and `firebase-functions` `0.5.4` – Michał Pietraszko Apr 04 '17 at 08:33
  • 4
    Thanks for verifying. Clearly the fix wasnt enough. We can get it addressed in another release. You can work around it in the meantime with the code above. – Thomas Bouldin Apr 04 '17 at 09:33
  • 1
    The next backend update for Cloud Functions should fix this for all possible return types (instead of timing out the cloud function will log a warning and complete). – Thomas Bouldin Jun 20 '17 at 17:58