通过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


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

查看所有标签

猜你喜欢:

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

密码学概论(中文版)

密码学概论(中文版)

wade trappe、lawrence C.washington / 特拉普 / 人民邮电出版社 / 2004-6-1 / 38.00

本书全面讲解了密码学基本知识以及相关的基础数学理论,介绍了椭圆曲线、AES和量子密码体制等密码学前沿知识,详细地阐述了数字签名、数字现金等应用问题。另外,书中每章均给出了相应的习题,在附录中给出了相关Mathematica、Maple和 MATLAB实例。 本书可供高等院校就用数学、通信和计算机等专业用作密码学、通信安全和网络安全等课程的教材或参考书,也可供信息安全系统设计开发人......一起来看看 《密码学概论(中文版)》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

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

RGB CMYK 互转工具