【问题标题】:firebase cloud function snapshot undefinedfirebase 云函数快照未定义
【发布时间】:2023-03-26 02:52:01
【问题描述】:

我正在尝试使用 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");
  });
});

【问题讨论】:

  • if (snapshot.previous.val() || !snapshot.val().name) { 快照在这里未定义..
  • 是的,但我不知道应该怎么做?

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


【解决方案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 中可用的方法相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 2019-02-18
    相关资源
    最近更新 更多