不能从firebase功能获得参数

时间:2018-06-01 18:03:16

标签: javascript angularjs firebase sendgrid

我目前正在尝试从firebase函数发送包含sendgrid API的确认电子邮件。

API不是问题,但似乎工作正常,我的问题是我无法让孩子创造价值(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

我的participant_id也是一个整数值(例如:3827),如果这改变了什么。

提前致谢!

1 个答案:

答案 0 :(得分:0)

该函数的签名错误,请查看Handle event data上的此示例:

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

因此,只需调整您的onCreate功能即可完成设置:)