Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

110
Vistas
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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda