Reputation: 83
I have a database like this:
- users
- userId1
- activities
- football: "20€"
- competitions
- competitionId1
- football
- prize: "40€"
- userId2
- activities
- baskets: "20€"
- football: "30€"
- competitions
- competitionId4
- basket
- prize: "40€"
So I would like to be notified on all deletes on this, I tried to use
functions.database.ref("users/{userId}").onDelete();
But it only listens to users/{userId}
, I could use .onUpdate()
, but I really need to know the entire path of the deleted object.
The only thing I could try to do is using .onUpdate()
and doing a deep comparison between the old and the new value to retrieve what element got removed.
But I don't think it's the best solution
For example:
If I remove users/userId1/competitions
I will be notified that users/userId1/competitions
is removed
Upvotes: 1
Views: 392
Reputation: 83093
Have a look at this section in the doc for Cloud Functions triggered by Realtime Database events.
Path specifications match all writes that touch a path, including writes that happen anywhere below it.
...
If the event data might be large, consider using multiple functions at deeper paths instead of a single function near the root of your database. For the best performance, only request data at the deepest level possible.
It's really up to you to decide if you should defined several Cloud Functions. However, since you want to listen to deletions, it will be probably easier to write a Cloud Function for each level, like:
functions.database.ref("users/{userId}").onDelete(...);
functions.database.ref("users/{userId}/{activitiesOrCompetitions}").onDelete(...);
functions.database.ref("users/{userId}/{activitiesOrCompetitions}/{CompetitionId}").onDelete(...);
Note that each time you'll delete a CompetitionId
node, if there is no more competitions
for this user, you'll trigger the second Cloud Function above.
Again, it's up to you to decide if you want to trigger several Cloud Functions for one deletion or you prefer to trigger only one Cloud Function (with onUpdate()
) and compare the snapshots, as you mentioned in your question. Remember that there is a generous free tier for Cloud Functions executions of 2M/month.
Upvotes: 1
Reputation: 7388
Have you tried changing the listener to:
functions.database.ref("users/{userId}/{path}").onDelete();
Then path
in your context
would be either "activities", "competitions" etc..
Upvotes: 0