首页 > 解决方案 > 无法从 firebase 函数获取参数

问题描述

我目前正在尝试通过 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 功能。我什至复制了粘贴的以前的工作代码,这些代码工作得很好,但我仍然得到一个未定义的值!

这里有什么问题?火力基地改变了event.params吗?

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

提前致谢!

标签: javascriptangularjsfirebasesendgrid

解决方案


函数的签名是错误的,看看这个关于处理事件数据的例子:

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

所以只要调整你的onCreate功能,你就可以了:)


推荐阅读