Cloud Function for Firebase:电子邮件重复

Cloud Function for Firebase: Email Duplicates

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

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