Home > Software design >  Is resource.data and request.resource.data the same thing?
Is resource.data and request.resource.data the same thing?

Time:10-17

I watched Firebase's official guide and the impression I got was request.resource.data points to the new data being written. However, when I'm testing in the emulator, request.resource.data exists no matter what I send, and always equals resource.data. I read the documentation and it's a little round about.

If these values should should be the same, how do I interpret this snippet from the guide

    allow create: if 
    request.resource.data.score is number &&
    request.resource.data.score >=1 &&
    request.resource.data.score <=5 &&

This was said to prevent users from sending invalid 1-5 star ratings for a restaurant. However, per what I understand from the emulator, this validates the already existing data and not the incoming.

Link to moment in video: https://youtu.be/eW5MdE3ZcAw?t=628

CodePudding user response:

In a create/update/delete operation request.resource refers to the document as it'll exist after the operation (if the operation succeeds), while resource refers to the document as it exists before the operation.

So (only) if your write operation makes no change whatsoever, will they be exactly the same.

From the documentation on data validation:

The resource variable refers to the requested document, and resource.data is a map of all of the fields and values stored in the document. For more information on the resource variable, see the reference documentation.

When writing data, you may want to compare incoming data to existing data. In this case, if your ruleset allows the pending write, the request.resource variable contains the future state of the document. For update operations that only modify a subset of the document fields, the request.resource variable will contain the pending document state after the operation. You can check the field values in request.resource to prevent unwanted or inconsistent data updates:

service cloud.firestore {
  match /databases/{database}/documents {
    // Make sure all cities have a positive population and
    // the name is not changed
    match /cities/{city} {
      allow update: if request.resource.data.population > 0
                    && request.resource.data.name == resource.data.name;
    }
  }
}
  • Related