DEV Community

loading...

Discussion on: Restrict specific fields updation in Firebase Firestore

Collapse
shaone profile image
ShaOne

Thanks for this @ Kushagra, really helpful!

I had a situation where I had to secure the fields of a Firestore map. This is what I got so far, which so far is testing well with various scenarios of map/field combinations. The final piece of the puzzle was ensuring an empty object could not be passed to the Firestore map as it would overwrite all the "good work" of the rules.

function notUpdatingNested(fsmap, field) {
      return 
      !(request.resource.data[fsmap] == {})
      && (((!(fsmap in resource.data) || !(fsmap in request.resource.data) )
        || (!(field in resource.data[fsmap]) || !(field in request.resource.data[fsmap])))
      || (resource.data[fsmap][field] == request.resource.data[fsmap][field]))
    }
Enter fullscreen mode Exit fullscreen mode

This is my initial effort (being fairly new to Firestore) so would appreciate feedback/corrections, or better ways ;)

Collapse
hakimio profile image
Tomas Rimkus

You could simplify this by using "MapDiff":

function notUpdatingNested(fsmap, field) {
    return !(fsmap in request.resource.data) 
        || (
            (request.resource.data[fsmap] is map)
            && (fsmap in resource.data)
            && !(request.resource.data[fsmap].diff(resource.data[fsmap]).affectedKeys().hasAny([field]))
        )
}
Enter fullscreen mode Exit fullscreen mode
Forem Open with the Forem app