-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.js
67 lines (57 loc) · 1.91 KB
/
template.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
const FlexSearch = require("flexsearch");
// This will be populated with search data by the build script.
const searchData = {};
const flexSearchOptions = {};
const index = FlexSearch.create(flexSearchOptions);
Object.entries(searchData).forEach(([id, item]) => {
index.add(id, item.text);
});
exports.handler = async function ({
queryStringParameters: { limit, term, excerpt },
}) {
const tokenizeStrategy = flexSearchOptions.tokenize || "strict";
const results = index.search(term, limit).map((id) => {
const response = searchData[id].response;
// If the excerpt param is set, find the match and the
// n closest words in both directions.
const excerptNum = parseInt(excerpt);
if (!isNaN(excerptNum)) {
const fullText = searchData[id].text.split(/\s/);
const index = fullText.findIndex((word) => {
const cleanWord = word.replace(/[^A-Za-z0-9\s]/g, "").toLowerCase();
const cleanTerm = term.toLowerCase();
switch (tokenizeStrategy) {
case "forward":
return cleanWord.startsWith(cleanTerm);
case "reverse":
return cleanWord.endsWith(cleanTerm);
case "full":
return cleanWord.includes(cleanTerm);
case "strict":
default:
return cleanWord === cleanTerm;
}
});
if (index > -1) {
const excerptStartIdx = Math.max(index - excerptNum, 0);
const excerptEndIdx = Math.min(
index + excerptNum + 1,
fullText.length - 1
);
response.excerpt = {
text: fullText.slice(excerptStartIdx, excerptEndIdx).join(" "),
matchIndex: index - excerptStartIdx,
moreBefore: index - excerptNum > 0,
moreAfter: index + excerptNum + 1 < fullText.length - 1,
};
}
}
return response;
});
return {
statusCode: 200,
body: JSON.stringify({
results,
}),
};
};