通过REST API进行Firebase交易

栏目: 后端 · 前端 · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/23041800/firebase-transactions-via-rest-api
我发现事务( https://www.firebase.com/docs/transactions.html

)是处理并发的一种很酷的方式,但似乎它们只能从客户端完成.

我们使用Firebase的方式主要是从我们的服务器写入数据并在客户端上观察它们.有没有办法在通过REST API编写数据时实现乐观并发模型?

谢谢!

您可以使用更新计数器使写操作以与事务类似的方式工作. (我将在下面使用一些伪代码;对不起,但我不想写一个完整的REST API作为示例.)

例如,如果我有这样的对象:

{
   total: 100,
   update_counter: 0
}

这样的写规则:

{
   ".write": "newData.hasChild('update_counter')",
   "update_counter": {
      ".validate": "newData.val() === data.val()+1"
   }
}

我现在可以通过简单地在每个操作中传入update_counter来防止并发修改.例如:

var url = 'https://<INSTANCE>.firebaseio.com/path/to/data.json';
addToTotal(url, 25, function(data) {
   console.log('new total is '+data.total);
});

function addToTotal(url, amount, next) {
   getCurrentValue(url, function(in) {
      var data = { total: in.total+amount, update_counter: in.update_counter+1 };
      setCurrentValue(ref, data, next, addToTotal.bind(null, ref, amount, next));
   });
}

function getCurrentValue(url, next) {
   // var data = (results of GET request to the URL) 
   next( data );
}

function setCurrentValue(url, data, next, retryMethod) {
   // set the data with a PUT request to the URL
   // if the PUT fails with 403 (permission denied) then
   // we assume there was a concurrent edit and we need
   // to try our pseudo-transaction again
   // we have to make some assumptions that permission_denied does not
   // occur for any other reasons, so we might want some extra checking, fallbacks,
   // or a max number of retries here
   // var statusCode = (server's response code to PUT request)
   if( statusCode === 403 ) {
       retryMethod();
   }
   else {
       next(data);
   }
}

翻译自:https://stackoverflow.com/questions/23041800/firebase-transactions-via-rest-api


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Hello World

Hello World

Hannah Fry / W. W. Norton Company / 2018-9 / GBP 17.99

A look inside the algorithms that are shaping our lives and the dilemmas they bring with them. If you were accused of a crime, who would you rather decide your sentence—a mathematically consistent ......一起来看看 《Hello World》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具