All files / src/search-js search.ts

93.33% Statements 14/15
85.71% Branches 6/7
100% Functions 5/5
92.85% Lines 13/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 566x                                             6x 129x 129x   129x   129x 2x   127x           2x     2x 4x 4x       2x                
import { nostojs } from "@nosto/nosto-js"
import {
  SearchOptions,
  SearchProduct,
  SearchQuery,
  SearchResult,
} from "@nosto/nosto-js/client"
 
export type Options = SearchOptions & {
  /**
   * Hit decorators to apply to the search results.
   */
  hitDecorators?: HitDecorator[]
}
 
/**
 * Performs a search operation using the provided query and options.
 *
 * @param query - The search query to be executed.
 * @param options - An object containing optional parameters for the search.
 * @param options.hitDecorators - An optional array of decorators to be applied to the search results.
 * @returns A promise that resolves to the search result.
 */
export async function search(
  query: SearchQuery,
  { hitDecorators, ...options }: Options = {}
): Promise<SearchResult> {
  const api = await new Promise(nostojs)
 
  if (hitDecorators?.length) {
    return applyDecorators(await api.search(query, options), hitDecorators)
  }
  return await api.search(query, options)
}
 
export type HitDecorator = (hit: SearchProduct) => SearchProduct
 
function applyDecorators(response: SearchResult, decorators: HitDecorator[]) {
  Iif (!response.products) {
    return response
  }
  const decorator: HitDecorator = product => {
    return decorators.reduce((acc, decorator) => {
      return decorator(acc)
    }, product)
  }
 
  return {
    ...response,
    products: {
      ...response.products,
      hits: response.products.hits.map(decorator),
    },
  }
}