Search code examples
firebasegoogle-cloud-firestorefirebase-security

Check with Firestore security rules if optional dates and maps have valid types


In Firestore security rules we can check the types of optional strings and lists as follows:

function reviewFieldsAreValidTypes(docData) {
  return docData.get('photo_url', '') is string &&
         docData.get('tags', []) is list;
}

What would one use as the default value for optional timestamps?

docData.get('dateModified', ???) is timestamp;

And for an optional map?

docData.get('translated', ???) is map;

Solution

  • We just need to set a default value of the correct type. We can use the request object:

    function reviewFieldsAreValidTypes(docData) {
      return docData.get('photo_url', '') is string &&
             docData.get('tags', []) is list &&
             docData.get('dateModified', request.time) is timestamp &&
             docData.get('translated', request.resource.data) is map;
    }