Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

109
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda