【发布时间】:2021-03-01 13:18:14
【问题描述】:
我有一个云功能,只要用户在网络应用程序上执行一组操作并且每天在指定时间执行一组操作,我就想运行它。为了不重复代码和未来的功能/错误修复,我想从一个函数/文件中运行两者。
对此流程的任何建议/参考将不胜感激!
【问题讨论】:
标签: firebase google-cloud-functions
我有一个云功能,只要用户在网络应用程序上执行一组操作并且每天在指定时间执行一组操作,我就想运行它。为了不重复代码和未来的功能/错误修复,我想从一个函数/文件中运行两者。
对此流程的任何建议/参考将不胜感激!
【问题讨论】:
标签: firebase google-cloud-functions
您可以在一个函数中编写业务逻辑,从两个云函数调用该函数。大致如下,具有异步业务逻辑并使用async/await:
exports.myFunctionCalledFromTheApp = functions.https.onCall(async (data, context) => {
try {
const result = await asyncBusinessLogic();
return { result: result }
} catch (error) {
// ...
}
});
exports.myFunctionCalledByScheduler = functions.pubsub.schedule('every 24 hours').onRun(async (context) => {
try {
await asyncBusinessLogic();
return null;
} catch (error) {
// ...
return null;
}
});
async function asyncBusinessLogic() {
const result = await anAsynchronousJob();
return result;
}
【讨论】:
context 对象传递给asyncBusinessLogic() 函数,但请注意auth 对象只会为可调用函数填充,而不是为预定函数填充(参见@ 987654321@)。由您来管理这两种不同的情况。
!context.auth 似乎不安全?
async function asyncBusinessLogic(context, caller); 和 await asyncBusinessLogic(context, 'callable'); 和 await asyncBusinessLogic(context, 'scheduled');