Firestore 规则停止监听器

问题描述 投票:0回答:1

对于我的 Firebase 项目,我创建了以下 Firestore 规则:

 match /games/{gameDoc=**} {
        allow read, write: if resource.data.playerOne == request.auth.uid 
        || resource.data.playerTwo == request.auth.uid;
}

该规则按预期工作,但我的问题是我设置了受这些规则影响的文档的侦听器。更改或创建文档时,将调用侦听器,但删除文档时,不会触发侦听器。据我了解,问题出在删除操作后没有 playerOne 或 playerTwo 字段,因此规则拒绝通知听众。有什么办法解决这个问题吗?

编辑:

客户端的监听器(Unity):

docRef.Listen(snapshot => {
            Debug.Log("Game data changed");

            if(snapshot.ToDictionary() == null) // Game got deleted
            {
                dataManager.gameList.Remove(dataManager.gameList.Find(g => g.gameID == snapshot.Id));
            } else
            {
                OnGameDataChanged(snapshot.ToDictionary());
            }
            // Update UI
            FindObjectOfType<GUIManager>().gameListGUI.DisplayGames();
        });

当我将规则更改为 true 时,监听器会收到通知。

firebase google-cloud-firestore firebase-security
1个回答
0
投票

如果你想检测删除,你必须使用

change.ChangeType
对象,如 doc 中所述:

 Query query = db.Collection("...").WhereEqualTo(...);

 ListenerRegistration listener = query.Listen(snapshot =>
        {
            foreach (DocumentChange change in snapshot.GetChanges())
            {
                if (change.ChangeType == DocumentChange.Type.Added)
                {
                    Debug.Log(String.Format("New: {0}", change.Document.Id));
                }
                else if (change.ChangeType == DocumentChange.Type.Modified)
                {
                    Debug.Log(String.Format("Modified: {0}", change.Document.Id));
                }
                else if (change.ChangeType == DocumentChange.Type.Removed)
                {
                    Debug.Log(String.Format("Deleted: {0}", change.Document.Id));
                }
            }
        });
    }
}

但是,有一个重要因素需要考虑:规则不是过滤器。所以你的查询必须符合你的安全规则。


此外,正如 l1b3rty 在他的评论中提到的,在写入数据时,

request.resource
变量包含文档的未来状态。见doc.

© www.soinside.com 2019 - 2024. All rights reserved.