相关疑难解决方法(0)

如何在云函数中进行幂等聚合?

我正在开发一个Firebase云功能,可以更新我的数据库中某些文档的一些聚合信息.这是一个非常简单的功能,只需将1个文档计数加1即可.与Firestore文档中示例函数非常相似.

我刚刚注意到,在创建单个新文档时,该函数被调用了两次.请参见下面的屏幕截图,并注意记录的文档ID(iDup09btyVNr5fHl6vif)重复两次:

在此输入图像描述

经过一番挖掘,我发现这个SO帖子说的如下:

目前不保证传递函数调用.随着Cloud Firestore和Cloud Functions集成的改进,我们计划保证"至少一次"交付.但是,在测试期间可能并非总是如此.这也可能导致单个事件的多次调用,因此对于最高质量的函数,确保函数被写为幂等的.

(来自Firestore文档:限制和保证)

这导致我的文档出现问题.如上所述的云函数意味着是幂等的(换句话说,无论函数运行一次还是多次运行,它们改变的数据应该相同).然而,我之前链接的示例函数(对我来说)并不是幂等的:

exports.aggregateRatings = firestore
  .document('restaurants/{restId}/ratings/{ratingId}')
  .onWrite(event => {
    // Get value of the newly added rating
    var ratingVal = event.data.get('rating');

    // Get a reference to the restaurant
    var restRef = db.collection('restaurants').document(event.params.restId);

    // Update aggregations in a transaction
    return db.transaction(transaction => {
      return transaction.get(restRef).then(restDoc => {
        // Compute new number of ratings
        var newNumRatings = restDoc.data('numRatings') + 1;

        // Compute new average …
Run Code Online (Sandbox Code Playgroud)

firebase google-cloud-functions google-cloud-firestore

8
推荐指数
1
解决办法
958
查看次数

具有Idempotency的云功能和Firebase Firestore

我正在使用带有云功能的测试版Firestore.在我的应用程序中,我需要触发一个侦听onCreate事件/company/{id}/point/{id}并执行插入的函数(collection('event').add({...}))

我的问题是:使用Firestore的云功能需要幂等功能.我不知道如何确保如果我的函数连续两次使用相同的事件触发,我将不会添加两个具有相同数据的文档.

我发现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)
})
Run Code Online (Sandbox Code Playgroud)

idempotent firebase google-cloud-functions google-cloud-firestore

6
推荐指数
1
解决办法
610
查看次数