/**
* Search by Azure Search API
* @param options : (object)
*/
var AzureSearch = function(options) {
SearchService.apply(this, arguments);
var self = this;
var endpoint = "https://" +self.config.serviceName+ ".search.windows.net/indexes/" +self.config.indexName+ "/docs?api-version=2015-02-28";
self.nav.current = 1;
/**
* 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.excerptStrip || "";
html += self.buildResult(url, title, digest);
});
return html;
};
/**
* Generate metadata after a successful query
* @param data : (object) the raw response data
* @param startIndex : (int) requested start index of current query
*/
self.buildMetadata = function(data, startIndex) {
self.nav.current = startIndex;
self.nav.currentCount = data.value.length;
self.nav.total = parseInt(data['@odata.count']);
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));
if (self.nav.total > 0) {
self.dom.metadata.show();
}
else {
self.dom.metadata.hide();
}
if (self.nav.current+self.nav.currentCount <= self.nav.total) {
self.nav.next = self.nav.current+self.nav.currentCount;
self.dom.nextButton.show();
}
else {
self.nav.next = -1;
self.dom.nextButton.hide();
}
if (self.nav.current > 1) {
self.nav.prev = self.nav.current-self.nav.currentCount;
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, startIndex, callback) {
self.uiBeforeQuery();
$.ajax({
url: endpoint,
headers: {
"Accept": "application/json",
"api-key": self.config.apiKey
},
data: {
search: queryText,
$skip: startIndex-1,
$top: self.config.per_page,
$count: true
},
type: "GET",
success: function(data, status) {
if (status === 'success' && data.value && data.value.length > 0) {
var results = self.buildResultList(data.value);
self.dom.resultContainer.html(results);
}
else {
self.onQueryError(queryText, status);
}
self.buildMetadata(data, startIndex);
self.uiAfterQuery();
if (callback) {
callback(data);
}
}
});
};
self.init();
};