Firebase的云功能:电子邮件重复

时间:2017-04-03 18:49:45

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

我正在尝试实施一些代码,以便向想要注册我的简报的任何人发送电子邮件。代码实际上正在工作,但它会发送多个重复项。我正在使用Firebase的样本代码,就像这样。

我认为问题在于它会在 {uid} 上监听每次更改并且我设置了4个值。如果我从仪表板手动更改数据库中的任何内容,它将触发事件并发送新邮件。我的代码:

'use strict';

const functions = require('firebase-functions');
const nodemailer = require('nodemailer');

// Configure the email transport using the default SMTP transport and a GMail account.
// For other types of transports such as Sendgrid see https://nodemailer.com/transports/
// TODO: Configure the `gmail.email` and `gmail.password` Google Cloud environment variables.

const gmailEmail = encodeURIComponent(functions.config().gmail.email);
const gmailPassword = encodeURIComponent(functions.config().gmail.password);
const mailTransport = nodemailer.createTransport(
    `smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`);

// Sends an email confirmation when a user changes his mailing list subscription.
exports.sendEmailConfirmation = functions.database.ref('/mailingList/{uid}').onWrite(event => {
  const snapshot = event.data;
  const val = snapshot.val();

  if (!snapshot.changed('subscribed')) {
    return;
  }

  const mailOptions = {
    from: '"Spammy Corp." <noreply@firebase.com>',
    to: val.email
  };

  // The user just subscribed to our newsletter.
  if (val.subscribed == true) {
      mailOptions.subject = 'Thanks and Welcome!';
      mailOptions.text = 'Thanks you for subscribing to our newsletter. You will receive our next weekly newsletter.';
      return mailTransport.sendMail(mailOptions).then(() => {
        console.log('New subscription confirmation email sent to:', val.email);
    });
  }
});

1 个答案:

答案 0 :(得分:1)

数据库触发器 将针对其监视的路径所做的每次更改运行,您需要为此进行规划。在您的功能中,您需要一种方法来确定电子邮件是否已经发送。典型的解决方案是将一个布尔值或一些其他标志值写回触发更改的节点,然后每次检查该值并在设置时提前返回。

&#xA;