0

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…

Sunshine
  • 372
  • 2
  • 21

1 Answers1

1

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks so much for your answer Frank ! - So if I perform those changes in the code is there a way for me to deploy this updated version of the extension to use in my Firebase ? How ? : ) – Sunshine Aug 03 '21 at 21:37
  • You shouldn't have to change the code of the extension, I merely included that to show you what the extension does. All you should need to do is change/delete the `delivery.state` of the document as far as I can tell. Did you try that? – Frank van Puffelen Aug 03 '21 at 22:06
  • Oh thanks so much ! Indeed I just had to switch delivery.state from "SUCCESS" to "RETRY" for it to resend - you're amazing Puff ! : ) – Sunshine Aug 04 '21 at 10:11