node.jsfirebasefirebase-realtime-databasefirebase-cloud-messaginggupshup

Accessing Firebase database from Gupshup


I am building a bot using Gupshup and Firebase. I wish to do two tasks: (i) I wish to store all my conversations with the users. (ii) When the users opens the conversation, I want to fetch the last 10 conversations.

Gupshup supports HTTP GET and HTTP POST methods.

The code for POST method:

var url3 = "https://My app name.firebaseio.com/Chat.json";
           var header3 = {"Content-Type": "application/json"};
               var param3 = JSON.parse(res).result.fulfillment.speech; // Parsing Result from NLP tool

       context.simplehttp.makePost(url3,JSON.stringify(param3),header3); 

The code for GET method:

context.simplehttp.makeGet('https://My app name.firebaseio.com/Chat.json', function(c,e){
var res = "Sample response from http put method\n"+e.getresp;
context.sendResponse(res);

Every time I make a HTTP POST to add data to the Firebase database, a real time is generated under which the data gets added.

Chat:

-KY4yWKeGKIKPf1qf74G:

"hi"

-KY4yWKfjoztU0EBPe1g:

"Hello. How can I help you?"

-KY4ykQtSus8srqa7okF:

"Okay here is the deal: Buy a pizza today and ge..."

-KY4ykQtSus8srqa7okG:

"show some deals"

When I try with HTTP GET https://My app name.firebaseio.com/Chat.json, the following JSON is returned:

{"-KY4x81jkuxvT9TjDOfk":"Hello. How can I help you?",
 "-KY4x81kw8zBoaKwAIe-":"hi","-KY4xAQCFDU7SW8PAEHX":"get",
 "-KY4xAR1KEEQNO1KfjnI":"I'm a bit confused by that last part."}

Now how can I parse this JSON and access the conversations and present it to users?

Or is there any way to access Child directly using HTTP GET?

Thanks in advance


Solution

  •     You can use the following way to access the keys and the data:
        //Parse your JSON if you are getting it using http call using JSON.parse(yourjson);
    
        var json={"-KY4x81jkuxvT9TjDOfk":"Hello. How can I help you?",
         "-KY4x81kw8zBoaKwAIe-":"hi","-KY4xAQCFDU7SW8PAEHX":"get",
         "-KY4xAR1KEEQNO1KfjnI":"I'm a bit confused by that last part."};
       //Getting Keys
    
       var keys=Object.keys(json);
       //Getting Conversations
       for(var i=0;i<keys.length;i++)
       {
        console.log(json[keys[i]);
       }