0

When the user files a request a firestore document is being created with its respective data. This creation of a document triggers a firebase function which then sends an email to a specific address. It works fine, but how can I get the promise from the function to return a success/error alert (clientside), when this email has been send/not send.

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();

exports.request = functions.firestore.document('requests/{requestId}').onCreate(async (snapshot, context) => {
  const itemDataSnap = await snapshot.ref.get();
  const name = itemDataSnap?.data()?.name ? itemDataSnap?.data()?.name : 'Unbekannt';
  const email = itemDataSnap?.data()?.email;
  const products = itemDataSnap?.data()?.products ? itemDataSnap?.data()?.products : 'Fehler: Keine Produkte vorhanden';

  return admin.firestore().collection('mail').add({
    to: [...],
    from: [email],
    message: {
      subject: ...,
      html: ...
    }
  }).then(() => console.log('Queued email for delivery!'))
});

As you can see, so far I'm logging 'Queued email for delivery!' as a success message for the firebase console - but how can I bring this to the client's side (to the user)?

1 Answer 1

1

Your Cloud Function is triggered by writing to the database. There is no way to return a value to the client directly from that, as there is no direct connection from this code to a client.

You have two options:

  1. Change this to a callable Cloud Function, which then performs the write to the database, and returns the value.
  2. Write the result to the database, and have the client wait for that.

The latter could for example be done by setting up a responses/{requestId} collection/document, that the Cloud Function write to. And since the document ID is the same as the request ID, the client can wait for that document to be written.

You could also base the document ID in the mail collection on the requestId, in which case the client can also wait for that document to show up:

return admin.firestore().collection('mail').doc(context.params.requestId).set(...)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.