Search code examples
node.jsgoogle-cloud-firestoresendgrid-templates

sending email through firebase triggers using sendgrid


I am sending email to user using onCreate trigger in firebase.I am using sendgrid templates for sending emails. when a new document is created in the firestore it should trigger the email to the user.

 const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const sgMail = require('@sendgrid/mail');
const SENDGRID_API_KEY = 'SG.ivqQZKFcSdqONZZ7IRtkjA.1RdSs50..kBaQ';
sgMail.setApiKey(SENDGRID_API_KEY);
exports.firestoreEmail = functions.firestore
.document('userAccount/{userId}')
.onCreate(event => {
  const userID = event.params.userId;

  if (userID === undefined) {
    console.log('userID DOES NOT EXIST')
    // This was a deletion event, we don't want to process this
    return;
  }
else{

    console.log(userID )
    return db.collection('userAccount').doc(userID)
             .get()
             .then(doc => {

                const user = doc.data()

                const msg = {
                    to: '[email protected]',
                    from: '[email protected]',
                    subject: 'NewFollower',

                    templateId: '8...............d760e',
                    substitutionWrappers: ['{{', '}}'],
                    substitutions: {
                      name: user.UserName
                      // and other custom properties here
                    }
                };

                return sgMail.send(msg)
            })
            // .then(() => console.log('email sent!') )
          }  // .catch(err => console.log(err) )

        });

The error I am getting is: TypeError: Cannot read property 'userId' of undefined


Solution

  • You have 2 parameters from the .onCreate() method. A snapshot from the created document and the event.

    exports.firestoreEmail = functions.firestore
      .document('userAccount/{userId}')
      .onCreate((documentSnapshot, event) => {
          const userID = event.params.userId;
          const documentData = documentSnapshot.data();
    

    I do not know if the event.params.userId works for Firestore.

    If you need the userId from the user which created the document you could use const userID = event.auth.uid.

    If you need the userId from the user you will send the mail to you should write the userId in the document.