Skip to content

Commit

Permalink
Reactive search results. Performance is not considered while implemen…
Browse files Browse the repository at this point in the history
…ting this.
  • Loading branch information
bompi88 committed Jan 28, 2016
1 parent 351b2c3 commit 04078f4
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,40 @@ Template.searchResult.helpers({
});
```

### Use reactive data in search results

By default, the contents returned by `getData()` is not reactive in the sense of it reflecting the current state of the mongo database. To use reactive content, do the following when creating a SearchSource object on the client

```js
var options = {
keepHistory: 1000 * 60 * 5,
localSearch: true,
collection: Documents, // Collection to reflect on the client
subscriptionName: 'documents.byIds' // Use subscription by this name
};

// Some fields
const fields = [ 'name', 'description' ];

const DocumentSearch = new SearchSource('docs', fields, options);
```

and on the server, publish the documents by ids

```js
Meteor.publish('documents.byIds', function (ids) {
check(ids, [ String ]);

return Documents.find({
_id: {
$in: ids
}
});
});
```

and the rest is as usual. One thing to notice is that `getData()` cannot return a cursor if reactive items are used. This is because we sort documents on a score field that is not attached to the documents itself, so mongo cannot take care of the ordering.

### Searching

Finally we can invoke search queries by invoking following API.
Expand Down
28 changes: 27 additions & 1 deletion lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ SearchSource.prototype._loadData = function(query, options) {
var self = this;
var version = 0;
var historyKey = query + EJSON.stringify(options);

if(this._canUseHistory(historyKey)) {
this._updateStore(this.history[historyKey].data);
this.metaData.set(this.history[historyKey].metadata);
Expand Down Expand Up @@ -149,6 +150,31 @@ SearchSource.prototype.getData = function(options, getCursor) {
transform: transform
});

var collection = this.options.collection;

if(collection) {
var ids = _.pluck(cursor.fetch(), '_id');

if (this.options.subscriptionName) {
Meteor.subscribe(this.options.subscriptionName, ids);
}

var docs = collection.find({
_id: {
$in: ids
}
}, {
transform: transform
}).fetch();

var sortIds = _.invert(_.object(_.pairs(ids)));
var sorted = _.sortBy(docs, function(x) {
return sortIds[x._id];
});

return sorted;
}

if(getCursor) {
return cursor;
}
Expand Down Expand Up @@ -234,4 +260,4 @@ SearchSource.prototype._getRegExpFilterRegExp = _.once(function() {
return "\\" + c;
}).join("|");
return new RegExp("(" + regExpCharsReplace + ")", "g");
});
});

0 comments on commit 04078f4

Please sign in to comment.