AbdullahMQ
AbdullahMQ

Reputation: 23

How read data by Dialogflow on Firebase

I use dialog flow chatbot but when I try to bring books from DB firebase I should write the key !!

picture for DB
I want read all keys ! but the problem on code I must declare key to bring data the in this case (-LsDnHZFnJ1Iz5sGsRKu) like this

 function handlecat(agent){
   return admin.database().ref('Books/-LsDnHZFnJ1Iz5sGsRKu').once("value").then((snapshot) => {
     agent.add(`in ` + snapshot.child('title').val() );
   });
 }

how can I do it auto like loop!? I use this code

admin.database().ref('Books').once("value").then((snapshot) => {
let books = snapshot.val();
books.forEach(function(element) {
    agent.add(element.child('title').val()); /// and I use element.title
});
});
}

but doesn't work !!

Upvotes: 1

Views: 472

Answers (1)

Prisoner
Prisoner

Reputation: 50701

If you want all of the children of "Book", then you can get a reference to that path, call once() on it, and get the val() of the snapshot returned. This should give you an array of books. Something like this:

admin.database().ref('Books').once("value").then((snapshot) => {
  let books = snapshot.val();
});

This will be a JavaScript Array, so you won't need to re-fetch everything from the server. You can just access this using normal JavaScript methods, so if there is a "title" attribute in each book that you want, you can get it with something like

books.forEach( element => {
  console.log( element.title );
} );

But this could be very large if you have a lot of items in that array. And it may take a while to fetch and a lot of memory to store. If you are, there are various approaches to working with lists of data including using ordering and filtering methods such as orderByChild() and limitToFirst() depending on your needs.

Once you have this value, you also need to send it to the user, since it sounds like you're using Dialogflow. One issue is that you can't just call agent.add() for each item, since some of Dialogflow's integrations only support calling agent.add() once and this may create a long list of titles which won't be very usable in a chat agent. Think about ways to narrow this down to just one or a few titles that you may want to report back. So it might be something like this

if( books.length === 0 ){
  agent.add( `There are no books.` );
} else if( books.length === 1 ){
  agent.add( `There is one book named ${books[0].title}` );
} else {
  agent.add( `There are ${books.length} books including one named ${books[0].title}` );
}

Upvotes: 1

Related Questions