在密钥名称上创建firebase数据库规则

时间:2017-08-20 17:47:03

标签: firebase firebase-realtime-database

我需要有关创建firebase数据库规则的帮助。用例是这样的:用户(游戏玩家)有3个宝盒,可以容纳任何宝藏。用户可以购买额外的宝箱。所以我出现的firebase数据库中的树结构是:

user
  |- settings
       |- max-t-box : 3
  |- boxes
       |- 1 : {} // a complicated data for the treasure or null
       |- 2 : {} // a complicated data for the treasure or null
       |- 3 : {} // a complicated data for the treasure or null

'user / settings / max-t-box'的规则很简单:用户只读且不允许写入(只能由服务器端管理员修改)。

“用户/盒子”下的规则应该是:新数据的密钥应该是一个数字,它的值应该是> 0和< ='用户/设置/ max-t-box'值。

根据firebase文档,我可以使用$ variable来捕获路径段,但是它没有提供足够的api来检查路径节点名称值。

到目前为止,我提出的解决方案是为路径'user / boxes / 1','user / boxes / 2'和'user / boxes / 3'编写规则。然而,在用户购买许多盒子之后,这看起来确实很愚蠢。

1 个答案:

答案 0 :(得分:2)

使用序号作为键,您将遇到问题的批次。 <(可以)将它们视为数组和Firebase Arrays Are Evil,通常应该避免使用。

无法修改,搜索数组,如果要修改它们,则必须完全重写它们。

使用push()或childByAuto()构建数据以创建密钥是可行的方法:

root
     settings
       max-t-box 3

    boxes
       -yuy8jj09j9090f
         box_num: 1
         box_name: "Big box"
         box_location: "Sewer"
       -y8jokokoais9g
         box_num: 2
         box_name: "Small box"
         box_location: "Tower"

然后规则很快

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null",
    "boxes": {
      "$box_num": {
        ".validate": "newData.child('box_num').val() > 0 && 
                      newData.child('box_num').val() <= 
                                        root.child('settings').child('max-t-box').val()" 
      }
    }
  }
}

我是直接在根节点内完成此操作,但您可以将root.child('users')替换为您的firebase结构。

相关问题