javascript - 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;
});
}
解决方案
推荐阅读
- boost - 如何在增强构建期间关闭标头安装?
- java - 如何跳过记录中的评论
- javascript - Django:如何将 js 变量作为标签传递给 html 模板
- javascript - 试图在js中制作一个lfsr
- spring-boot - 使用 Java 高级 Rest 客户端的 Elastic Search 自定义创建索引
- php - 使用 Codeception 测试 GraphQL 请求时,布尔值 TRUE 转换为字符串“1”
- ruby - 使用 HexaPdf 用粗体文本填充 PDF AcroForm 文本字段
- godot - 我的 godot 脚本 gdscript 有错误,你能解决吗
- algorithm - 多时无向加权图
- azure - 隐藏 Azure Databricks 日志