-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathgatsby-node.js
175 lines (155 loc) · 4.92 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
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
const fs = require("fs").promises
const cheerio = require("cheerio")
const TypesenseClient = require("typesense").Client
const TYPESENSE_ATTRIBUTE_NAME = "data-typesense-field"
let utils = require("./lib/utils")
function typeCastValue(fieldDefinition, attributeValue) {
if (fieldDefinition.type.includes("int")) {
return parseInt(attributeValue);
}
if (fieldDefinition.type.includes("float")) {
return parseFloat(attributeValue);
}
if (fieldDefinition.type.includes("bool")) {
if (attributeValue.toLowerCase() === "false") {
return false;
}
if (attributeValue === "0") {
return false;
}
return attributeValue.trim() !== "";
}
return attributeValue;
}
async function indexContentInTypesense({
fileContents,
wwwPath,
typesense,
newCollectionSchema,
reporter,
}) {
const $ = cheerio.load(fileContents)
let typesenseDocument = {}
$(`[${TYPESENSE_ATTRIBUTE_NAME}]`).each((index, element) => {
const attributeName = $(element).attr(TYPESENSE_ATTRIBUTE_NAME)
const attributeValue = $(element).text()
const fieldDefinition = newCollectionSchema.fields.find(
f => f.name === attributeName
)
if (!fieldDefinition) {
const errorMsg = `[Typesense] Field "${attributeName}" is not defined in the collection schema`
reporter.panic(errorMsg)
return Promise.error(errorMsg)
}
if (fieldDefinition.type.includes("[]")) {
typesenseDocument[attributeName] = typesenseDocument[attributeName] || []
typesenseDocument[attributeName].push(typeCastValue(fieldDefinition, attributeValue))
} else {
typesenseDocument[attributeName] = typeCastValue(fieldDefinition, attributeValue);
}
})
if (utils.isObjectEmpty(typesenseDocument)) {
reporter.warn(
`[Typesense] No HTMLelements had the ${TYPESENSE_ATTRIBUTE_NAME} attribute, skipping page`
)
return Promise.resolve()
}
typesenseDocument["page_path"] = wwwPath
typesenseDocument["page_priority_score"] =
typesenseDocument["page_priority_score"] || 10
try {
reporter.verbose(
`[Typesense] Creating document: ${JSON.stringify(
typesenseDocument,
null,
2
)}`
)
await typesense
.collections(newCollectionSchema.name)
.documents()
.create(typesenseDocument)
reporter.verbose("[Typesense] ✅")
return Promise.resolve()
} catch (error) {
reporter.panic(`[Typesense] Could not create document: ${error}`)
}
}
exports.onPostBuild = async (
{ reporter },
{
server,
collectionSchema,
publicDir,
rootDir,
exclude,
generateNewCollectionName = utils.generateNewCollectionName,
}
) => {
reporter.verbose("[Typesense] Getting list of HTML files")
// backward compatibility
rootDir = rootDir || publicDir
const htmlFiles = await utils.getHTMLFilesRecursively(rootDir, rootDir, exclude)
const typesense = new TypesenseClient(server)
const newCollectionName = generateNewCollectionName(collectionSchema)
const newCollectionSchema = { ...collectionSchema }
newCollectionSchema.name = newCollectionName
try {
reporter.verbose(`[Typesense] Creating collection ${newCollectionName}`)
await typesense.collections().create(newCollectionSchema)
} catch (error) {
reporter.panic(
`[Typesense] Could not create collection ${newCollectionName}: ${error}`
)
}
for (const file of htmlFiles) {
const wwwPath = file.replace(rootDir, "").replace(/index\.html$/, "")
reporter.verbose(`[Typesense] Indexing ${wwwPath}`)
const fileContents = (await fs.readFile(file)).toString()
await indexContentInTypesense({
fileContents,
wwwPath,
typesense,
newCollectionSchema,
reporter,
})
}
let oldCollectionName
try {
oldCollectionName = (
await typesense.aliases(collectionSchema.name).retrieve()
)["collection_name"]
reporter.verbose(`[Typesense] Old collection name was ${oldCollectionName}`)
} catch (error) {
reporter.verbose(`[Typesense] No old collection found, proceeding`)
}
try {
reporter.verbose(
`[Typesense] Upserting alias ${collectionSchema.name} -> ${newCollectionName}`
)
await typesense
.aliases()
.upsert(collectionSchema.name, { collection_name: newCollectionName })
reporter.info(
`[Typesense] Content indexed to "${collectionSchema.name}" [${newCollectionName}]`
)
} catch (error) {
reporter.error(
`[Typesense] Could not upsert alias ${collectionSchema.name} -> ${newCollectionName}: ${error}`
)
}
try {
if (oldCollectionName) {
reporter.verbose(
`[Typesense] Deleting old collection ${oldCollectionName}`
)
await typesense.collections(oldCollectionName).delete()
}
} catch (error) {
reporter.error(
`[Typesense] Could not delete old collection ${oldCollectionName}: ${error}`
)
}
}
exports.onPreInit = ({ reporter }) =>
reporter.verbose("Loaded gatsby-plugin-typesense")