Sunshine
Sunshine

Reputation: 334

Trigger Email Firebase Extension on modified Document

How do i trigger the sending of an email when a document data is modified ?

Trigger Email only composes and sends an email based on the contents of a document written to a Cloud Firestore collection but not modified

I can’t figure this one out…

Upvotes: 0

Views: 386

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599766

From checking the code we can see that the extension already processes all writes to the document:

export const processQueue = functions.handler.firestore.document.onWrite(
  ...

From looking a bit further it seems that the action the extension takes upon a write depends on the value of the delivery.state field in the document.

async function processWrite(change) {
  ...
  const payload = change.after.data() as QueuePayload;
  ...

  switch (payload.delivery.state) {
    case "SUCCESS":
    case "ERROR":
      return null;
    case "PROCESSING":
      if (payload.delivery.leaseExpireTime.toMillis() < Date.now()) {
        // Wrapping in transaction to allow for automatic retries (#48)
        return admin.firestore().runTransaction((transaction) => {
          transaction.update(change.after.ref, {
            "delivery.state": "ERROR",
            error: "Message processing lease expired.",
          });
          return Promise.resolve();
        });
      }
      return null;
    case "PENDING":
    case "RETRY":
      // Wrapping in transaction to allow for automatic retries (#48)
      await admin.firestore().runTransaction((transaction) => {
        transaction.update(change.after.ref, {
          "delivery.state": "PROCESSING",
          "delivery.leaseExpireTime": admin.firestore.Timestamp.fromMillis(
            Date.now() + 60000
          ),
        });
        return Promise.resolve();
      });
      return deliver(payload, change.after.ref);
  }
}

My guess is that if you clear that field, the extension will pick up on that change and try to mail the document again.

Upvotes: 1

Related Questions