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

179
Visualizações
Firebase functions crashes while accessing firestore

Could you please find an error in following code?

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



exports.GetShort = functions.https.onRequest((request, response) => {
    response.header("Access-Control-Allow-Origin", "*");
    longURL = request.query.long
    functions.logger.info("url is - " ,longURL)
    SaveToDB(longURL)
})


function SaveToDB(link){
    functions.logger.info("here")
    admin.firestore().collection("url").where("urlNames","array_contains",link).get().then(
  
        function(querySnapshot){
            functions.logger.info("snap, " ,querySnapshot)
            querySnapshot.forEach(function(doc) {
            functions.logger.info("things :  " ,doc.id, " => ", doc.data())

                // doc.data() is never undefined for query doc snapshots
                console.log(doc.id, " => ", doc.data());
            });
        }
    ) .catch(function(error) {
        functions.logger.info("Error getting documents: ", error);
    });
}

After hitting above function, firebase-functions logs displays logs till "here". After that it crashes without any more logs/stacktrace.

below is the contents of packages.json from functions directory.

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "lint": "eslint .",
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "14"
  },
  "main": "index.js",
  "dependencies": {
    "firebase-admin": "^9.8.0",
    "firebase-functions": "^3.14.1"
  },
  "devDependencies": {
    "eslint": "^7.6.0",
    "eslint-config-google": "^0.14.0",
    "firebase-functions-test": "^0.2.0"
  },
  "private": true
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I would kindly suggest you watch the 3 videos about "JavaScript Promises" from the Firebase video series to see how to manage the life cycle of a Cloud Function and the way to deal with calls to asynchronous methods.

In particular, for an HTTPS Cloud Function, you need to end it with send(), redirect(), or end().

So your code could be adapted as follows:

exports.GetShort = functions.https.onRequest((request, response) => {
    response.header("Access-Control-Allow-Origin", "*");
    const longURL = request.query.long;
    functions.logger.info("url is - ", longURL)
    SaveToDB(longURL)
    .then(() => {
        response.status(200).send('Saved to DB');
    })
    .catch(error => {
        // See video series
        response.status(500).send(error);
    })
})


function SaveToDB(link) {
    functions.logger.info("here")
    return admin.firestore().collection("url").where("urlNames", "array_contains", link).get()
    .then(querySnapshot => {
        functions.logger.info("snap, ", querySnapshot)
        querySnapshot.forEach(function (doc) {
            functions.logger.info("things :  ", doc.id, " => ", doc.data())

            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data());
            
            // => Here, depending on your real functional requirements, you may need to use Promise.all()
            
        });
        return null;
    }
    ).catch(function (error) {
        functions.logger.info("Error getting documents: ", error);
        // Throw an error
    });
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Well, I found the problem. Sometimes silly things make most of the noise around. Instead of "array-contains", I wrote "array_contains".

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