How to type-check optional properties in Firestore

Viewed 1755

I can't figure out how to do optional properties in Firestore. It doesn't seem to be covered in the docs and the following fails for me.

service cloud.firestore {
  match /databases/{database}/documents {
    function maybeString(val) {
      return val == null || val is string
    }

    match /myCollection/{document} {
      function mySchema() {
        return request.resource.data.name is string
          && maybeString(request.resource.data.optionalProp);
      }

      allow read: if request.auth != null;
      allow create, update: if mySchema();
    }
  }
}


service cloud.firestore {
  match /databases/{database}/documents {
    match /myCollection/{document} {
      function mySchema() {
        return request.resource.data.keys().hasAll(['name'])
          && request.resource.data.name is string
          && request.resource.data.optionalProp is string;
      }

      allow read: if request.auth != null;
      allow create, update: if mySchema();
    }
  }
}
1 Answers

I am using the second solution but you need to check for the presence of the optionalProp using 'fieldName' in resource.data.keys():

service cloud.firestore {
  match /databases/{database}/documents {
    match /myCollection/{document} {
      function mySchema() {
        return request.resource.data.keys().hasAll(['name'])
          && request.resource.data.name is string
          && (
            ! ('optionalProp' in request.resource.data.keys())
            || request.resource.data.optionalProp is string
          );
      }

      allow read: if request.auth != null;
      allow create, update: if mySchema();
    }
  }
}
Related