Can I trust the order of the Cloud Firestore trigg

2019-08-08 02:04发布

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.

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.

So two questions:

  1. Can I trust that my triggers happens in the same order?
  2. If not how do I solve this issue?

Thanks for explaining and helping!

2条回答
看我几分像从前
2楼-- · 2019-08-08 02:36

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

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.

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.

查看更多
Rolldiameter
3楼-- · 2019-08-08 02:40

Both Realtime Database and Firestore can take a timestamp command so that the instant the .create or .update occurs, it's timestamped. So, it seems like your cloud function could then look at the timestamp to determine what's the latest value(s).

.firebase.database.ServerValue.TIMESTAMP;
.firebase.firestore.FieldValue.serverTimestamp()
查看更多
登录 后发表回答