Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions app/composables/npm/useAlgoliaSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ export function useAlgoliaSearch() {
filters: `objectID:${checks.checkPackage}`,
length: 1,
analyticsTags: ['npmx.dev'],
attributesToRetrieve: EXISTENCE_CHECK_ATTRS,
attributesToRetrieve: ATTRIBUTES_TO_RETRIEVE,
attributesToHighlight: [],
})
}
Expand Down Expand Up @@ -369,7 +369,17 @@ export function useAlgoliaSearch() {
let packageExists: boolean | null = null
if (packageQueryIndex >= 0) {
const pkgResponse = results[packageQueryIndex] as SearchResponse<AlgoliaHit> | undefined
packageExists = (pkgResponse?.nbHits ?? 0) > 0
const [exactHit] = pkgResponse?.hits ?? []
const isExactHit = exactHit?.name === checks?.checkPackage

packageExists = isExactHit

if (exactHit && isExactHit) {
searchResult.objects = [
hitToSearchResult(exactHit),
...searchResult.objects.filter(result => result.package.name !== exactHit.name),
]
}
}

return { search: searchResult, orgExists, userExists, packageExists }
Expand Down
29 changes: 29 additions & 0 deletions test/nuxt/composables/use-algolia-search.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,33 @@ describe('useAlgoliaSearch', () => {
const filtered = objects.filter(o => !o.package.isSecurityHeld).map(o => o.package.name)
expect(filtered).toEqual(['npmx-connector'])
})

it('places an exact package match before the regular search results', async () => {
const otherHit = fixture.find(hit => hit.name === 'vuln-npm')
const exactHit = fixture.find(hit => hit.name === 'npmx-connector')

if (!otherHit || !exactHit) {
throw new Error('Expected Algolia fixtures are missing')
}

mockSearch.mockResolvedValue({
results: [
{ hits: [otherHit], nbHits: 2 },
{ hits: [exactHit], nbHits: 1 },
],
})

const { searchWithSuggestions } = useAlgoliaSearch()
const result = await searchWithSuggestions(
'npmx-connector',
{},
{ checkPackage: 'npmx-connector' },
)

expect(result.packageExists).toBe(true)
expect(result.search.objects.map(item => item.package.name)).toEqual([
'npmx-connector',
'vuln-npm',
])
})
})
Loading