Skip to content

Commit e01ea71

Browse files
committed
allow overriding sorting
1 parent 9fa4780 commit e01ea71

File tree

2 files changed

+56
-2
lines changed

2 files changed

+56
-2
lines changed

packages/instant-meilisearch/__tests__/overridden-meilisearch-parameters.test.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,4 +61,53 @@ describe('InstantMeiliSearch overridden parameters', () => {
6161
'<span>While racing to a boxing match</span>'
6262
)
6363
})
64+
65+
test('sort parameter precedence: per-index overrides global overrides', async () => {
66+
await meilisearchClient
67+
.index('movies')
68+
.updateSettings({
69+
sortableAttributes: ['release_date', 'title'],
70+
})
71+
.waitTask()
72+
73+
const { searchClient, setMeiliSearchParams } = instantMeiliSearch(
74+
'http://localhost:7700',
75+
'masterKey',
76+
{
77+
meiliSearchParams: {
78+
sort: ['title:asc'],
79+
},
80+
}
81+
)
82+
83+
const queryParams = [
84+
{
85+
indexName: 'movies',
86+
params: { query: '', hitsPerPage: 3 },
87+
},
88+
]
89+
90+
// Test global sort override - should sort by title ascending
91+
const globalResponse = await searchClient.search<Movies>(queryParams)
92+
const globalHits = globalResponse.results[0].hits
93+
expect(globalHits.length).toBeGreaterThan(1)
94+
// Verify titles are sorted in ascending order
95+
const globalTitles = globalHits.map((hit: Movies) => hit.title).filter(Boolean)
96+
expect(globalTitles).toEqual([...globalTitles].sort())
97+
98+
// Test per-index sort override takes precedence over global
99+
setMeiliSearchParams({
100+
sort: ['title:asc'],
101+
indexesOverrides: {
102+
movies: { sort: ['title:desc'] },
103+
},
104+
})
105+
106+
const perIndexResponse = await searchClient.search<Movies>(queryParams)
107+
const perIndexHits = perIndexResponse.results[0].hits
108+
expect(perIndexHits.length).toBeGreaterThan(1)
109+
// Verify titles are sorted in descending order
110+
const perIndexTitles = perIndexHits.map((hit: Movies) => hit.title).filter(Boolean)
111+
expect(perIndexTitles).toEqual([...perIndexTitles].sort().reverse())
112+
})
64113
})

packages/instant-meilisearch/src/adapter/search-request-adapter/search-params-adapter.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,8 +195,13 @@ export function MeiliParamsCreator(searchContext: SearchContext) {
195195
}
196196
},
197197
addSort() {
198-
if (sort?.length) {
199-
meiliSearchParams.sort = Array.isArray(sort) ? sort : [sort]
198+
const overrideSort =
199+
overrideParams?.indexesOverrides?.[indexUid]?.sort ??
200+
overrideParams?.sort
201+
202+
const value = overrideSort ?? sort
203+
if (value && (Array.isArray(value) ? value.length : true)) {
204+
meiliSearchParams.sort = Array.isArray(value) ? value : [value]
200205
}
201206
},
202207
addGeoSearchFilter() {

0 commit comments

Comments
 (0)