【问题标题】:Increment firebase value from javascript, subject to constraint从javascript增加firebase值,受约束
【发布时间】:2020-05-14 18:05:49
【问题描述】:

我在 firebase 中有一个需要增加的值,它受竞争条件的影响,所以我更愿意一次性完成。

    node: {
      clicks: 3
    }

我需要设置clicks = clicks + 1,只要clicks < 20。我可以从 Web API 发出一个调用来执行此操作吗?

【问题讨论】:

  • 您可以使用 Firebase 验证规则吗?类似".validate": "newData.val() < 20"

标签: javascript firebase firebase-realtime-database


【解决方案1】:

reference documentation for a transaction

var ref = firebase.database().ref('node/clicks');
ref.transaction(function(currentClicks) {
  // If node/clicks has never been set, currentRank will be `null`.
  return (currentClicks || 0) + 1;
});

以上将简单地自动增加值,而无需用户选择覆盖彼此的结果。

接下来,确保值永远不会 > 20:

var ref = firebase.database().ref('node/clicks');
ref.transaction(function(currentClicks) {
  // If node/clicks has never been set, currentRank will be `null`.
  var newValue = (currentClicks || 0) + 1;
  if (newValue > 20) {
    return; // abort the transaction
  }
  return newValue;
});

为了更好地衡量,您还需要将安全规则设置为只允许最多 20 次点击。安全规则在 Firebase 数据库服务器上强制执行,因此这样可以确保即使是恶意用户也无法绕过您的规则。基于Firebase documentation on validating data中的示例:

{
  "rules": {
    "node": {
      "clicks": {
        ".validate": "newData.isNumber() && 
                      newData.val() >= 0 && 
                      newData.val() <= 20"
      }
    }
  }
}

【讨论】:

    【解决方案2】:

    firebase JavaScript SDK v7.14.0 中有一个新方法ServerValue.increment()

    因为不需要往返,所以性能更好,而且更便宜。

    here

    添加了 ServerValue.increment() 以支持无事务的原子字段值增量。

    API 文档here

    使用示例:

    firebase.database()
        .ref('node')
        .child('clicks')
        .set(firebase.database.ServerValue.increment(1))
    

    或者你可以递减,只要把-1作为函数arg,就像这样:

    firebase.database()
        .ref('node')
        .child('clicks')
        .set(firebase.database.ServerValue.increment(-1))
    

    【讨论】:

    • 太棒了...我更喜欢这个而不是交易。很高兴知道!
    猜你喜欢
    • 2013-10-17
    • 1970-01-01
    • 2015-11-04
    • 2020-05-31
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    相关资源
    最近更新 更多