meteorhacks / search-source

Reactive Data Source for Search
MIT License
146 stars 33 forks source link

Metadata #31

Open roberto-belardo opened 9 years ago

roberto-belardo commented 9 years ago

Hi, I tried to use the API getMetadata to get the number of results for a certain search but I can get it working. Could you provide a working example?

I defined an helper:

Template.toursSearchResults.helpers({
  meta: function() {
    console.log("METADATA: " + TourSearch.getMetadata());
    return TourSearch.getMetadata();
  }
});

I defined a server searchSource:

SearchSource.defineSource('tours', function(searchText, options) {
  var options = {sort: {submitted: -1}, limit: 20};
  if(searchText) {
   var regExp = buildRegExp(searchText);
   var selector = {$or: [
     {title: regExp},
     {summary: regExp}
   ]};
   return Tours.find(selector, options).fetch();
//  var data = getSearchResult(searchText);
//  var metadata = getMetadata();

//  return {
//    data: data,
//    metadata: metadata
//  }
 } else {
   return Tours.find({}, options).fetch();
 }
});

function buildRegExp(searchText) {
  // this is a dumb implementation
  var parts = searchText.trim().split(/[ \-\:]+/);
  return new RegExp("(" + parts.join('|') + ")", "ig");
}

And i am calling the search in the helper at the keyup as in you example:

Template.toursSearchBox.events({
  "keyup #search-box": _.throttle(function(e) {
    var text = $(e.target).val().trim();
    TourSearch.search(text);
  }, 200)
});

But i cannot get the metadata. In the browser console i get an empty metadata object. If i uncomment the getMetadata() call in the searchSource server side definition I get a getMetadata is not defined.

Could you help me understand where is the error?

Thank you for your great job!

Kostanos commented 9 years ago

You should define which data you want to have in metadata in the Server side. Example:

SearchSource.defineSource('meals', function(searchText, options){
  var options = options ? options : {sort: {_id: -1}, limit: 5};
  var selector = {}
  if (searchText){
    var regExp = buildRegExp(searchText);
    selector = {$or: [
      {title: regExp},
      {description: regExp}
    ]};
  }
  var query = Tours.find(selector, options);
  return {
    data: query.fetch(),
    metadata: {count: query.count()}
  }
});
...
WitaliB commented 8 years ago

@Kostanos: That worked perfect for me. Thanks.

guylemon commented 8 years ago

+1 @Kostanos This also worked for me. Thanks!

krishnaff commented 8 years ago

+1 @Kostanos Thank you!