【问题标题】:can't get params from firebase function无法从 firebase 函数获取参数
【发布时间】:2018-06-01 18:03:16
【问题描述】:

我目前正在尝试通过 firebase 函数使用 sendgrid API 发送确认电子邮件。

API 不是问题,它似乎工作正常,我的问题是我无法获取子 oncreate 的值(Firebase 函数日志):

TypeError: Cannot read property 'participant_id' of undefined
    at exports.SendEmail.functions.database.ref.onCreate.event (/user_code/index.js:15:38)
    at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
    at next (native)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
    at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
    at /var/tmp/worker/worker.js:716:24
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

这是我的代码:

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

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

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

exports.SendEmail = functions.database.ref('participants/{participant_id}').onCreate(event => {


  const participant_id = event.params.participant_id;

  const db = admin.database();

  return db.ref(`participants/${participant_id}`).once('value').then(function(data){

    const user = data.val();

    const email = {
      to: user.email,
      from: 'recrutement.cisssme16@ssss.gouv.qc.ca',
      subject: "Bienvenue au Blitz d'embauche 2018!",

      templateId: 'dd3c9553-5e92-4054-8919-c47f15d3ecf6',
      substitutionWrappers: ['<%', '%>'],
      substitutions: {
        name: user.name,
        num: user.num
      }
    };

    return sgMail.send(email)
  })
  .then(() => console.log('email sent to', user.email))
  .catch(err => console.log(err))

});

这不是我的第一个 firebase 功能。我什至复制了以前的工作代码,这些代码可以正常工作,但我仍然得到一个未定义的值!

这里有什么问题? firebase 是否更改了event.params

我的参与者 ID 也是一个整数值(例如:3827),如果这改变了一些东西的话。

提前致谢!

【问题讨论】:

    标签: javascript angularjs firebase sendgrid


    【解决方案1】:

    函数的签名错误,看看Handle event data上的这个例子:

    exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
        .onCreate((snapshot, context) => {
            console.log('Uppercasing', context.params.pushId, original);
        });
    

    因此,只需调整您的 onCreate 函数,您就一切就绪 :)

    【讨论】:

      猜你喜欢
      • 2018-10-13
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-27
      相关资源
      最近更新 更多