云函数和具有幂等性的 Firebase Firestore [英] Cloud functions and Firebase Firestore with Idempotency
问题描述
我正在使用带有 Cloud Functions 的测试版 Firestore.在我的应用程序中,我需要触发一个函数,该函数在 /company/{id}/point/{id}
处侦听 onCreate
事件并执行插入 (集合('事件').add({...}))
I'm using Firestore at beta version with Cloud Functions. In my app I need to trigger a function that listens for an onCreate
event at /company/{id}/point/{id}
and performs an insert (collection('event').add({...}))
我的问题是:带有 Firestore 的 Cloud Functions 需要幂等函数.我不知道如何确保如果我的函数连续两次触发相同的事件,我不会添加两个具有相同数据的文档.
My problem is: Cloud Functions with Firestore require an idempotent function. I don't know how to ensure that if my function triggers two times in a row with the same event, I won't add two documents with the same data.
我发现 context.eventId
可以解决这个问题,但我不知道如何使用它.
I've found that context.eventId
could handle that problem, but I don't recognize a way to use it.
exports.creatingEvents = functions.firestore
.document('/companies/{companyId}/points/{pointId}')
.onCreate((snap, context) => {
//some logic...
return db.doc(`eventlog/${context.params.companyId}`).collection('events').add(data)
})
推荐答案
两件事:
- 首先检查您的集合以查看文档中是否包含具有
context.eventId
值的属性.如果存在,则在函数中不执行任何操作. - 如果具有事件 ID 的文档尚不存在,请将
context.eventId
的值放入您添加的文档的属性中.
- First check your collection to see if a document has a property with the value of
context.eventId
in it. If it exists, do nothing in the function. - If a document with the event id doesn't already exist, put the value of
context.eventId
in a property in the document that you add.
这应该防止函数的多次调用为给定的事件 ID 添加多个文档.
This should prevent multiple invocations of the function from adding more than one document for a given event id.
这篇关于云函数和具有幂等性的 Firebase Firestore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!