【发布时间】:2017-04-03 18:49:44
【问题描述】:
我正在尝试实现一些代码,该代码可以向任何想要订阅我的时事通讯的人发送电子邮件。该代码实际上是有效的,但它发送了多个重复项。我正在使用 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);
});
}
});
【问题讨论】:
标签: node.js firebase firebase-realtime-database google-cloud-functions