0

我正在用 React 和 Firebase 做一个简单的图书管理器应用程序。用户可以输入图书的作者、标题和评级,我正在尝试验证输入。

数据结构如下:

"books" : {
    "-LSon2JjuqUWb6tXV-EA" : {
      "author" : "Stephen King",
      "rating" : "5",
      "title" : "\"Misery\""
    },
    "-LSp33lP1b5W2XOXyEmI" : {
      "author" : "Stephen King",
      "rating" : "10",
      "title" : "\"Cujo\""
    }
}

Firebase 在调用 push 方法时以编程方式生成每个密钥。现在,我想验证用户的输入,但关键似乎引发了问题。我应该如何在陈述中提及它?或者我的规则不起作用的原因可能完全不同?如果我省略生成的键并直接在“书籍”对象中引用作者/标题/评级,我可以添加不符合我所说的条件的数据。

{
  "rules": {
    ".read": "true",
    ".write": "true",
      "books" : {
        "???" : {
          "author" : {
            ".validate" : "newData.isString() && newData.val() > 0"
          },
          "title" : {
            ".validate" : "newData.isString() && newData.val() > 0"
          },
          "rating" : {
            ".validate" : "newData.isNumber()"
          }
        }
      }
  }
}

我将不胜感激任何提示。

链接到我的项目的回购

4

2 回答 2

0

你应该首先去规则模拟器测试你的规则,它在你的规则的右边。

在模拟类型中选择 SET。

在区域中写入 /books/{newkey} 在 JSON 区域中写入:

{“作者”:“作者数据”}

对 newkey(您的推送生成的密钥)节点下的每个字段重复此操作。

这至少会告诉您哪些规则不起作用,如果您单击详细信息,您将能够知道原因。

另外我要补充一点,你如何得出像作者这样的数据:“斯蒂芬,我的意思是没有最后一个引号?

于 2018-12-04T02:30:25.793 回答
0

您应该将您的 Firebase 推送键称为“$bookId”,然后可以在需要时在规则中使用它。

例子:

{
  "rules": {
    "rooms": {
      // this rule applies to any child of /rooms/, the key for each room id
      // is stored inside $room_id variable for reference
      "$room_id": {
        "topic": {
          // the room's topic can be changed if the room id has "public" in it
          ".write": "$room_id.contains('public')"
        }
      }
    }
  }
}

https://firebase.google.com/docs/database/security/securing-data#using_variables_to_capture_path_segments

于 2018-12-05T14:43:33.620 回答