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;
}
});