Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problems with response snapshot of firebase functions

exports.getCompanies = app.https.onRequest((req, res) => {
  
  const starCountRef = app.database.ref("company/");
  starCountRef.onCreate((snapshot, context) => {
    res.send(snapshot.val());
  });

});

exports.getCompanies = app.https.onRequest((req, res) => {
  
  const starCountRef = app.database.ref("company/");
  var data;
  starCountRef.onCreate((snapshot, context) => {
    data = snapshot.val();
  });
  res.send(data);
});


These are the two ways im trying to send back a response. The first one just loads so im guessing its stuck in the onCreate. The second one gives me undefined which im guessing i need to wait a bit longer before the data gets the snapshot. But ive tried to add a then to the onCreate but it didnt work since its not a async function.

Before i used functions ive written the restapi locally and then the second method worked to send back the data. But now im getting undefined.

If anyone has a solution for this it would be very appriciated. I need a way to wait for the data. Is it a promise? How would it be implemented in that case?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I understand that you want to read a Realtime Database node form in an HTTPS Cloud Function and send back the result. In a Cloud Function for Firebase you need to use the Node.js Admin SDK in order to interact with the Firebase services.

The following should do the trick:


const functions = require('firebase-functions');

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


exports.getCompanies = functions.https.onRequest(async (req, res) => {

    try {
        const starCountRef = admin.database().ref("company/");
        const snapshot = await starCountRef.get()

        res.status(200).send(snapshot.val());
    } catch (error) {
        // Watch the video https://youtu.be/7IkUgCLr5oA
    }
    
});

Note that:

  • We use functions.https.onRequest and not app.https.onRequest
  • We use async/await because the get() method is asynchronous
  • How we import, initialize and use the Admin SDK (admin.database().ref("company/");).
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading