Firebase cloud function server side global variables

為{幸葍}努か 提交于 2020-05-15 04:14:18

问题


It's possible to have a sort of a global variable on firebase cloud functions?

I mean I could have an index.js like that in which set-up a global variable, let's say panicModeVariable.

And I would like to check in my cloud functions this variable before doing anything, like here in the auth create user trigger.

const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

var globalVariable = false;

// Create Account User
exports.createUserAccount = functions.auth.user().onCreate(event => {
    if (!globalVariable) {
        const uid = event.data.uid
        const email = event.data.email
        const photoUrl = event.data.photoURL
    }
    [...]

I tried with two dummy functions

exports.setGlobal = functions.https.onRequest((request, response) => {
    globalVariable = true;
    response.send("Set " + globalVariable);
});

exports.getGlobal = functions.https.onRequest((request, response) => {
    response.send("Read " + globalVariable);
});

But it seems that I cannot access this variable in the way I intended.

The writing function it uses a 'local' variable, while the reading one uses the initial value, always.

I'd like to do that, if it is possible, to have a sort of server side variable to be read directly without the need to a call to the SDK to read, let's say, a database stored value (so that to not have a function call counting).


回答1:


You could use Environment Config variables https://firebase.google.com/docs/functions/config-env

As far as I'm aware, you can't set them in the function themselves, they need to be set by CLI before you upload a function.

You could do something like firebase functions:config:set panic.mode=true

Then in your createUserAccount function you could call functions.config().panic.mode

But this won't help you set the variable via the https trigger. For that you'll need to make use of the database.



来源:https://stackoverflow.com/questions/48874686/firebase-cloud-function-server-side-global-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!