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


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

查看所有标签

猜你喜欢:

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

删除

删除

[英] 维克托•迈尔-舍恩伯格(Viktor Mayer-Schönberger)著 / 袁杰 译 / 浙江人民出版社 / 2013-1 / 49.90元

《删除》讲述了遗忘的美德,为读者展现了大数据时代的取舍之道。 《删除》从大数据时代信息取舍的目的和方法分别诠释了“被遗忘的权利”。维克托首先回溯了人类追寻记忆的过程,之后提出数字技术与全球网络正在瓦解我们天生的遗忘能力。对此,他考察了促进遗忘终止4大驱动力——数字化,廉价的存储器,易于提取,全球性访问。之后,他提出了当前数字化记忆的两大威胁——信息权力与时间,并给出了应对威胁的6大对策——数......一起来看看 《删除》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具