Is there any way to setup firestore triggers stemming from multiple firestore collections to trigger only one cloud (javascript) function?

Viewed 244

So typically, on a basic level, you often see firestore collection triggered functions written like:

exports.myFunction = functions.firestore
  .document('my-collection/{docId}')
  .onWrite((change, context) => { /* ... */ });

That being said, I am running my deployments a bit different, although structurally identical.

  • I have a exports.main = (content, event) where:
    • event holds the EVENT information:
    • eventId (e.x: 66e9e123-d3fg-1234-123a-1234f110b71b-0)
    • eventType (e.x: providers/cloud.firestore/eventTypes/document.create)
    • notSupported (e.x: {})
    • params (e.x: {eventId: 1CB89AD0-5AS0-1233-SD70-E3B7DS52D23D})
    • resource (e.x: projects/its-the-project-id/databases/(default)/documents/TheCollection/1CB89AD0-5AS0-1233-SD70-E3B7DS52D23D
    • timestamp (e.x: 2021-05-19T20:00:24.131151Z)
  • and content is, well, the data

I deploy the functions via Terraform where I define:

  • event_trigger:
    • event_type = providers/cloud.firestore/eventTypes/document.create
    • resource = ${TheCollection}/{eventId}

So as you can see, while the way I do it is certainly requires more configuration, it's very much identical, it's just configured in a more GCP-able fashion (if you will)

So, with that context:

  1. Is there any possible way to have more than one collection/document trigger, trigger only 1 cloud function?
    • So say I have collection x and collection y, I want them both to trigger the same cloud function
  2. If there is a way, feel free to write it in the oftenly written Firebase-able fashion and I can try to translate that over to be deployable in Firestore
1 Answers

Yes, you can do this by using multiple wildcards:

exports.myFunction = functions.firestore
  .document('{collectionId}/{docId}')
  .onWrite((change, context) => {
    console.log(context.params.collectionId);
    console.log(context.params.docId);
});

More info here.

Related