1 import {
2 adaptFacetFilters,
3 adaptNumericFilters,
4 mergeFiltersAnd,
5 withQuery,
6 } from "./filters"
7 import type {
8 InstantSearchAdapterOptions,
9 InstantSearchRequest,
10 InstantSearchSearchParams,
11 SearchFacetRequest,
12 SearchHighlightOptions,
13 SearchOptions,
14 SearchOrderBy,
15 SearchPagination,
16 SearchQuery,
17 } from "./types"
18
19 const SORT_SUFFIX = /^(.*)\/sort\/(.+)$/
20
21 export function parseSearchParams(
22 params?: InstantSearchSearchParams | string
23 ): InstantSearchSearchParams {
24 if (!params) {
25 return {}
26 }
27 if (typeof params !== "string") {
28 return params
29 }
30
31 const search = new URLSearchParams(params)
32 const result: Record<string, unknown> = {}
33
34 for (const [key, value] of search.entries()) {
35 if (
36 key === "page" ||
37 key === "hitsPerPage" ||
38 key === "maxValuesPerFacet" ||
39 key === "maxFacetHits"
40 ) {
41 result[key] = Number(value)
42 continue
43 }
44
45 if (key === "typoTolerance" || key === "distinct") {
46 if (value === "true") {
47 result[key] = true
48 } else if (value === "false") {
49 result[key] = false
50 } else if (!Number.isNaN(Number(value)) && value !== "") {
51 result[key] = Number(value)
52 } else {
53 result[key] = value
54 }
55 continue
56 }
57
58 if (
59 key === "facetFilters" ||
60 key === "numericFilters" ||
61 key === "facets" ||
62 key === "attributesToRetrieve" ||
63 key === "attributesToHighlight" ||
64 key === "attributesToSnippet" ||
65 key === "restrictSearchableAttributes"
66 ) {
67 result[key] = parseMaybeJson(value)
68 continue
69 }
70
71 result[key] = value
72 }
73
74 return result as InstantSearchSearchParams
75 }
76
77 function parseMaybeJson(value: string): unknown {
78 try {
79 return JSON.parse(value)
80 } catch {
81 return value
82 }
83 }
84
85 export function stringifyParams(params: InstantSearchSearchParams): string {
86 const search = new URLSearchParams()
87 for (const [key, value] of Object.entries(params)) {
88 if (value === undefined) {
89 continue
90 }
91 search.set(key, typeof value === "string" ? value : JSON.stringify(value))
92 }
93 return search.toString()
94 }
95
96 export function parseIndexName(indexName: string): {
97 entity: string
98 order?: Record<string, SearchOrderBy>
99 } {
100 const match = indexName.match(SORT_SUFFIX)
101 if (!match) {
102 return { entity: indexName }
103 }
104
105 const entity = match[1]
106 const order: Record<string, SearchOrderBy> = {}
107
108 for (const part of match[2].split(",")) {
109 if (!part) {
110 continue
111 }
112 const separator = part.lastIndexOf(":")
113 const field = separator === -1 ? part : part.slice(0, separator)
114 const direction = separator === -1 ? "ASC" : part.slice(separator + 1)
115 if (!field) {
116 continue
117 }
118 order[field] = direction.toUpperCase() === "DESC" ? "DESC" : "ASC"
119 }
120
121 return {
122 entity,
123 order: Object.keys(order).length ? order : undefined,
124 }
125 }
126
127 function parseSnippetAttribute(attribute: string): {
128 field: string
129 length?: number
130 } {
131 const separator = attribute.lastIndexOf(":")
132 if (separator <= 0) {
133 return { field: attribute }
134 }
135 const field = attribute.slice(0, separator)
136 const length = Number(attribute.slice(separator + 1))
137 if (Number.isNaN(length)) {
138 return { field: attribute }
139 }
140 return { field, length }
141 }
142
143 type MappingOptions = Pick<
144 InstantSearchAdapterOptions,
145 | "numericAttributes"
146 | "distinctAttribute"
147 | "additionalSearchParameters"
148 | "indexSpecificSearchParameters"
149 >
150
151 function eachFacetName(
152 facets: InstantSearchSearchParams["facets"],
153 visit: (field: string) => void
154 ): void {
155 if (facets == null || facets === "") {
156 return
157 }
158
159 if (Array.isArray(facets)) {
160 for (const facet of facets) {
161 if (facet && facet !== "*") {
162 visit(facet)
163 }
164 }
165 return
166 }
167
168 if (facets !== "*") {
169 visit(facets)
170 }
171 }
172
173 function buildSearchOptions(
174 params: InstantSearchSearchParams,
175 options: MappingOptions
176 ): SearchOptions | undefined {
177 let result: SearchOptions | undefined
178 const numericAttributes = options.numericAttributes
179
180 eachFacetName(params.facets, (field) => {
181 result ??= {}
182 const facets = (result.facets ??= [])
183
184 if (numericAttributes?.includes(field)) {
185 facets.push({ field, type: "stats" })
186 return
187 }
188
189 const facet: SearchFacetRequest = { field, type: "value" }
190 if (params.maxValuesPerFacet != null) {
191 facet.limit = params.maxValuesPerFacet
192 }
193 if (params.sortFacetValuesBy) {
194 facet.sort = params.sortFacetValuesBy
195 }
196 facets.push(facet)
197 })
198
199 const highlightFields: string[] = []
200 let snippetConfigured = false
201 let snippetLength: number | undefined
202
203 const addHighlightField = (field: string) => {
204 if (!field || field === "*" || highlightFields.includes(field)) {
205 return
206 }
207 highlightFields.push(field)
208 }
209
210 if (params.attributesToHighlight) {
211 for (const field of params.attributesToHighlight) {
212 addHighlightField(field)
213 }
214 }
215
216 if (params.attributesToSnippet) {
217 for (const attribute of params.attributesToSnippet) {
218 snippetConfigured = true
219 const snippet = parseSnippetAttribute(attribute)
220 addHighlightField(snippet.field)
221 if (snippetLength == null && snippet.length != null) {
222 snippetLength = snippet.length
223 }
224 }
225 }
226
227 if (highlightFields.length) {
228 const highlight: SearchHighlightOptions = { fields: highlightFields }
229 if (params.highlightPreTag) {
230 highlight.pre_tag = params.highlightPreTag
231 }
232 if (params.highlightPostTag) {
233 highlight.post_tag = params.highlightPostTag
234 }
235 if (snippetConfigured) {
236 highlight.snippet =
237 snippetLength != null ? { length: snippetLength } : true
238 }
239 result ??= {}
240 result.highlight = highlight
241 }
242
243 if (params.restrictSearchableAttributes?.length) {
244 result ??= {}
245 result.attributes_to_search_on = params.restrictSearchableAttributes
246 }
247
248 if (params.typoTolerance === false || params.typoTolerance === true) {
249 result ??= {}
250 result.typo_tolerance = params.typoTolerance
251 }
252
253 if (params.distinct && options.distinctAttribute) {
254 result ??= {}
255 result.distinct = options.distinctAttribute
256 }
257
258 return result
259 }
260
261 function mergeSearchOptions(
262 base?: SearchOptions,
263 overlay?: SearchOptions
264 ): SearchOptions | undefined {
265 if (!base) {
266 return overlay
267 }
268 if (!overlay) {
269 return base
270 }
271
272 return {
273 ...base,
274 ...overlay,
275 facets: overlay.facets ?? base.facets,
276 highlight: overlay.highlight ?? base.highlight,
277 }
278 }
279
280 function applyLayer(
281 query: SearchQuery,
282 layer?: Partial<Omit<SearchQuery, "entity">>
283 ): void {
284 if (!layer) {
285 return
286 }
287
288 const filters = mergeFiltersAnd(query.filters, layer.filters)
289 if (filters) {
290 query.filters = filters
291 }
292
293 query.fields ??= layer.fields
294
295 if (layer.pagination) {
296 const pagination = (query.pagination ??= {})
297 pagination.skip ??= layer.pagination.skip
298 pagination.take ??= layer.pagination.take
299 pagination.order ??= layer.pagination.order
300 pagination.cursor ??= layer.pagination.cursor
301 }
302
303 query.search_options = mergeSearchOptions(
304 layer.search_options,
305 query.search_options
306 )
307 }
308
309 function applyConfiguredParameters(
310 query: SearchQuery,
311 options: MappingOptions
312 ): SearchQuery {
313 applyLayer(query, options.additionalSearchParameters)
314 applyLayer(query, options.indexSpecificSearchParameters?.[query.entity])
315 return query
316 }
317
318 function fromInstantSearch(
319 request: InstantSearchRequest,
320 options: MappingOptions
321 ): SearchQuery {
322 const params = parseSearchParams(request.params)
323 const { entity, order } = parseIndexName(request.indexName)
324 const query: SearchQuery = { entity }
325
326 if (params.hitsPerPage != null || order) {
327 const pagination: SearchPagination = {}
328 if (params.hitsPerPage != null) {
329 pagination.take = params.hitsPerPage
330 pagination.skip = (params.page ?? 0) * params.hitsPerPage
331 }
332 if (order) {
333 pagination.order = order
334 }
335 query.pagination = pagination
336 }
337
338 const filters = withQuery(
339 params.query,
340 mergeFiltersAnd(
341 adaptFacetFilters(params.facetFilters),
342 adaptNumericFilters(params.numericFilters)
343 )
344 )
345 if (filters) {
346 query.filters = filters
347 }
348
349 if (params.attributesToRetrieve?.length) {
350 query.fields = params.attributesToRetrieve
351 }
352
353 const searchOptions = buildSearchOptions(params, options)
354 if (searchOptions) {
355 query.search_options = searchOptions
356 }
357
358 return query
359 }
360
361 export function adaptSearchRequest(
362 request: InstantSearchRequest,
363 options: MappingOptions = {}
364 ): SearchQuery {
365 return applyConfiguredParameters(fromInstantSearch(request, options), options)
366 }
367
368 export function adaptFacetSearchRequest(
369 request: InstantSearchRequest,
370 options: MappingOptions = {}
371 ): SearchQuery {
372 const query = adaptSearchRequest(request, options)
373 const params = parseSearchParams(request.params)
374
375 if (!params.facetName) {
376 throw new Error(
377 "@medusajs/instantsearch-adapter: searchForFacetValues requires params.facetName"
378 )
379 }
380
381 const pagination = (query.pagination ??= {})
382 pagination.skip = 0
383 pagination.take = 0
384
385 const facet: SearchFacetRequest = {
386 field: params.facetName,
387 type: "value",
388 limit: params.maxFacetHits ?? params.maxValuesPerFacet ?? 10,
389 }
390 if (params.facetQuery) {
391 facet.query = params.facetQuery
392 }
393
394 const searchOptions = (query.search_options ??= {})
395 searchOptions.facets = [facet]
396
397 return query
398 }