Reputation: 455
I'm on a simple application: It's my first try with firebase functions + realtime database.
The functions are going to be called by an external client application (e.g.: android).
if it was not javascript + nosqldb I would not have a problem, but here I am stuck, because I'm not sure for the best db structure and about transaction-like operations.
I. stored data:
II. actions:
user buy some tickets - should add tickets to the user's amount AND add a record to buyings history
user use some tickets - should remove tickets from the user's amount AND add a record to usings history
So my base problem is this ANDs - if it was a SQL db i would use a transaction but here I'm not sure what is db structure and js code in order to achieve same result.
EDITED: ======== index.js =======
exports.addTickets = functions.https.onCall((data, context) => {
// data comes from client app
const buyingRecord = data;
console.log(‘buyingRecord: ‘ + JSON.stringify(buyingRecord));
return tickets.updateTicketsAmmount(buyingRecord)
.then((result)=>{
tickets.addTicketsBuyingRecord(buyingRecord);
result.userid = buyingRecord.userid;
result.ticketsCount = buyingRecord.ticketsCount;
return result;
});
});
====== tickets.js =======
exports.updateTicketsAmmount = function(buyingRecord) {
var userRef = db.ref(‘users/’ + buyingRecord.userid);
var amountRef = db.ref(‘users/’ + buyingRecord.userid + ‘/ticketsAmount’);
return amountRef.transaction((current)=>{
return (current || 0) + buyingRecord.ticketsCount;
})
.then(()=>{
console.log(“amount updated for userid [“ + buyingRecord.userid + “]”);
return userRef.once(‘value’);
})
.then((snapshot)=>{
var data = snapshot.val();
console.log(“data for userid [“ + snapshot.key + “]:” + JSON.stringify(data));
return data;
});
}
exports.addTicketsBuyingRecord = function(buyingRecord) {
var historyRef = db.ref(‘ticketsBuyingHistory’);
var newRecordRef = historyRef.push();
return newRecordRef.set(buyingRecord)
.then(()=>{
console.log(‘history record added.’);
return newRecordRef.once(‘value’);
})
.then((snapshot)=>{
var data = snapshot.val();
console.log(‘data:’ + JSON.stringify(data));
return data;
});
}
Upvotes: 1
Views: 134
Reputation: 96
You would have to use the callback, the request on Android to add or read data have an onSuccess or OnFailure CallBack, i used this to trigger my new request.
You can check this on the doc here :)
Also if instead of using RealTime Database you use Firestore you can use the FireStore Transactions here is the info.
Upvotes: 1