๐Ÿ›ก๏ธ Functions

Extracting complex logic into reusable functions

file_type_firebase firestore.rules
    match /users/{userId} {

      allow read: if isLoggedIn();
      allow write: if belongsTo(userId);

    }

    match /todos/{docId} {

      allow read: if resource.data.status == 'published';

      allow create: if canCreateTodo();
                    

      allow update: if belongsTo() 
                    && request.resource.data.keys().hasOnly(['text', 'status']);
    }

    function isLoggedIn() { 
      return request.auth.uid != null;
    }

    function belongsTo(userId) {    
      return request.auth.uid == userId || request.auth.uid == resource.data.uid;
    }

    function canCreateTodo() {
      let uid = request.auth.uid;
      let hasValidTimestamp = request.time == request.resource.data.createdAt;

      return belongsTo(uid) && hasValidTimestamp;
    }
    

Questions? Let's chat

Open Discord