Home > Blockchain >  How to fetch data in json format from realtime-database (Firebase)?
How to fetch data in json format from realtime-database (Firebase)?

Time:02-14

I am trying to make a search functionality in my app which basically filter the json data (for eg. product list) according to the query of user(like any product name) and shows the nearest results. I have succesfully implemented this search bar and logic of filtering but it is working on the local json data of my product list I have in my app. What I want is to fetch the json data from Network call (http call) and then filter it . But I have the data in my realtime-database and I do not know how to retrieve them as in json format. I could setup the cloud functions(node js) to return the json data to the client but I am not sure about what should be the logic in the cloud functions to connect it to realtime-database and return the response

My data in Firebase: enter image description here

Now how can I fetch this data from my app through the cloud functions ?

CodePudding user response:

I am not sure about what should be the logic in the cloud functions to connect it to realtime-database and return the response. .... how can I fetch this data from my app through the cloud functions ?

I understand that you want to use an HTTPS Cloud Function as a REST API endpoint (You write "What I want is to fetch the json data from Network call (http call)").

You can write a Cloud Function along the following lines:

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

exports.getRTDBData = functions.https.onRequest(async (req, res) => {
  
    const rtdbRootRef = admin.database().ref();

    const noticesDataSnapshot = await rtdbRootRef.child('notices').get();

    res.status(200).send(noticesDataSnapshot.val());   

});

When calling this HTTPS Cloud Function with an http call you will get the entire noticesRTDB node. If necessary, it's up to you to adapt the RTDB query, for example by filtering data, as explained in the doc.

In addition, I would suggest you watch this video for more info on how to deal with errors in your HTTPS Cloud Function.

  • Related