根据约束增加javascript的firebase值

Bon*_*ott 8 javascript firebase firebase-realtime-database

我在firebase中有一个值,我需要增加,它受竞争条件的限制,所以我更喜欢这一切.

    node: {
      clicks: 3
    }
Run Code Online (Sandbox Code Playgroud)

我需要设定clicks = clicks + 1这么久clicks < 20.我可以通过Web API进行一次调用来执行此操作吗?

Fra*_*len 19

请参阅交易参考文档:

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;
});
Run Code Online (Sandbox Code Playgroud)

上面将简单地以原子方式递增值,而不会让用户选择覆盖彼此的结果.

接下来,确保值永远不会超过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;
});
Run Code Online (Sandbox Code Playgroud)

为了更好地衡量,您还需要将安全规则设置为仅允许最多20次点击.安全规则在Firebase数据库服务器上实施,因此这可确保即使是恶意用户也无法绕过您的规则.基于Firebase文档中有关验证数据的示例:

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


Ole*_*leg 6

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

由于不需要往返,因此性能更好且更便宜。

这里

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

API文档在这里

用法示例:

firebase.database()
    .ref('node')
    .child('clicks')
    .set(firebase.database.ServerValue.increment(1))
Run Code Online (Sandbox Code Playgroud)

或者你可以递减,就像这样放置-1函数 arg :

firebase.database()
    .ref('node')
    .child('clicks')
    .set(firebase.database.ServerValue.increment(-1))
Run Code Online (Sandbox Code Playgroud)

  • 太棒了...我更喜欢这个而不是交易。很高兴知道! (2认同)