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



我试图实现一些代码,向任何想注册我的时事通讯的人发送电子邮件。代码实际上有效,但它发送了多个重复项。我使用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);
    });
  }
});

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

最新更新