-
-
Notifications
You must be signed in to change notification settings - Fork 424
Expand file tree
/
Copy pathuseAlgoliaSearch.ts
More file actions
238 lines (216 loc) · 6.04 KB
/
useAlgoliaSearch.ts
File metadata and controls
238 lines (216 loc) · 6.04 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import type { NpmSearchResponse, NpmSearchResult } from '#shared/types'
import {
liteClient as algoliasearch,
type LiteClient,
type SearchResponse,
} from 'algoliasearch/lite'
/**
* Singleton Algolia client, keyed by appId to handle config changes.
*/
let _searchClient: LiteClient | null = null
let _configuredAppId: string | null = null
function getOrCreateClient(appId: string, apiKey: string): LiteClient {
if (!_searchClient || _configuredAppId !== appId) {
_searchClient = algoliasearch(appId, apiKey)
_configuredAppId = appId
}
return _searchClient
}
interface AlgoliaOwner {
name: string
email?: string
avatar?: string
link?: string
}
interface AlgoliaRepo {
url: string
host: string
user: string
project: string
path: string
head?: string
branch?: string
}
/**
* Shape of a hit from the Algolia `npm-search` index.
* Only includes fields we retrieve via `attributesToRetrieve`.
*/
interface AlgoliaHit {
objectID: string
name: string
version: string
description: string | null
modified: number
homepage: string | null
repository: AlgoliaRepo | null
owners: AlgoliaOwner[] | null
downloadsLast30Days: number
downloadsRatio: number
popular: boolean
keywords: string[]
deprecated: boolean | string
isDeprecated: boolean
license: string | null
}
/** Fields we always request from Algolia to keep payload small */
const ATTRIBUTES_TO_RETRIEVE = [
'name',
'version',
'description',
'modified',
'homepage',
'repository',
'owners',
'downloadsLast30Days',
'downloadsRatio',
'popular',
'keywords',
'deprecated',
'isDeprecated',
'license',
]
function hitToSearchResult(hit: AlgoliaHit): NpmSearchResult {
return {
package: {
name: hit.name,
version: hit.version,
description: hit.description || '',
keywords: hit.keywords,
date: new Date(hit.modified).toISOString(),
links: {
npm: `https://www.npmjs.com/package/${hit.name}`,
homepage: hit.homepage || undefined,
repository: hit.repository?.url || undefined,
},
maintainers: hit.owners
? hit.owners.map(owner => ({
name: owner.name,
email: owner.email,
}))
: [],
},
score: {
final: 0,
detail: {
quality: hit.popular ? 1 : 0,
popularity: hit.downloadsRatio,
maintenance: 0,
},
},
searchScore: 0,
downloads: {
weekly: Math.round(hit.downloadsLast30Days / 4.3),
},
updated: new Date(hit.modified).toISOString(),
}
}
export interface AlgoliaSearchOptions {
/** Number of results */
size?: number
/** Offset for pagination */
from?: number
/** Algolia filters expression (e.g. 'owner.name:username') */
filters?: string
}
/**
* Composable that provides Algolia search functions for npm packages.
*
* Must be called during component setup (or inside another composable)
* because it reads from `useRuntimeConfig()`. The returned functions
* are safe to call at any time (event handlers, async callbacks, etc.).
*/
export function useAlgoliaSearch() {
const { algolia } = useRuntimeConfig().public
const client = getOrCreateClient(algolia.appId, algolia.apiKey)
const indexName = algolia.indexName
/**
* Search npm packages via Algolia.
* Returns results in the same NpmSearchResponse format as the npm registry API.
*/
async function search(
query: string,
options: AlgoliaSearchOptions = {},
): Promise<NpmSearchResponse> {
const { results } = await client.search([
{
indexName,
params: {
query,
offset: options.from,
length: options.size,
filters: options.filters || '',
analyticsTags: ['npmx.dev'],
attributesToRetrieve: ATTRIBUTES_TO_RETRIEVE,
attributesToHighlight: [],
},
},
])
const response = results[0] as SearchResponse<AlgoliaHit> | undefined
if (!response) {
throw new Error('Algolia returned an empty response')
}
return {
isStale: false,
objects: response.hits.map(hitToSearchResult),
total: response.nbHits ?? 0,
time: new Date().toISOString(),
}
}
/**
* Fetch all packages for an Algolia owner (org or user).
* Uses `owner.name` filter for efficient server-side filtering.
*/
async function searchByOwner(
ownerName: string,
options: { maxResults?: number } = {},
): Promise<NpmSearchResponse> {
const max = options.maxResults ?? 1000
const allHits: AlgoliaHit[] = []
let offset = 0
let serverTotal = 0
const batchSize = 200
// Algolia supports up to 1000 results per query with offset/length pagination
while (offset < max) {
// Cap at both the configured max and the server's actual total (once known)
const remaining = serverTotal > 0 ? Math.min(max, serverTotal) - offset : max - offset
if (remaining <= 0) break
const length = Math.min(batchSize, remaining)
const { results } = await client.search([
{
indexName,
params: {
query: '',
offset,
length,
filters: `owner.name:${ownerName}`,
analyticsTags: ['npmx.dev'],
attributesToRetrieve: ATTRIBUTES_TO_RETRIEVE,
attributesToHighlight: [],
},
},
])
const response = results[0] as SearchResponse<AlgoliaHit> | undefined
if (!response) break
serverTotal = response.nbHits ?? 0
allHits.push(...response.hits)
// If we got fewer than requested, we've exhausted all results
if (response.hits.length < length || allHits.length >= serverTotal) {
break
}
offset += length
}
return {
isStale: false,
objects: allHits.map(hitToSearchResult),
// Use server total so callers can detect truncation (allHits.length < total)
total: serverTotal,
time: new Date().toISOString(),
}
}
return {
/** Search packages by text query */
search,
/** Fetch all packages for an owner (org or user) */
searchByOwner,
}
}