简体   繁体   中英

Cloud Functions - Use global variables

I have a function cloudFunctionCall in my cloud-function setup that is invoked on every cloud function call.

import * as functions from "firebase-functions";
const mysql = require("mysql");

function cloudFunctionCall(asyncFunc) {
  return functions
    .region(region)
    .https.onCall(async (data: any, context: any) => {
      try {
        const pool = mysql.createPool(getConfig(context));
        const result = await asyncFunc(data, pool);
        pool.end();
        res.send(result);
      } catch (err) {
        log("A promise failed to resolve", err);
        res.status(500).send(err);
      }
    });
}

export const func1 = cloudFunctionCall(_func1);
export const func2 = cloudFunctionCall(_func2);

context and therefore pool defines to which database an invoked function needs to talk to which might change on every cloud function call. Now I want to avoid passing pool as a parameter to asyncFunc since it is not actually required for the function logic and makes the functions more verbose.

Now my question: Is it safe to define pool as a global variable that gets updated on every cloud function call like the following?

//...
let pool;

function cloudFunctionCall(asyncFunc) {
  return functions
    .region(region)
    .https.onCall(async (data: any, context: any) => {
      try {
        pool = mysql.createPool(getConfig(context));
        const result = await asyncFunc(data, pool);
//...

I understand that every exported function is hosted in it's own environment but what would happen if func1 would get executed twice in quick succession on different databases? Could it happen that the second invocation overwrites pool that was set by the first invocation so that the latter one executes on the wrong database?

If so, is there another way to avoid passing pool as a parameter?

Cloud Function invocations run in strict isolation of each other: each container will only ever have one execution at a time. So there is no chance of function invocations overwriting the value of your global for each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM