Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to type-check optional properties in Firestore

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();
    }
  }
}
like image 991
rhythnic Avatar asked Sep 19 '25 23:09

rhythnic


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();
    }
  }
}
like image 98
Huafu Avatar answered Sep 23 '25 11:09

Huafu