云功能和具有幂等性的Firebase Firestore [英] Cloud functions and Firebase Firestore with Idempotency
问题描述
我正在使用带有Cloud Functions的Beta版本的Firestore.在我的应用程序中,我需要触发一个函数,该函数侦听/company/{id}/point/{id}
处的onCreate
事件并执行插入(collection('event').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的云功能需要幂等函数.我不知道如何确保如果函数在同一事件中连续触发两次,则不会添加具有相同数据的两个文档.
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屋!