infernalsirius
5/4/2017 - 12:07 PM

Semantic UI & Algolia search

Semantic UI & Algolia search

/*
Implementing Semantic UI and Algolia search can be a pain in the but if you're not use to deal with Semantic UI API stuff. This feels a little bit hackish but so far it works well enough; bonus for not needing the Algolia javascript client.
*/

var algolia = {
  id: "Algolia app ID",
  key: "Public key",
  index: "Index name"
};

$('.ui.search')
  .search({
    cache: false,
    apiSettings: {
      method: 'post',
      url: 'https://' + algolia.id + '-dsn.algolia.net/1/indexes/' + algolia.index + '/query',
      beforeXHR: function(xhr) {
        // adjust XHR with additional headers
        xhr.setRequestHeader ('X-Algolia-API-Key', algolia.key);
        xhr.setRequestHeader ('X-Algolia-Application-Id', algolia.id);

        return xhr;
      },
      beforeSend: function(settings) {
        // Retrieve the actual query and urlencode it. There's definitely a better way to do this...
        settings.data = JSON.stringify({ "params" : "query=" + encodeURIComponent(settings.urlData.query) + "&hitsPerPage=5" });
        return settings;
      },
      onResponse: function(algoliaResponse) {
        var
          response = {
            results : []
          }
        ;
        // translate Algolia API response to work with search.
        $.each(algoliaResponse.hits, function(index, item) {
          // Of course you'll have to adapt this to your needs.
          response.results.push({
            title       : item.title,
            url         : "/myroute/" + item.id
          });
        });
        return response;
      },
    }
  });