【发布时间】:2020-08-26 09:43:10
【问题描述】:
使用 firebase,您可以write cloud functions in multiple files。
我有两个函数,名为“function1”和“function2”,位于两个单独的文件中。
文件:function1.js
const functions = require('firebase-functions');//This will be executed regardless of the function called
exports.function1 = functions.https.onRequest((request, response) => {
// ...
});
文件:function2.js
const functions = require('firebase-functions');//This will be executed regardless of the function called
const admin = require('firebase-admin');//This will be executed regardless of the function called
exports.function2 = functions.https.onRequest((request, response) => {
// ...
});
现在我使用 index.js 来导出这些文件,如 here 所示。
文件:index.js
const function1 = require('./function1');
const function2 = require('./function2');
exports.function1 = function1.function1;
exports.function2 = function2.function2;
当我执行 function1 时,我可以从 function2 访问“admin”变量。
明显的解决方法是不在全局范围内声明变量。
修改文件:function2.js
const functions = require('firebase-functions');//This will be executed regardless of the function called
exports.function2 = functions.https.onRequest((request, response) => {
const admin = require('firebase-admin');//This will only be executed when function2 is called
// ...
});
现在“admin”变量仅在我调用 function2 而不是 function1 时才被初始化。
Cloud Functions 经常recycles 之前调用的执行环境。
如果您在全局范围内声明一个变量,则其值可以在后续调用中重复使用,而无需重新计算。
但是现在“admin”变量将不会在后续调用中被重用,因为它没有在全局范围内声明。
所以我的问题是如何将“admin”变量存储在全局范围内(以便它可以被多个实例重用),但在调用 function1 时没有初始化它?
【问题讨论】:
标签: javascript firebase google-cloud-platform google-cloud-functions