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

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

问题描述

我正在使用带有 Cloud Functions 的测试版 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天全站免登陆