api/src/lib/search.ts
45 lines · 1177 bytes
4 symbols in this file
1/**
2 * Full-text search over every service in the awesome-privacy dataset
3 * Builds a MiniSearch index lazily on first call, then reuses it
4 * Used for the public /search endpoint and MCP search_services tool
5 */
6
7import MiniSearch from 'minisearch'
8import { allServices } from '@/lib/data'
9import type { FlatService } from '@/types'
10
11type Indexed = FlatService & { id: string }
12
13let index: MiniSearch<Indexed> | null = null
14
15const STORED_FIELDS = [
16 'slug',
17 'name',
18 'url',
19 'description',
20 'category',
21 'categorySlug',
22 'section',
23 'sectionSlug',
24]
25
26const build = () => {
27 // Service slugs repeat across sections, so build a composite id
28 const items: Indexed[] = allServices().map((service) => ({
29 ...service,
30 id: `${service.sectionSlug}/${service.slug}`,
31 }))
32 const ms = new MiniSearch<Indexed>({
33 idField: 'id',
34 fields: ['name', 'description', 'category', 'section'],
35 storeFields: STORED_FIELDS,
36 searchOptions: { boost: { name: 3, section: 1.5 }, fuzzy: 0.2, prefix: true },
37 })
38 ms.addAll(items)
39 return ms
40}
41
42export const search = (query: string, limit = 20) => {
43 index ??= build()
44 return index.search(query).slice(0, limit)
45}