1
votes

I am trying to build triggers for a firebase app around following and followers. Below is a snippet of my cloud code. I want to increase a counter when a user follows. For this I use oncreate (for when the user gains their first follower due the structure not existing until this point) and then I use onupdate. I then use ondelete to decrement the following count when a user unfollows and is removed.

The problem I am having is that .ondelete is not being called and only .onupdate is being called regardless of users being added or removed (which looking back makes sense I guess). My question is how to write the cloud functions to separate the deletions from the additions.

the database looks something like this

user1
  - following
     -user2
       -small amount of user2data
     -user3
       -small amount of user3data

And the code:

    exports.countFollowersUpdate = functions.database.ref('/{pushId}/followers/')
        .onUpdate(event => {

          console.log("countFollowers")


          event.data.ref.parent.child('followers_count').transaction(function (current_value) {

            return (current_value || 0) + 1;
          });


        });

exports.countFollowersCreate = functions.database.ref('/{pushId}/followers/')
    .onCreate(event => {

      console.log("countFollowers")


      event.data.ref.parent.child('followers_count').transaction(function (current_value) {

        return (current_value || 0) + 1;
      });


    });


exports.countFollowersDelete = functions.database.ref('/{pushId}/followers/')
    .onDelete(event => {

      console.log("countFollowers2")


      event.data.ref.parent.child('followers_count').transaction(function (current_value) {

        if ((current_value - 1) > 0) {
          return (current_value - 1);
        }
        else{
          return 0;
        }
      });
1
read my question again. The server doesn't know if it's a follow or unfollow. It only knows how the data was edited. The problem is that it can't tell the difference between an update and a delete. As for your first question it is horrible from an efficiency stand point to count the entire number every transaction.Blue
Please indicate how the client i adding the data to the database. Also note that your database structure is unreadable in your question - it requires formatting.Doug Stevenson

1 Answers

1
votes

onDelete isn't being called because you're listening to the entire followers node, so it would only be called when follower counts goes to zero (nothing left). Instead you probably want all of these to be more like:

functions.database.ref('/{pushId}/followers/{followerId}').onDelete()

It's also unusual that you have a top-level push id. A structure would normally be more like /users/{pushId}/followers/{followerId}.