Firebase cloud function transaction remove node if count hits 0

103 views Asked by At

I have the following function:

exports.tagCountDecrement = functions.database
 .ref('/categoryTags/{tagName}/{postId}')
 .onDelete((snapshot, context) => {

  const tagsWithCountRef = admin
    .database()
    .ref('tags')
    .child(context.params.tagName);

  return tagsWithCountRef
    .transaction(counter_value => {
      return (counter_value || 0) - 1;
    })
}) 

To make sure users aren't loading the node by its key (with a value of 0), I want to remove it completely if the count reaches 0. I thought about replacing the 0 with null but it needs a number to begin with if the node doesnt exist.

What is the cleanest was to go about this via firebase cloud functions?

Cheers.

1

There are 1 answers

1
robsiemb On BEST ANSWER

You didn't supply your data, so I'm going to assume it looks something like this:

{
  "categoryTags" : {
    "id1" : {
      "post" : "postpostpost"
    },
    "id2" : {
      "post1" : "postpostpost",
      "post2" : "postpostpost"
    }
  },
  "tags" : {
    "id1" : 1,
    "id2" : 2
  }
}

In that case, to remove the node instead of letting the count hit zero, you need to return null from the transaction whenever the value is 1 (or less, or nonexistent, since I can't think of anything reasonable to do in those cases except maybe log an error of some sort):

exports.tagCountDecrement = functions.database.ref('/categoryTags/{tagName}/{postId}')
  .onDelete((snapshot, context) => {
    const tagsWithCountRef = admin
      .database()
      .ref('tags')
      .child(context.params.tagName)

    return tagsWithCountRef
      .transaction((current_value) => {
        if (!current_value || current_value <= 1) {
          // in either of these cases, delete (or leave it alone)
          return null;
        } else {
          // otherwise, reduce by 1
          return current_value - 1;
        }
      });
  });