0

right now I have something similar to

 var cursor = self.apos.docs.find(req, { highSearchText:  {$regex: new RegExp(self.apos.utils.regExpQuote(req.query.search), 'i') }  } )

 cursor.queryToFilters({ highSearchText:  {$regex: new RegExp(self.apos.utils.regExpQuote(req.query.search), 'i') }  }, 'public')

.perPage(self.perPage);

And I am trying to figure out a way to implement autocomplete

Parik Tiwari
  • 1,525
  • 1
  • 12
  • 19

1 Answers1

1

As you know I'm the head of the Apostrophe team at P'unk Avenue.

You're trying way, way, way too hard (:

Name your search field "autocomplete" in your form.

Then do this:

var cursor = self.apos.docs.find(req, {})
  .queryToFilters(req.query, 'public')
  .perPage(self.perPage);
};

Really... that's it. The whole purpose of queryToFilters is to basically just do this (not quite, see below for security notes on what it really does):

// DON'T DO THIS, JUST GIVES YOU AN IDEA OF WHAT'S GOING ON
_.each(req.query, function(val, key) {
  cursor[key](val);
});

It invokes cursor methods with the same name as the properties of req.query (well, almost).

Of course that would be unsafe, but queryToFilters specifically makes sure the methods in question are cursor filters that are marked as safeFor: 'public' and runs their sanitizers too.

autocomplete is such a cursor filter, so... boom, we're done.

Also, I see you are working with self.apos.docs.find directly. I assume you are doing that because you want ALL types of docs to come back from the query, in which case you are doing the right thing.

In case it is not clear, if you're not even working with a query string in the first place, you can just call autocomplete directly with whatever it is you do have:

cursor.autocomplete('startofaword');

Hope this is helpful!

Tom Boutell
  • 7,281
  • 1
  • 26
  • 23