我正在尝试编写一个具有Firebase云功能的函数,该函数会在将新消息添加到我的“ contactMessages”实时数据库中后立即发送电子邮件。所以我做到了,但是在这里我得到了一个未定义的快照:
const functions = require("firebase-functions");
const nodemailer = require("nodemailer");
const gmailEmail =
encodeURIComponent(functions.config().gmail.email);
const gmailPassword =
encodeURIComponent(functions.config().gmail.password);
const mailTransport = nodemailer.createTransport(
`smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`
);
exports.sendContactMessage = functions.database
.ref("/contactMessages/{pushKey}")
.onWrite((change, context) => {
// Only send email for new messages.
if (snapshot.previous.val() || !snapshot.val().name) {
return;
}
const val = snapshot.val();
const mailOptions = {
to: "test@example.com",
subject: `Information Request from ${val.name}`,
html: val.html
};
return mailTransport.sendMail(mailOptions).then(() => {
return console.log("Mail sent to: test@example.com");
});
});
答案 0 :(得分:1)
更改此:
exports.sendContactMessage = functions.database
.ref("/contactMessages/{pushKey}")
.onWrite((change, context) => {
// Only send email for new messages.
if (snapshot.previous.val() || !snapshot.val().name) {
return;
}
对此:
exports.sendContactMessage = functions.database
.ref("/contactMessages/{pushKey}")
.onWrite((change, context) => {
// Only send email for new messages.
if (change.before.val() || !change.after.val().name) {
return;
}
从文档中
对于
onWrite
和onUpdate
事件,change
参数具有before
和after
字段。每个都是DataSnapshot
,具有admin.database.DataSnapshot
中可用的相同方法。