[英]Run batch or transaction in Cloud Firestore onCreate trigger
Let's imagine that, in firestore, I have a collection of vendor documents :让我们想象一下,在 firestore 中,我有一组供应商文档:
vendors : {
vendor1: {
id: "vendor1",
name: "John",
shopId: "shop1"
},
vendor2: {
id: "vendor2",
name: "Mary",
shopId: "shop2"
}
}
And a collection of shop documents :和商店文件的集合:
shops : {
shop1: {
id: "shop1",
name: "My Super shop - City A",
vendors : {
vendor1: {
id: "vendor1",
name: "John"
},
shop2: {
id: "shop2",
name: "My Super shop - City B",
vendors : {
vendor2: {
id: "vendor2",
name: "Mary"
}
}
For read performances, each shop document has a copy of its vendors.对于读取性能,每个商店文档都有其供应商的副本。 I copy only vendor data that are needed in my view (mobile app), and I update vendor datas on shop documents if an onUpdate trigger is launch on vendors collection.
我只复制我的视图(移动应用程序)中需要的供应商数据,如果 onUpdate 触发器在供应商集合上启动,我会更新商店文档中的供应商数据。
Today, what I do is :今天,我要做的是:
exports.updatesOnCreateVendor = functions
.firestore.document("vendors/{vendorId}")
.onCreate(async snapshot => {
const vendor = snapshot.data();
const { shopId } = vendor;
const shopRef = db.collection("shops").doc(shopId);
const shopAfter = {
vendors: {}
};
shopAfter.vendors[vendorId] = { ...vendor };
const batch = db.batch();
batch.set(shopRef, shopAfter, { merge: true });
return batch
.commit()
.then(console.log)
.catch(console.error);
});
I don't want to loose this copy if the cloud function failed (and I don't want to active retries on cloud functions).如果云功能失败(并且我不想主动重试云功能),我不想丢失此副本。 (same constraint onUpdate).
(对更新的相同约束)。 After reading the documentation, I conclued that using batch or transaction will guaranty that it will retry if it hasn't succeeded after 25 tries.
阅读文档后,我得出结论,使用批处理或事务将保证如果在 25 次尝试后仍未成功,它将重试。
So, I would like to know if it's a best practice to use batch / transaction like that on cloud function triggers ?所以,我想知道在云函数触发器上使用这样的批处理/事务是否是最佳实践?
If I refactor this and replace the batch process by just using shopRef.set(shopAfter, { merge: true })
and if the cloud function failed, what's happening ?如果我重构它并仅使用
shopRef.set(shopAfter, { merge: true })
替换批处理shopRef.set(shopAfter, { merge: true })
并且如果云功能失败,发生了什么? (I think I'll lose my copy :p ) (我想我会丢失我的副本:p)
Thank you for the time passed to help me better understand Firebase :)感谢您花时间帮助我更好地了解 Firebase :)
The batch isn't going to change your situation at all here.这批货根本不会改变你的情况。 A batch write of one document isn't any different than a normal write of one document.
批量写入一个文档与正常写入一个文档没有任何不同。 All a batch will do is ensure that all of the documents writes happen atomically, all taking effect at the exact same moment.
批处理要做的就是确保所有文档写入原子地发生,并且在完全相同的时刻生效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.