pierreaurelemartin
pierreaurelemartin

Reputation: 1682

Firestore: Better understand how security rules work when fetching other document

I'm really digging Firestore but it's hard to find answer to specific question so here I am. This is just to be sure I understood properly how security rules works :)

Here's my schema:

/databases/{database}/documents/Bases/Base1 {
   roles: { // map
      user1: {admin: true}
   },
   Items: { // SubCollection
      item1: {
        name: "Hello World"
      },
      ...n,
      item10: {
        name: "Good Bye World"
      }
   }
}

I want my user1 to fetch all 10 items in Base1. Query is pretty simple db.collection('Bases').doc('Base1').collection('Items').get()

But I also want to be sure that user1 is an admin in Base1. So I'm setting this security rules:

match /bases/{baseId}/items/{itemId}{
     allow read: if request.auth != null
       && get(/databases/$(database)/documents/bases/$(baseId)).data.roles[request.auth.id].admin == true
}

Which works, all good. Here're the questions:

1/ I understand this rules get() will cost me one read (which is very cheap I know). Is it one read per query OR one read per document that needs to be validate? ie. 10 reads in my case.

2/ I assume answer to 1/ is that it'll cost 10 reads. But, as I'm always querying the same $(baseId), cache will kick-in and even if not guarantee, it should drastically reduce the number of charged reads (theorically 1 read even if I'm fetchin 1000 docs)?

Any other advice on how to handle those kind of schemas are welcome. I know read ops are very cheap but I like to understand where I'm going :)

Thanks SO :)

Upvotes: 0

Views: 76

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317392

The cost of a get() in security rules only applies once per query. It does not apply per document fetched.

Since you have one query, it will cost one read.

Upvotes: 1

Related Questions