【发布时间】:2019-02-01 01:49:48
【问题描述】:
我的要求有一些变化:
不仅创建/请求/取消整个报价,而且对报价的详细信息执行一些操作:
这是 activeOffers 列表中的一个报价:
activeOffers
-LKohyZ58cnzn0vCnt9p
details
direction: "city"
seatsCount: 2
timeToGo: 5
uid: "-ABSIFJ0vCnt9p8387a" ---- offering user
用户应该能够“要求座位”,如果成功,报价记录应该如下所示:
activeOffers
-LKohyZ58cnzn0vCnt9p
details
direction: "city"
seatsCount: 1 ----- reduced count
timeToGo: 5
uid: "-ABSIFJ0vCnt9p8387a"
deals
-GHFFJ0vCnt9p8345b ----- the userId of asking user
seatsCount: 1
status: "asked"
但是我在执行下图的源码后遇到了3个问题:
(如上图提供2个席位,用户要求1个席位)
在我的日志中执行后,我有“将座位数减 1”和“座位数不足”... 即:“if-then-else”的“then”和“else”部分: o
函数结果为 [] - 即未创建交易。
我不确定如何执行 TODO: 部分 - 使用询问 userId 作为 KEY 在 DealRef 下添加子项(新交易对象),因为我认为这里不需要自动生成的密钥。
输入数据的结构如下:
data
"uid": "-GHFFJ0vCnt9p8345b", ----- the userId of asking user
"id": "-LKohyZ58cnzn0vCnt9p", ----- the id of offer
"details":
"seatsCount": 1
这是我的代码:
dealSeats = function(data) {
const TAG = '[dealSeats]: ';
var details = data.details;
var info = data.info;
var entryRef = db.ref('activeOffers/' + data.id);
var entryDetailsRef = entryRef.child('details');
var seatsCountRef = entryDetailsRef.child('seatsCount');
var success = false;
return seatsCountRef.transaction((current)=>{
var value = current;
if (value >= details.seatsCount) {
success = true;
value = value - details.seatsCount;
console.log(TAG + 'Reducing seats count by ' + details.seatsCount);
} else {
console.log(TAG + 'Not enought seats');
}
return value;
})
.then(()=>{
var deal = [];
if (success) {
console.log(TAG + 'Succes');
deal.seatsCount = details.seatsCount;
deal.status = 'asked';
// TODO: here should add the new deal to dealsRef
return deal;
} else {
console.log(TAG + 'Failure');
return deal;
}
})
}
如您所见 - 我不确定检查交易是否成功的正确方法...
【问题讨论】:
标签: javascript firebase firebase-realtime-database transactions