首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过ref()从firebase比较布尔索引

如何通过ref()从firebase比较布尔索引
EN

Stack Overflow用户
提问于 2019-03-20 19:07:15
回答 1查看 78关注 0票数 0

当比赛的主机创建一个新的游戏时,我试图存储游戏设置。他们只有一次机会改变设置,然后它就会锁定。

我的问题是,我无法弄清楚如何从firebase获取匹配设置/锁定索引的索引值(它应该是true或false)。

该方法工作正常,但我现在要停止播放机在第一次方法调用后编辑设置。

代码语言:javascript
复制
  changeSettings(time, increment) : void {
    let timePerRound = time;
    let decrease= increment;
    this.db.database.ref(`users/${this.gameId}/matchSettings/locked`).once('value').then( s => {
      if (s == true) {
        // dont allow another update
      }
    })
    this.db.object(`games/${this.gameId}/matchSettings`).update({
      timePerRound: time, decrease: increment, locked: true
    });
    console.log("game settings updated")
  }

这里有一些显示数据库的打印脚本.

http://prntscr.com/n0n9ef <-数据未被锁定,因此允许更改一次设置。http://prntscr.com/n0n9ov <--我现在调用了changeSettings(45,45),但是它也会将锁更改为= true。

EN

回答 1

Stack Overflow用户

发布于 2019-03-20 21:29:16

首先,您面临的一个问题是,您的第一个数据库引用是针对users的,而它应该是针对games的。除此之外..。

应该将更新调用移到从数据库接收的第一个结果中,以便知道是否允许更新:

代码语言:javascript
复制
changeSettings(time, increment) : void {
    let timePerRound = time;
    let decrease= increment;

    this.db.database.ref(`games/${this.gameId}/matchSettings/locked`).once('value')
    .then( s => {
        if (s == true) {
            // dont allow another update
        } else {
            // Yes allow the update
            this.db.object(`games/${this.gameId}/matchSettings`).update({
                timePerRound: time, decrease: increment, locked: true
            });
            console.log("game settings updated")
        }
    })
}

当然,这段代码是可以优化的,这是一个非常难看的if/else语句.但是,为了理解,让我们把它放在基本的位置。

请注意,这是不够的,并不是真的。这只是前端的保安..。这是幻觉。如果你真的想阻止游戏设置的改变,那么你应该实现数据库规则的效果。例如,类似于:

代码语言:javascript
复制
{
    "rules": {
        "games": {
            "$gameId": {
                "matchSettings": {
                    // Allow writing to this node only if...
                    // If the old data doesn't exist... (allow create attempts)
                    // Or if the old data's "locked" property is false
                    ".write": "!data.exists() || data.child('locked').val() == false"
                }
            }
        }
    }
}

*免责声明:未经测试的代码和规则,例如仅限

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55268441

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档