I created few functions in the same index.js file, which is sendEmail
, sendEmailByDbStatusChange
and sendEmailConfirmation
.
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 aDeltaSnapshot
; now in v 1.0 it is aDataSnapshot
.For
onWrite
andonUpdate
events, thedata
parameter hasbefore
andafter
fields. Each of these is aDataSnapshot
with the same methods available inadmin.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));
});
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.