具有幂等性的云函数和 Firebase Firestore

Cloud functions and Firebase Firestore with Idempotency

我在 Cloud Functions 中使用 Beta 版的 Firestore。在我的应用程序中,我需要触发一个函数,该函数在 /company/{id}/point/{id} 处侦听 onCreate 事件并执行插入 (collection('event').add({...}))

我的问题是:带有 Firestore 的 Cloud Functions 需要幂等函数。我不知道如何确保如果我的函数连续触发两次相同的事件,我不会添加两个具有相同数据的文档。

我发现 context.eventId 可以解决这个问题,但我不知道如何使用它。

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)
})

两件事:

  1. 首先检查您的 collection 以查看文档中是否有 属性 且其中的值为 context.eventId。如果存在,则在函数中什么也不做。
  2. 如果不存在具有事件 ID 的文档,请将 context.eventId 的值放入您添加的文档的 属性 中。

这应该可以防止函数的多次调用为给定的事件 ID 添加多个文档。

为什么不 set 文档(通过上下文中的事件 ID 建立索引)而不是创建文档?这样如果你写了两次,你只会覆盖而不是创建一个新记录。

https://firebase.google.com/docs/firestore/manage-data/add-data

这种方法使写操作幂等。