【问题标题】:Firebase functions update document / sendgridFirebase 函数更新文档/sendgrid
【发布时间】:2019-12-04 03:58:39
【问题描述】:

我有 Firebase Firestore 的这个功能,每次在集合 pagos 中创建一个新文档时,我都会通过 Sendgrid 发送一封交易电子邮件,其中包含创建的这个新文档的数据。效果很好。

我的问题是我如何做同样的功能,即发送所说的电子邮件但只有当文档更新了某个字段时(例如dataPago)可以做到吗?

这是我创建文档时的功能:

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

const admin = require('firebase-admin');
admin.initializeApp();

const SENDGRID_API_KEY = functions.config().sendgrid.key

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(SENDGRID_API_KEY);

exports.pagoRealizado = functions.firestore
  .document('pagos/{pagoId}')
  .onCreate((snap, context) => {
     const pagoId = context.params.pagoId;
     const db = admin.firestore()
     return db.collection('pagos').doc(pagoId)
       .get()
       .then(doc => {
          const pago = doc.data();
          const msg = {
            from: 'xxx@gmail.com',
            to: 'xxx@xxx.com',
            templateId: 'd-3473a9cc588245b7b2a6633f05dafdd8',
            substitutionWrappers: ['{{', '}}'],
            dynamic_template_data: {
               nombre: pago.dataCliente.nombre,
               }
          };
            return sgMail.send(msg)
          })
          .then(() => console.log('email enviado!'))
          .catch(err => console.log(err))
});

【问题讨论】:

    标签: javascript firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    您可以使用 onUpdate 触发器,而不是使用 onCreate 触发器。每当匹配的文档以某种方式更改但未创建或删除时,这将触发。您可以在documentation 中阅读有关每种 Firestore 触发器的更多信息。

    您不能在文档中的特定字段上设置触发器。当文档中的任何字段以任何方式更改时,触发器将触发。您必须检查传递给函数的文档快照的前后状态,以确定它是否是您想要采取行动的更改。同样,文档对此进行了更详细的讨论。

    【讨论】:

      猜你喜欢
      • 2019-09-16
      • 2019-05-19
      • 1970-01-01
      • 2020-05-24
      • 2019-10-06
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多