与 Sendgrid 集成的 Firebase 函数

Firebase functions integrating with Sendgrid

我是 Firebase 函数的新手,我正在尝试创建一个简单的 onCreate() 触发器,但我似乎无法启动它 运行。

我没有正确返回 Sendgrid 的承诺吗?不确定我错过了什么

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const sendGrid = require("@sendgrid/mail");
admin.initializeApp();

const database = admin.database();
const API_KEY = '';
const TEMPLATE_ID = '';
sendGrid.setApiKey(API_KEY);

const actionCodeSettings = {
  ...
};

exports.sendEmailVerify = functions.auth.user().onCreate((user) => {
  admin
    .auth()
    .generateEmailVerificationLink(user.email, actionCodeSettings)
    .then((url) => {
      const msg = {
        to: user.email,
        template_id: TEMPLATE_ID,
        dynamic_template_data: {
          subject: "test email",
          name: name,
          link: url,
        },
      };
      return sendGrid.send(msg);
    })
    .catch((error) => {
      console.log(error);
    });
});

来自 firebase 函数的日志

sendEmailVerify
Function execution started

sendEmailVerify
Function returned undefined, expected Promise or value

sendEmailVerify
Function execution took 548 ms, finished with status: 'ok'

sendEmailVerify
{ Error: Forbidden

sendEmailVerify
at axios.then.catch.error (node_modules/@sendgrid/client/src/classes/client.js:133:29)

sendEmailVerify
at process._tickCallback (internal/process/next_tick.js:68:7)

sendEmailVerify
code: 403, 

sendEmailVerify
message: 'Forbidden', 

您没有在云函数中正确返回 Promises chain。你应该这样做:

exports.sendEmailVerify = functions.auth.user().onCreate((user) => {
  return admin // <- See return here
    .auth()
    .generateEmailVerificationLink(user.email, actionCodeSettings)
    .then((url) => {
      const msg = {
        to: user.email,
        template_id: TEMPLATE_ID,
        dynamic_template_data: {
          subject: "test email",
          name: name,
          link: url,
        },
      };
      return sendGrid.send(msg);
    })
    .catch((error) => {
      console.log(error);
      return null;
    });
});

这里至少有两个编程问题。

  1. 您不是 return 函数的承诺,它会在所有异步工作完成时解析。这是一个要求。调用 then 和 `catch 是不够的。您实际上有一个来自函数处理程序的 return 承诺。

  2. 您正在调用 sendGrid.send(email),但您从未在代码中的任何地方定义变量 email。如果是这种情况,那么您将向 sendgrid 传递一个未定义的值。

也有可能您的项目不在付费计划中,在这种情况下,由于免费计划中缺少出站网络,调用 sendgrid 总是会失败。你需要有一个付款计划才能使它起作用。