Firebase functions onCreate() onDelete() path specificity

1.3k views Asked by At

I'm experiencing a lack of understanding of Firebase functions events. To make my function work as intended, I am adding more specificity to the reference path then I believe is required.

For example, I want to increment or decrement a count each time a child is added to or deleted from this path:

/invites

I used these as my functions to accomplish this:

functions.database.ref('/invites').onCreate(event => {
  return admin.database().ref('/counter').transaction((current) => {
    return (current || 0) + 1;
  })
});

functions.database.ref('/invites').onDelete(event => {
  return admin.database().ref('/counter').transaction((current) => {
    if (current >=1) return (current - 1);
    else return;
  })
});

This is what I based my path on:

Path specifications match all writes that touch a path, including writes that happen anywhere below it. If you set the path for your function as /foo/bar, it matches events at both of these locations:

/foo/bar

/foo/bar/baz/really/deep/path

In my case /invites would be the equivalent of /bar in that example.

However, the above functions only fire on the first child being added to /invites as well as the last child being deleted. Outside of those two conditions, anything else will not trigger the counter functions. The only way I have been able to make this work is by using this as my path:

invites/{idOfInvite}

While I understand this would work, I don't know that this is exactly what I need. Later I might decide to add new data under the path of a certain {idOfInvite}, which would cause my counter function to fire (I think?).

This SO answer indicates that my functions' behavior is expected, but it is not what I expect based on my understanding of the docs. Perhaps I'm interpreting the docs incorrectly?

As you can tell, my understanding of how these add/delete events trigger is somewhat off.

1

There are 1 answers

0
Doug Stevenson On BEST ANSWER

onCreate will only be called only when the given path is newly created in the database. If the path already exists (that is, it already has a child), then adding another child is not a "create" event at that path. It's an update event. So, if your function was using onUpdate, it will get triggered anytime anything under that path is written to.

Your use of onCreate/onDelete at /invites/{id} is correct for you use case, because it's effectively asking to be called when any individual child of /invites is newly created or deleted.