import { injectable } from "inversify"; import Base from "../../base"; import { IBase, IResourceMapper, IJsonApiResponse, ISearchParams, IAutocompleteParams } from "../../interfaces"; import { ISearch, ISearchResource, searchType, ISearchResultsPayload } from "./"; import { IAutocomplete, IAutocompletePayload } from "./autocomplete"; import Mapper from "./mapper"; import AutocompleteMapper from "./autocomplete/mapper"; export interface ISearchService extends IBase { query(options: ISearchParams): Promise; createClickthrough(term: string, searchResultId: string): Promise; createAutocompleteClickthrough(prefix: string, searchResultSwiftypeId: string): Promise; queryAutocomplete(options: ISearchParams): Promise; } @injectable() export default class SearchService extends Base implements ISearchService { resource: string = searchType; mapper: IResourceMapper = new Mapper(); public url() { return `${this.host}/search`; } public async query(options: ISearchParams): Promise { const response = await this.http.fetch>( `${this.url()}${this.qs(options)}`, { ...options, headers: this.headers(), }); const parsed = this.parse(response); return { data: parsed, meta: { query: response.meta.query as string, total: response.meta.total as number, }, total: response.meta.total as number, }; } public async createClickthrough(term, searchResultId) { await this.http.fetch(`${this.url()}/clickthroughs`, { method: "POST", body: { data: { attributes: { term: term, id: searchResultId }, type: 'search-clickthrough', } }, headers: this.headers(), }); } public async createAutocompleteClickthrough(prefix, searchResultSwiftypeId) { await this.http.fetch(`${this.url()}/autocomplete/clickthroughs`, { method: "POST", body: { data: { attributes: { prefix: prefix, id: searchResultSwiftypeId }, type: 'autocomplete-clickthrough', } }, headers: this.headers(), }); } public async queryAutocomplete(options: IAutocompleteParams): Promise { const url = `${this.url()}/autocomplete${this.qs(options)}`; const response = await this.http.fetch>(url, { headers: this.headers(), ...options }); const mapper: IResourceMapper = new AutocompleteMapper(); return { meta: { query: response.meta.query as string, total: response.meta.total as number, }, data: mapper.map(response) } } }