![](/img/trans.png)
[英]Can i create an app with React-native, firebase, and node js?
[英]How to make a firebase function (using on create) return an error that I can catch from my react native app
我為我的購物應用程序創建了一個 Firebase function,其中 function 在創建訂單時觸發,然后它會檢查訂單中每個產品的數量並更新數據庫中的產品數量。 我需要這個來跟蹤每個產品的剩余數量。 但是,如果訂單中的一個產品數量多於剩余數量(數據庫中的產品數量),我需要一種方法讓 function 返回一個錯誤,我可以從我的 react 本機應用程序中捕獲,這樣我就可以通知用戶他要求的數量不可用。 我還需要 function 來停止在數據庫中創建訂單文檔。
這是我寫的 firebase function:
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],
});
}
}
});
正如 Doug Stevenson 評論的那樣,您的應用程序無法直接運行onCreate
function,因為這種類型的 function 是背景 function 。 如第三點所示,這些函數是從后端調用的:
當事件提供程序生成與函數條件匹配的事件時,將調用代碼。
您可以查看此相關帖子以獲取更多參考,其中還提到了偵聽用於保存操作狀態的文檔。
另一種選擇是使用可調用的 function。 這些函數允許您在客戶端處理錯誤並在您的應用程序中直接調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.