-
Notifications
You must be signed in to change notification settings - Fork 11
/
gatsby-node.js
95 lines (81 loc) · 2.5 KB
/
gatsby-node.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
95
const _ = require('lodash')
const fs = require('fs')
// set flexsearch object as a global variable to make it available to language files
global.FlexSearch = require('flexsearch')
exports.onPostBootstrap = function(_ref, options) {
const { getNodes } = _ref
const { type } = options
const _options$langua = options.languages
const languages = _options$langua === undefined ? ['en'] : _options$langua
const _options$fields = options.fields
const fields = _options$fields === undefined ? [] : _options$fields
const store = []
const indexStore = []
const fullIndex = {}
languages.forEach(lng => {
// collect fields to store
const fieldsToStore = fields
.filter(field => (field.store ? field.resolver : null))
.map(field => ({ name: field.name, resolver: field.resolver }))
const nid = []
// add each field to index
fields.forEach(index_ => {
const index = {}
index.name = index_.name
if (index_.indexed) {
const attrs = index_.attributes
index.attrs = attrs
// load language files if needed by stemmer or filter
if (
index_.attrs.stemmer !== undefined ||
index_.attrs.filter !== undefined
) {
try {
if (lng === 'en') {
require('./lang/en')
} else if (lng === 'de') {
require('./lang/en')
} else {
console.error(
'Language not supported by pre-defined stemmer or filter'
)
}
} catch (e) {
console.error(e)
}
}
index.values = new FlexSearch(attrs)
}
getNodes()
.filter(node => {
if (node.internal.type === type) {
return node
}
})
.forEach((n, i) => {
const id = i
if (index_.indexed) {
const content = _.get(n, index_.resolver)
index.values.add(id, content)
}
const nodeContent = {}
fieldsToStore.forEach(field => {
nodeContent[field.name] = _.get(n, field.resolver)
})
if (!nid.includes(id)) {
store.push({ id, node: nodeContent })
nid.push(id)
}
})
if (index_.indexed) {
index.values = index.values.export()
indexStore.push(index)
}
})
fullIndex[lng] = {
index: indexStore,
store,
}
})
fs.writeFileSync('public/flexsearch_index.json', JSON.stringify(fullIndex))
}