首页 > 解决方案 > firebase 函数 + 实时数据库 - 数据库结构和代码

问题描述

我在一个简单的应用程序上:这是我第一次尝试使用 firebase 函数 + 实时数据库。

这些函数将由外部客户端应用程序(例如:android)调用。

如果不是 javascript + nosqldb 我不会有问题,但在这里我被卡住了,因为我不确定最好的数据库结构和类似事务的操作。

一、存储数据:

二、行动:

所以我的基本问题是这个 AND - 如果它是一个 SQL 数据库,我会使用一个事务,但在这里我不确定什么是数据库结构和 js 代码以实现相同的结果。

已编辑: ======== 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;
 });
});

====== ticket.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;
 });
}

标签: javascriptfirebasefirebase-realtime-database

解决方案


您必须使用回调,Android 上添加或读取数据的请求具有 onSuccess 或 OnFailure 回调,我用它来触发我的新请求。

您可以在此处的文档上查看此内容:)

此外,如果您使用 Firestore 而不是使用实时数据库,则可以使用 FireStore Transactions here is the info


推荐阅读