質問

トランザクション(href="https://www.firebase.com/docs/transactions.html"> https://www.firebase.com/docs/transactions.html )並行性を処理するかっこいい方法であるが、顧客からのみ行うことができるようです。

FireBaseを使用する方法は、主に私たちのサーバーからデータを書いてクライアント上で観察することです。REST APIを介してデータを書き込むときに楽観的な同時実行モデルを実現する方法はありますか?

ありがとう!

役に立ちましたか?

解決

アップデートカウンタを利用することができ、取引と同様の方法でWRIT OPSが機能することができます。(私は下の疑似コードを使うつもりです。それでは申し訳ありませんが、例のフル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);
   }
}
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top