云功能和具有幂等性的Firebase Firestore [英] Cloud functions and Firebase Firestore with Idempotency

查看:97
本文介绍了云功能和具有幂等性的Firebase Firestore的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有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)
})

推荐答案

两件事:

  1. 首先检查您的集合,以查看文档中是否具有值为context.eventId的属性.如果存在,则在函数中不执行任何操作.
  2. 如果尚无具有事件ID的文档,请将context.eventId的值放在您添加的文档的属性中.
  1. 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.
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆