Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud functions and Firebase Firestore with Idempotency

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)
})
like image 959
João Victor Avatar asked Apr 26 '18 16:04

João Victor


2 Answers

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.

like image 117
Doug Stevenson Avatar answered Sep 22 '22 00:09

Doug Stevenson


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.

like image 24
brabster Avatar answered Sep 18 '22 00:09

brabster