Cloud Functions for Firebase onWrite trigger: snapshot.val is not a function

后端 未结 2 1252
时光取名叫无心
时光取名叫无心 2021-01-06 05:00

I created few functions in the same index.js file, which is sendEmail, sendEmailByDbStatusChange and sendEmailConfirmation.

相关标签:
2条回答
  • 2021-01-06 05:39

    It looks like you updated to v1.0 of the Firebase SDK for Cloud Functions, but didn't upgrade your code to match.

    The entire process is explained in this documentation page. Right now you're being hit by the changes in database triggers, which shows that:

    Event data now a DataSnapshot

    In earlier releases, event.data was a DeltaSnapshot; now in v 1.0 it is a DataSnapshot.

    For onWrite and onUpdate events, the data parameter has before and after fields. Each of these is a DataSnapshot with the same methods available in admin.database.DataSnapshot. For example:

    Before (<= v0.9.1)

    exports.dbWrite = functions.database.ref('/path').onWrite((event) => {
      const beforeData = event.data.previous.val(); // data before the write
      const afterData = event.data.val(); // data after the write
    });
    

    Now (v1.0.0)

    exports.dbWrite = functions.database.ref('/path').onWrite((change, context) => {
      const beforeData = change.before.val(); // data before the write
      const afterData = change.after.val(); // data after the write
    });
    

    According to that example, you'll need something along these lines:

    exports.sendEmailConfirmation = functions.database.ref('/users/{uid}').onWrite((change, context) => {
      const snapshot = change.after;
      const val = snapshot.val();
      console.log(val)
    
      if (!snapshot.changed('subscribedToMailingList')) {
        return null;
      }
    
      const mailOptions = {
        from: '"Spammy Corp." <noreply@firebase.com>',
        to: val.email,
      };
    
      const subscribed = val.subscribedToMailingList;
    
      // Building Email message.
      mailOptions.subject = subscribed ? 'Thanks and Welcome!' : 'Sad to see you go :`(';
      mailOptions.text = subscribed ? 'Thanks you for subscribing to our newsletter. You will receive our next weekly newsletter.' : 'I hereby confirm that I will stop sending you the newsletter.';
    
      return mailTransport.sendMail(mailOptions)
        .then(() => console.log(`New ${subscribed ? '' : 'un'}subscription confirmation email sent to:`, val.email))
        .catch((error) => console.error('There was an error while sending the email:', error));
    });
    
    0 讨论(0)
  • 2021-01-06 05:51

    Since version 1.0.0 of the firebase-functions module, database onWrite events now deliver a Change object rather than a DataSnapshot object as the first parameter. You can read about all the breaking changes in 1.0.0 in the documentation. You should use this change object instead to choose if you want to examine the contents of the database before or after the change that invoked it.

    0 讨论(0)
提交回复
热议问题