Search code examples
firebasegoogle-cloud-platformgoogle-cloud-firestorefirebase-security

Firestore rules: placeholders for optional fields


Firestore rules allow you to enforce field types: https://cloud.google.com/firestore/docs/security/rules-fields#enforcing_field_types. It also allows doing this for optional fields: https://cloud.google.com/firestore/docs/security/rules-fields#enforcing_types_for_optional_fields

So you could have something like:

function reviewFieldsAreValidTypes(docData) {
   return docData.get('variableA', {}) is map &&
        docData.get('variableB', {}) is map &&
        docData.get('variableC', '') is int &&
        docData.get('variableD', '') is bool &&
        docData.get('variableE', '') is string &&
        docData.get('variableF', []) is list;
}

I was wondering about the "placeholders" for the different data types in the above function. With placeholders, I mean the {} for map, '' for int, bool, and string, and [] for list.

Are these placeholders correct or should they always be '' irrespective of the field type?


Solution

  • The rules.Map#get(key, default_value) returns:

    the value corresponding to the given key, or the default return value specified by default_value if no match to the given key is found.

    So, you can use the following default values:

    • {} which is an empty map
    • [] which is an empty array
    • '' which is an empty string

    Or any other default values for:

    • 0 for an int
    • false for boolean