Skip to content

Instantly share code, notes, and snippets.

@artchen
Last active September 1, 2016 16:14
Show Gist options
  • Save artchen/231eee1223539cfdd094caa07bd6bec5 to your computer and use it in GitHub Desktop.
Save artchen/231eee1223539cfdd094caa07bd6bec5 to your computer and use it in GitHub Desktop.
Universal Search Algolia Search
/**
* Search by Algolia Search
* @param options : (object)
*/
var AlgoliaSearch = function(options) {
SearchService.apply(this, arguments);
var self = this;
var endpoint = "https://" +options.appId+ ".algolia.net/1/indexes/" +options.indexName;
/**
* Generate result list html
* @param data : (array) result items
*/
self.buildResultList = function(data) {
var html = "";
$.each(data, function(index, row) {
var url = row.permalink || row.path || "";
if (!row.permalink && row.path) {
url = "/" + url;
}
var title = row.title;
var digest = row._highlightResult.excerptStrip.value || "";
html += self.buildResult(url, title, digest);
});
return html;
};
/**
* Generate metadata after a successful query
* @param data : (object) the raw google custom search response data
*/
self.buildMetadata = function(data) {
self.nav.current = data.page * data.hitsPerPage + 1;
self.nav.currentCount = data.hits.length;
self.nav.total = parseInt(data.nbHits);
self.dom.metadata.children('.total').html(self.nav.total);
self.dom.metadata.children('.range').html(self.nav.current + "-" + (self.nav.current+self.nav.currentCount-1));
self.dom.metadata.show();
if (data.page < data.nbPages-1) {
self.nav.next = (data.page+1)+1;
self.dom.nextButton.show();
}
else {
self.nav.next = -1;
self.dom.nextButton.hide();
}
if (data.page > 0) {
self.nav.prev = (data.page+1)-1;
self.dom.prevButton.show();
}
else {
self.nav.prev = -1;
self.dom.prevButton.hide();
}
};
/**
* Send a GET request
* @param queryText : (string) the query text
* @param page : (int) the current page (start from 1)
* @param callback : (function)
*/
self.query = function(queryText, page, callback) {
self.uiBeforeQuery();
$.get(endpoint, {
query: queryText,
page: page-1,
hitsPerPage: self.config.per_page,
"x-algolia-application-id": self.config.appId,
"x-algolia-api-key": self.config.apiKey
}, function(data, status) {
if (status === 'success' && data.hits && data.hits.length > 0) {
var results = self.buildResultList(data.hits);
self.dom.resultContainer.html(results);
}
else {
self.onQueryError(queryText, status);
}
self.buildMetadata(data);
self.uiAfterQuery();
if (callback) {
callback(data);
}
});
};
self.init();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment