Firestore + cloud function: How to tell if it's a create, update, or delete event

Viewed 2732

I want to write a Firebase cloud function that is triggered by a Firestore write event. Inside of the function, I have to know if the write is actually a create, update, or delete function. The logic is slightly different, but I don't want to copy and paste three different event handlers. How can I tell which event type it is?

The cloud documentation reads very confusing to me.

The documentation for Event says that in the case of FireStore, the event is actually a DeltaDocumentSnapshot.

https://firebase.google.com/docs/reference/functions/functions.Event

The documentation for DeltaDocumentSnapshot suggests that the class has no information about the event itself (e.g. indication of create, update, or delete), but only the target document:

https://firebase.google.com/docs/reference/functions/functions.firestore.DeltaDocumentSnapshot

I found samples, where the author seemed to infer create/update/delete by checking if the current or previous document exists. I've tried that but I get an error.

https://github.com/firebase/functions-samples/blob/master/child-count/functions/index.js#L30

Here is what I've tried:

exports.updateLikeCount = functions.firestore
.document('likes/{likeId}').onWrite((event) => {
    if (event.data.data().exists()) {
      // Looks like the document still exists. It must be an update or create.
    }

    if (event.data.previous.data().exists()) {
      // Looks like the document existed before. It must be an update or delete.
    }

That code fails with this error:

TypeError: event.data.exists is not a function
2 Answers

I've tried a few different things. The version below seems to work, yet I don't know if it is correct.

var exists = event.data.exists;`
var hasExisted = (event.data.previous != null) && event.data.previous.exists;
var isCreate = (exists && !hasExisted);
var isDelete = (!exists && hasExisted);
Related