nicco.io/src/routes/search.json.js

35 lines
860 B
JavaScript
Raw Normal View History

2020-12-06 17:46:18 +01:00
import lunr from 'lunr'
import { getAll } from '../lib/wp'
function removeHTML(s) {
return s.replace(/<.*?>|\s+|&#\d+;/g, ' ').trim()
}
async function convertForIdx(type, fields = []) {
const items = await getAll(type)
2021-01-27 13:01:26 +01:00
const keys = ['title', 'content', 'slug', ...fields]
2020-12-06 17:46:18 +01:00
return items.map((item) => ({
url: `${item.type}/${item.slug}`,
2021-01-27 13:01:26 +01:00
data: keys.map((field) => removeHTML(item[field])).join(' '),
2020-12-06 17:46:18 +01:00
}))
}
export async function get(req, res) {
const all = await Promise.all([
convertForIdx('projects', ['description']),
convertForIdx('pages'),
convertForIdx('posts'),
convertForIdx('works', ['role']),
])
const idx = lunr(function () {
this.ref('url')
this.field('data')
2020-12-09 13:56:58 +01:00
all.flat().forEach((doc) => this.add(doc))
2020-12-06 17:46:18 +01:00
})
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify(idx))
}