Transazioni di Firebase tramite API di riposo
Domanda
trovo transazioni ( https://www.firebase.com/docs/transactions.html ) aSii un modo fresco di gestione della concorrenza, tuttavia sembra che possano essere eseguiti solo dai clienti.
Il modo in cui usiamo Firebase è principalmente scrivendo dati dai nostri server e osservandoli sui clienti.C'è un modo per ottenere un modello di concorrenza ottimista durante la scrittura di dati tramite API di riposo?
Grazie!
Soluzione
È possibile utilizzare un contatore di aggiornamento per far funzionare OPS di scrittura in modo simile alle transazioni.(Ho intenzione di usare un po 'di pseudo-codice qui sotto; Ci scusiamo per quello ma non volevo scrivere un'API a riposo completo per un esempio.)
Ad esempio, se ho un oggetto come questo:
{
total: 100,
update_counter: 0
}
.
E una regola di scrittura come questa:
{
".write": "newData.hasChild('update_counter')",
"update_counter": {
".validate": "newData.val() === data.val()+1"
}
}
.
Ho ora potuto prevenire le modifiche simultanee semplicemente passando in Aggiorna_Counter con ogni operazione.Ad esempio:
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);
}
}
. Altri suggerimenti
FYI, FireBase Realtime Database in tempo ufficialmente supporta questo ora.
Leggi il Blog e