【发布时间】:2020-08-27 04:56:35
【问题描述】:
我最近一直在尝试学习 firebase 云功能,并且我编写了一个带有 itemName、sellerUid 和数量的 http。然后我有一个后台触发器(onWrite),它使用提供的 SellerUid 和 itemName 查找商品价格并计算总价格(商品价格 * 数量),然后将其写入 firestore 中的文档。
我的问题是:
以我现在拥有的,假设我的客户购买了 N 件物品,这意味着我将拥有:
-
N 次读取(从 N 个商品的价格搜索中),
-
2 次写入(计算后 N 项 1 次初始写入,总金额 1 次),
-
从云端功能搜索 N 次??
我不确定云函数如何计入读取和写入以及它需要的计算时间量(尽管这只是文本,但应该可以忽略不计?)
很想听听您对我所拥有的是否已经足够好或者是否有更有效的方法来解决这个问题的想法。
谢谢!
exports.itemAdded = functions.firestore.document('CurrentOrders/{documentId}').onWrite(async (change, context) => {
const snapshot = change.after.data();
var total = 0;
for (const [key, value] of Object.entries(snapshot)) {
if (value['Item Name'] != undefined) {
await admin.firestore().collection('Items')
.doc(key).get().then((dataValue) => {
const itemData = dataValue.data();
if (!dataValue.exists) {
console.log('This is empty');
} else {
total += (parseFloat(value['Item Quantity']) * parseFloat(itemData[value['Item Name']]['Item Price']));
}
});
console.log('This is in total: ', total);
}
}
snapshot['Total'] = total;
console.log('This is snapshot afterwards: ', snapshot);
return change.after.ref.set(snapshot);
});
【问题讨论】:
-
如果您想对您编写的代码提供反馈,这属于 Code Review Stack Exchange:codereview.stackexchange.com
标签: firebase google-cloud-firestore google-cloud-functions