Firebase函数与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链。你应该做如下:

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. 当所有异步工作完成时,您不会从解析函数返回promise。这是一项要求。调用then和`catch是不够的。实际上,函数处理程序会返回一个promise。

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

还有一种可能性是,您的项目不在支付计划中,在这种情况下,由于免费计划中缺乏出站网络,对sendgrid的调用总是会失败。你需要有一个付款计划,这样才能发挥作用。

相关内容

  • 没有找到相关文章

最新更新