0

I use this function to wait for an HTTP request from my app. Once it gets fired, it will use its filter function to only add items to the array that match the search term given by the http request.

Can it be optimized for speed performance?

exports.getFoodnames = functions.https.onRequest((request, response) => {
  cors(request, response, () => {
    const ref = admin.database().ref('foodnames');
    ref.once('value').then((snapshot)=> {
      let filtered_name = [];
      let searchTerm = request.query.search;

      snapshot.forEach(snap => {
        if (snap.val().name.indexOf(searchTerm) !== -1) filtered_names.push({ name : snap.val().name, $key: snap.key});
      });

      response.status(200).send(JSON.stringify(filtered_names));
    });
  });
});
Sam van beastlo
  • 819
  • 2
  • 11
  • 24
  • Which part exactly do you think could be optimized? I think a direct connection to the database from the client would be way faster. – creativecreatorormaybenot Aug 20 '17 at 11:46
  • True, but that's not an option because firebase does not allow for text filtering inside a string. It's only possible to use something like 'startAt' and that would really limit the usability of the search. – Sam van beastlo Aug 20 '17 at 11:51
  • The filtering you do is the equivalent of a "contains" operation. This operation is not available in Firebase Database queries. See https://stackoverflow.com/questions/28589092/firebase-query-find-item-with-child-that-contains-string – Frank van Puffelen Aug 20 '17 at 12:48

0 Answers0