如何防止“冲突"? firebase云功能? [英] How to prevent "conflicting" firebase cloud functions?

查看:67
本文介绍了如何防止“冲突"? firebase云功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组具有基于时间的派生属性的对象.

I have a set of objects that has a time-based derived property.

我有一个Firebase云函数,该函数正在侦听创建和写入以计算该属性,并且运行良好.

I have a Firebase cloud function that is listening for creates and writes to calculate the property and it is working well.

我还添加了一个通过HTTP触发的功能(例如cron),以在周日清晨重新计算属性(该属性每周更改一次).

I have also added a function that is triggered via HTTP, like a cron, to recalculate the property early in the morning on Sunday (this property will change weekly).

这工作正常,但是只要cron函数更新了属性,第一个函数就会捕获写入并再次进行整个计算.

This is working fine, but whenever the cron function updates a property, the first function catches the write and does the whole calculation over again.

有没有一种简单的方法可以防止这种情况发生?我已经探索过为第一个函数设置环境变量以检测cron是否正在运行,但是似乎无法在运行时设置环境变量.

Is there a simple way to prevent this? I've explored setting an environment variable for the first function to detect if the cron is running, but it doesn't seem that environment variables can be set at runtime.

推荐答案

您应该可以通过检查先前的值来防止出现这种情况.我会尝试提供一个例子

You should be able to prevent this by checking the previous value. I'll try to provide an example

exports.yourFunction = functions.database.ref('/somepath/{someKey}').onWrite(event => {
  if (event.data.previous.val().time != event.data.val().time) {
    return;
  }
  else {
    // perform calculation
  }
 });

总而言之,如果先前的值与当前值不同,则变量time只是被您的其他函数更改了.您需要将.time更改为变量名.

In summary if the previous value is not the same as the current value then the variable time was just changed by your other function. You'll need to change .time to your variable name.

注意:这不会阻止函数触发,只会阻止它再次执行计算.如果您根本不希望函数触发,则必须设计一种不同的方法来计算值.例如仅计算onCreate,然后在设定的时间间隔内使用Cron更新值.监听onWrite会使每次将数据写入Firebase时触发该函数.

Note: This does not prevent the function from firing, it only prevents it from preforming the calculation again. If you don't want the function to fire at all you'll have to devise a different way of calculating the value. Such as only calculating it onCreate then use the Cron at a set time interval to update the values. Listening to onWrite will cause the function to fire everytime data is written to Firebase.

您可以阅读有关 Firebase数据库触发器

这篇关于如何防止“冲突"? firebase云功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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