Cloud functions and Firebase Firestore with Idempotency

孤街醉人 提交于 2019-12-30 18:49:33

问题


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({...}))

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.

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:


Two things:

  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.

This should prevent multiple invocations of the function from adding more than one document for a given event id.




回答2:


Why not set the document (indexing by the event id from your context) instead of creating it? This way if you write it twice, you'll just overwrite rather than create a new record.

https://firebase.google.com/docs/firestore/manage-data/add-data

This approach makes the write operation idempotent.



来源:https://stackoverflow.com/questions/50047718/cloud-functions-and-firebase-firestore-with-idempotency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!