Search code examples
firebasegoogle-cloud-firestorefirebase-security

Firebase, Security Rules, how to check a item of array String size


the way of getting and verifying array list size in Firestore is below

request.resource.data.arraylist.size() < 10

but I want to know the "request.resource.data.arraylist[last_index].length" not the "list size"

how do I figure out this?


Solution

  • The Bytes, List, Map, Set, and String variable types in the rules namespace all share the size() method which is used in place of length.

    So, using that, you would assert the last element has a size of less than 10 using:

    request.resource.data.arraylist[request.resource.data.arraylist.size()-1].size() < 10
    

    Because that looks messy (especially amongst other conditions), you could rewrite it as a custom function like so:

    function doesLastElementOfListHaveSizeLessThan(num, list) {
      return list[list.size()-1].size() < num;
    }
    
    doesLastElementOfListHaveSizeLessThan(10, request.resource.data.arraylist);
    

    Notes:

    • You can name the function whatever you want, I just used a sentence for clarity and it makes rereading your rules later easier.
    • While this rule asserts the length of the last index, other indexes could have been modified to be longer than your threshold in the same write.
    • For performance reasons, security rules do not support iteration, you must hard code in each check for an index manually. If you need to check a range of indexes, you should implement a custom function that checks a small range of indexes that takes a starting offset. If you implement such a function, make sure that it short-circuits to true/false as soon as possible and doesn't throw errors such as the index being out of bounds.