Search code examples
google-cloud-firestoretransactionsfirebase-security

Is it possible to write a Firestore rule that only allow an operation if it's a part of certain transactions?


I have a document called accountA. It has a balance field. Now accountA has a sub-collection called transactions. Each document in transactions has amount field. I already wrote a transaction using Firestore SDK to add/remove a transaction doc and then update its corresponding account.

Is there a rule I can write so that a transaction doc can be written only if there's a matching update to the balance of the corresponding account in the same transaction? Or am I better off writing a Cloud Function?


Solution

  • Yes, you can certainly write a rule that checks that multiple documents are updated at the same time in order to preserve consistency. From the documentation:

    For writes, you can use the getAfter() function to access the state of a document after a transaction or batch of writes completes but before the transaction or batch commits. Like get(), the getAfter() function takes a fully specified document path. You can use getAfter() to define sets of writes that must take place together as a transaction or batch.