mirror of
https://github.com/tcsenpai/obsidiangarden_netlify.git
synced 2025-06-03 19:40:03 +00:00

Context: having search is almots essential feature for most of the websites. This commit adds very basic functionality based on lunrjs library. It allows to build an use search index. Changes: - Build search index using 11ty template - Adds postbuild step to build lunr index - Adds netlify function to serve as API for search - Adds search page and links to notes pages - Wraps hashtags with proper styling and adds search by hashtag link to them - Adds missing obsidian class for content
46 lines
1.1 KiB
JavaScript
46 lines
1.1 KiB
JavaScript
const lunrjs = require('lunr');
|
|
|
|
const handler = async (event) => {
|
|
try {
|
|
|
|
|
|
const search = event.queryStringParameters.term;
|
|
if(!search) throw('Missing term query parameter');
|
|
|
|
const data = require('./data.json');
|
|
const indexJson = require('./index.json');
|
|
const index = lunrjs.Index.load(indexJson);
|
|
console.log('index made');
|
|
|
|
let results = index.search(search);
|
|
|
|
results.forEach(r => {
|
|
r.title = data[r.ref].title;
|
|
r.content = truncate(data[r.ref].content, 400);
|
|
r.date = data[r.ref].date;
|
|
r.url = data[r.ref].url;
|
|
|
|
delete r.ref;
|
|
});
|
|
|
|
return {
|
|
statusCode: 200,
|
|
body: JSON.stringify(results),
|
|
// // more keys you can return:
|
|
// headers: { "headerName": "headerValue", ... },
|
|
// isBase64Encoded: true,
|
|
}
|
|
} catch (error) {
|
|
return { statusCode: 500, body: error.toString() }
|
|
}
|
|
}
|
|
|
|
function truncate(str, size) {
|
|
//first, remove HTML
|
|
str = str.replace(/<.*?>/g, '');
|
|
if(str.length < size) return str;
|
|
return str.substring(0, size-3) + '...';
|
|
}
|
|
|
|
module.exports = { handler }
|