kumovega-instantsearch-adapter
Version:
Adapter to use InstantSearch UI widgets with Kumovega Search
96 lines (82 loc) • 3.18 kB
JavaScript
;
import { Configuration } from "./Configuration";
import { SearchClient as KumovegaSearchClient } from "kumovega";
import { SearchRequestAdapter } from "./SearchRequestAdapter";
import { SearchResponseAdapter } from "./SearchResponseAdapter";
import { FacetSearchResponseAdapter } from "./FacetSearchResponseAdapter";
export default class KumovegaInstantsearchAdapter {
constructor(options) {
this.updateConfiguration(options);
this.searchClient = {
clearCache: () => this.clearCache(),
search: (instantsearchRequests) => this.searchKumovegaAndAdapt(instantsearchRequests),
searchForFacetValues: (instantsearchRequests) => this.searchKumovegaForFacetValuesAndAdapt(instantsearchRequests),
};
}
async searchKumovegaAndAdapt(instantsearchRequests) {
let kumovegaResponse;
try {
kumovegaResponse = await this._adaptAndPerformKumovegaRequest(instantsearchRequests);
const adaptedResponses = kumovegaResponse.results.map((kumovegaResult, index) => {
this._validateKumovegaResult(kumovegaResult);
const responseAdapter = new SearchResponseAdapter(
kumovegaResult,
instantsearchRequests[index],
this.configuration,
kumovegaResponse.results,
kumovegaResponse,
);
let adaptedResponse = responseAdapter.adapt();
return adaptedResponse;
});
return {
results: adaptedResponses,
};
} catch (error) {
console.error(error);
throw error;
}
}
async searchKumovegaForFacetValuesAndAdapt(instantsearchRequests) {
let kumovegaResponse;
try {
kumovegaResponse = await this._adaptAndPerformKumovegaRequest(instantsearchRequests);
const adaptedResponses = kumovegaResponse.results.map((kumovegaResult, index) => {
this._validateKumovegaResult(kumovegaResult);
const responseAdapter = new FacetSearchResponseAdapter(
kumovegaResult,
instantsearchRequests[index],
this.configuration,
);
return responseAdapter.adapt();
});
return adaptedResponses;
} catch (error) {
console.error(error);
throw error;
}
}
async _adaptAndPerformKumovegaRequest(instantsearchRequests) {
const requestAdapter = new SearchRequestAdapter(instantsearchRequests, this.kumovegaClient, this.configuration);
const kumovegaResponse = await requestAdapter.request();
return kumovegaResponse;
}
clearCache() {
this.kumovegaClient = new KumovegaSearchClient(this.configuration.server);
return this.searchClient;
}
updateConfiguration(options) {
this.configuration = new Configuration(options);
this.configuration.validate();
this.kumovegaClient = new KumovegaSearchClient(this.configuration.server);
return true;
}
_validateKumovegaResult(kumovegaResult) {
if (kumovegaResult.error) {
throw new Error(`${kumovegaResult.code} - ${kumovegaResult.error}`);
}
if (!kumovegaResult.hits && !kumovegaResult.grouped_hits) {
throw new Error(`Did not find any hits. ${kumovegaResult.code} - ${kumovegaResult.error}`);
}
}
}