Firebase Realtime数据库结构最佳实践问题

时间:2018-11-10 12:36:35

标签: firebase firebase-realtime-database firebase-security-rules

我正在尝试在保护数据时找出Firebase Realtime数据库结构的最佳做法。我已经阅读了有关如何使用Firebase Realtime Database Rules保护数据库的信息。

例如: 用户添加“注释”并与其他用户(成员)共享这些“注释”,然后其他用户(成员)可以编辑和注释这些“注释”。 让我们考虑如下存储结构:

-categories
  -uuid-cat1
    -data
      title: "my category 1"
    -members
      author: "uuid-user1"
-notes
  -uuid-note1
    -data
      title: "Hello World!"
      categoryId: "uuid-cat1"
      -comments
         -uuid-comment1
           title: "Can you explain?"
           author: "uuid-user2"
         -uuid-comment2
           title: "Certainly!"
           author: "uuid-user1"
    -members
      author: "uuid-user1"
      uuid-user2: "uuid-user2" //UPDATE 2 - This is another user with access to the note
  -uuid-note2
    -data
      title: "Hello Universe!"
      -categoryIds
         uuid-2: "uuid-cat2"
    -members
      author: "uuid-user2"
-users
  -uuid-user1
    name: "Jane"
  -uuid-user2
    name: "Jane"

仅当用户被列为“成员/作者”或“成员/用户ID”时,用户才能访问注释或类别。这是由Firebase Realtime数据库规则强制执行的。

这项工作会大规模进行吗? 假设我们存储了20万张钞票。

当请求从数据库中读取所有“注释”时,此结构是否会引起Firebase的性能问题-因为Firebase在返回列表之前必须循环通过所有“注释”来确定访问权限?

是否有更好的方法(最佳实践)来构造数据?

更新

我的规则看起来类似于:

{
  "rules": {
    "notes" : {
      //indexes
      ".indexOn": ["data/title", "members/author"],
      //access
      ".read": "
        auth.uid != null &&
        query.orderByChild == 'members/author' && query.equalTo == auth.uid
      ",
      ".write": "
        auth.uid != null && 
        query.orderByChild == 'members/author' && query.equalTo == auth.uid
      ",
      "$noteid": {
        "data": {
          "title": {
            ".validate": "newData.isString() && newData.val().length > 0"
          }
        }, 
        "members" : {
          ".read" : true, 
          ".write": true, 
          //validation
            ".validate": "newData.hasChildren([
                'author'
            ])",
          "author" :{
            ".validate": "newData.isString()"
          }
        }
      }    
    },
    "categories": {
      //The same type of rules as for "notes"
    },
    "users": {
      "$userid": {
        ".read": "$userid === auth.uid",
        ".write": "$userid === auth.uid"
      }
    }
  }
}

我的代码看起来很像:

const myUid = firebase.auth().currentUser.uid;
const ref = firebase.database().ref('notes');
ref.orderByChild('members/author').equalTo(myUid).on('value', (snapshot) => {
  console.log(snapshot.key)
  const notesArray = []

  snapshot.forEach( (childSnapshot) => {
    notesArray.push({
      id: childSnapshot.key,
      data: childSnapshot.val()
    });
  });

  console.log(notesArray);
}

0 个答案:

没有答案