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?
>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.onRequestand notapp.https.onRequest - We use
async/awaitbecause theget()method is asynchronous - How we import, initialize and use the Admin SDK (
admin.database().ref("company/");).