我为我的购物应用程序创建了一个Firebase函数,该函数在创建订单时触发,然后检查订单中每个产品的数量,并在数据库中更新产品数量。我需要这个来跟踪有多少项目是剩下的每一个产品。但是,如果订单中的某个产品的数量超过了剩余的数量(数据库中的产品数量),我需要一种方法使函数返回从我的react本地应用程序中捕捉到的错误,这样我就可以通知用户他所要求的数量是不可用的。我还需要这个函数来停止在数据库中创建order。
下面是我编写的firebase函数:
exports.countOrderProductChange = functions.firestore.document("/orders/{id}")
.onCreate((change, context) => {
const data = change.data();
const itemsList = data["itemsList"];
let error = "";
const newProductsSizes = {};
for (const item of itemsList) {
db.collection("products").doc(item.product.id).get().then((doc) => {
const product = doc.data();
let sizes = [];
if (item.product.id in newProductsSizes) {
sizes = newProductsSizes[item.product.id];
} else {
sizes = product.sizes;
}
const remaingSize = sizes.find((size) => (size.name == item.size));
const remaingSizeQty = remaingSize.qty;
if (remaingSizeQty < item.qty) {
if (remaingSizeQty == 0) {
error = "Sorry there's no more (" + item.size +
") size of the product: " + item.product.name;
} else {
error = "Sorry there's only "+ remaingSizeQty +
" of (" + item.size +
") size of the product: " + item.product.name;
}
functions.logger.log(error);
return error;
} else {
const sizeIndex = sizes.findIndex((obj) => (obj.name == item.size));
const newQty = remaingSizeQty - item.qty;
const newSizes = sizes;
newSizes[sizeIndex].qty = newQty;
newProductsSizes[item.product.id] = newSizes;
}
});
}
for (const productId in Object.keys(newProductsSizes)) {
if (Object.prototype.isPrototypeOf.call(newProductsSizes, productId)) {
db.collection("products").doc(productId).update({
sizes: newProductsSizes[productId],
});
}
}
});
https://stackoverflow.com/questions/73084488
复制