Slavik N
Slavik N

Reputation: 5328

Firebase rules simulator: how to simulate push

Here's my database:

{
  "lists": {
    "list1_id_1": {
      "field1": "some value",
      "field2": "some value"
    }
  }
}

I want to allow any user to create new lists, but not modify existing ones, so I tried the following rules:

{
  "rules": {
    "lists": {
      ".read": "true",
      ".write": "!data.exists()"
    }
  }
}

This didn't work when I tried to write the following data to /lists/:

{ "field1": "qq", "field2": "ww" }

Apparently, the ".write" rule failed the write because /lists/ already exists.

So I tried the following rules:

{
  "rules": {
    "lists": {
      ".read": "true",
      "$list_id": {
        ".write": "!data.exists()"
      }
    }
  }
}

This didn't work either, Firebase simulator didn't select the rule which failed the write operation, so I guess it's because the ".write" is missing from "lists".

Could you please help me out here? I think my problem is with both the rules, and the way I tried to push a new item to /lists/ in the simulator.

P.S. I know the list_id will be generated by Firebase when I try to push new data, but I'm not sure how to use this knowledge for the simulator.

Thanks! Slavik

Upvotes: 2

Views: 908

Answers (1)

Grimthorr
Grimthorr

Reputation: 6926

Your second set of rules should do the job, but you'll need to specify a child ID in the simulator:

{
  "rules": {
    "lists": {
      ".read": "true",
      "$list_id": {
        ".write": "!data.exists()"
      }
    }
  }
}

The $list_id variable points to any child under the /lists node, so within the simulator, you'll need to set the location to /lists/list1_id_1 to test writing to a child that already exists, which should fail, something like:

simulator screenshot

A push operation creates a child with a unique ID at the given location. To simulate this, you just need to set the location to any random child key that you know doesn't already exist, for example: /lists/some-random-string or /lists/-Kfg3YL0TS1X1SfQ9GGg.

Upvotes: 1

Related Questions