forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lunr-search-index.js
94 lines (79 loc) · 2.24 KB
/
lunr-search-index.js
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
const lunr = require('lunr')
require('lunr-languages/lunr.stemmer.support')(lunr)
require('lunr-languages/tinyseg')(lunr)
require('lunr-languages/lunr.ja')(lunr)
require('lunr-languages/lunr.es')(lunr)
require('lunr-languages/lunr.pt')(lunr)
require('lunr-languages/lunr.de')(lunr)
const fs = require('fs').promises
const path = require('path')
const rank = require('./rank')
const validateRecords = require('./validate-records')
const { compress } = require('./compress')
module.exports = class LunrIndex {
constructor (name, records) {
this.name = name
// Add custom rankings
this.records = records.map(record => {
record.customRanking = rank(record)
return record
})
this.validate()
return this
}
validate () {
return validateRecords(this.name, this.records)
}
build () {
const language = this.name.split('-').pop()
const records = this.records
this.index = lunr(function constructIndex () { // No arrow here!
if (['ja', 'es', 'pt', 'de'].includes(language)) {
this.use(lunr[language])
}
this.ref('objectID')
this.field('url')
this.field('slug')
this.field('breadcrumbs')
this.field('heading')
this.field('title')
this.field('content')
this.field('topics')
this.field('customRanking')
this.metadataWhitelist = ['position']
for (const record of records) {
this.add(record)
}
})
}
toJSON () {
this.build()
return JSON.stringify(this.index, null, 2)
}
get recordsObject () {
return Object.fromEntries(
this.records.map(record => [record.objectID, record])
)
}
async write () {
this.build()
// Write the parsed records
await Promise.resolve(this.recordsObject)
.then(JSON.stringify)
.then(compress)
.then(content => fs.writeFile(
path.posix.join(__dirname, 'indexes', `${this.name}-records.json.br`),
content
// Do not set to 'utf8'
))
// Write the index
await Promise.resolve(this.index)
.then(JSON.stringify)
.then(compress)
.then(content => fs.writeFile(
path.posix.join(__dirname, 'indexes', `${this.name}.json.br`),
content
// Do not set to 'utf8'
))
}
}