我可以信任Cloud Firestore触发器的顺序吗? [英] Can I trust the order of the Cloud Firestore triggers?

查看:42
本文介绍了我可以信任Cloud Firestore触发器的顺序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试与Cloud Firestore一起使用的Firebase Cloud Functions设置调试一些奇怪的问题.我正在将一些数据写入Cloud Firestore,并在Cloud Functions中内置了一些触发器.当我查看日志时,似乎有时onCreate触发器在onUpdate触发器之后运行.

I'm trying to debug some weird issues with my Firebase Cloud Functions setup used together with Cloud Firestore. I'm writing some data to Cloud Firestore and have some triggers built in Cloud Functions. When I look at the logs it seems like sometimes onCreate trigger runs after onUpdate trigger.

文档中,我读到与所有后台功能一样,事件排序不能保证."

From documentation I read "As with all background functions, event ordering is not guaranteed."

因此,据我了解,这实际上可能发生吗?我只想确保这会在我的设置中发生很大的变化.

So from my understanding this can actually happen? I just want to make sure as this would change a lot in my setup.

例如,如果在更新或创建文档时需要更新其他文档,那么如果更新未按正确顺序运行,如何确保写入最新数据.我通常使用来自change.after.data()的数据,但我能看到的唯一其他解决方案是每次都读取数据以确保拥有最新数据.

For example if I need to update some other document when a document is updated or created, how can I make sure I write the latest data if the updates doesn't run in the correct order. I usually use the data from change.after.data() but the only other solution I could see would be to read the data everytime to make sure to have the latest.

有两个问题:

  1. 我可以相信我的触发器以相同的顺序发生吗?
  2. 如果没有,我该如何解决这个问题?

感谢您的解释和帮助!

推荐答案

正如文档所述:不能保证解决触发器的顺序.

As the documentation already says: the order in which triggers are resolved is not guaranteed.

处理此问题的最佳方法是确保所有操作都是幂等的. IE.多次执行相同的操作或以不同的顺序运行,将导致相同的结果.这是我亲自在onCreateonUpdate等上使用onWrite触发器首选的原因之一,因为它们使我更容易编写在其中执行相同操作的代码所有情况.

The best way to deal with this is to ensure that all your operations are idempotent. I.e. running the same operation multiple times or in a different order, leads to the same result. This is one of the reasons I personally prefer using onWrite triggers, over onCreate, onUpdate, etc., since they make it easier for me to write code that performs the same operation in all cases.

因此,在您的代码中,您将检查目标文档是否已存在.如果是这样,请阅读目标文档.如果不是,请创建对新文档的引用.接下来,您将检查目标文档是否包含所需的数据.如果可以,则什么也不做.如果不是,则根据源文档生成数据,然后将其写入Firestore.

So in your code you'll check if the target document already exists. If it does, read the target document. If not, create a reference to a new document. Next you'll check if the target documents contains the data you want. If it does, do nothing. If it doesn't, generate the data based on the source document, and write it to Firestore.

这篇关于我可以信任Cloud Firestore触发器的顺序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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