forked from oramasearch/orama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
83 lines (67 loc) · 1.92 KB
/
index.ts
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
import type { Orama, TypedDocument } from '@orama/orama'
import { create, insertMultiple } from '@orama/orama'
import type { SearchResultWithHighlight } from '@orama/plugin-match-highlight'
import { afterInsert as highlightAfterInsertHook } from '@orama/plugin-match-highlight'
export type NextraOrama = Orama<typeof defaultSchema>
type HighlightedHits = SearchResultWithHighlight<NextraOrama>['hits']
export function groupDocumentsBy(arr: HighlightedHits, key: string) {
return arr.reduce((acc, current) => {
const keyValue = current.document[key] as string
if (!acc[keyValue]) {
acc[keyValue] = []
}
acc[keyValue].push(current)
return acc
}, {})
}
const defaultSchema = {
id: 'string',
title: 'string',
url: 'string',
content: 'string'
} as const
export async function createOramaIndex(basePath, locale): Promise<NextraOrama> {
const response = await fetch(`${basePath}/_next/static/chunks/nextra-data-${locale}.json`)
const data = await response.json()
const index = await create({
schema: defaultSchema,
components: {
tokenizer: {
stemming: false
}
},
plugins: [
{
name: 'match-highlight',
afterInsert: highlightAfterInsertHook
}
]
})
const paths = Object.keys(data)
const documents: TypedDocument<NextraOrama>[] = []
for (const path of paths) {
const url = path
const title = data[path].title
const content = data[path].data['']
documents.push({
id: url,
title,
url,
content
})
const sectionData = data[path].data
delete sectionData['']
for (const sectionTitle in sectionData) {
const [hash, title] = sectionTitle.split('#')
const content = sectionData[sectionTitle]
documents.push({
id: `${url}#${hash}`,
title,
url: `${url}#${hash}`,
content
})
}
}
await insertMultiple(index, documents)
return index
}