vir us
vir us

Reputation: 10717

Create firestore trigger programmatically?

Is there a way to create a firestore trigger programmatically?

I'm looking to use firestore triggers to keep composite objects consistent where they are in a primary->secondary relationship - "secondary" must be updated accordingly if "primary" is changed.

However I don't need to watch for every "primary" document in a collection since only a limited number of "primary" objects has a "secondary" relationship - my assumption is that watching only specific documents instead of the whole collection will improve overall performance and reduce costs since the triggers will fire only for the relevant documents, giving that the number of the documents to listen is much less comparing to the overall number of documents in the collection

While I can put those documents with the relationship in a separate collection and to add a wildcarded trigger there, I don't want to do that because I want to keep the collection consistent and to reduce overhead on querying/updating the "primary" documents across my application.

Instead I'm wondering if there is a way to add triggers to a specific "primary" documents dynamically as new relationship is created?

Or does it really matter from performance/cost perspective if I add multiple single doc sparse triggers vs adding a wildcarded listener for the whole collection?

Upvotes: 1

Views: 167

Answers (2)

vir us
vir us

Reputation: 10717

Based on Doug's answer, I've ended up setting a whildcarded trigger to the whole collection and added a flag field to the "primary" doc that indicates if there is a relationship to update or not.

This helps to minimize redundant work inside the trigger to save on CPU/Memory/extra requests and to only perform an additional logic based on the flag field.

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317362

There is no known performance downside with a Firestore database when using Cloud Functions triggers. The database simply emits events asynchronously after changes happen. They don't impact the performance of the database.

The only way to add new triggers is to go through the deployment process. Typically this is going to happen with the Firebase CLI or gcloud. If you don't want to use either of these CLIs, you will have to use the Cloud Functions REST API. This is very much non-trivial to set up and use. It's up to you to determine if this is going to be worthwhile.

Upvotes: 1

Related Questions