Firebase云功能快照未定义

时间:2019-05-17 10:54:04

标签: javascript node.js firebase firebase-realtime-database google-cloud-functions

我正在尝试编写一个具有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");
  });
});

1 个答案:

答案 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;
  }

从文档中

  

对于onWriteonUpdate事件,change参数具有beforeafter字段。每个都是DataSnapshot,具有admin.database.DataSnapshot中可用的相同方法。