51 lines
977 B
TypeScript
51 lines
977 B
TypeScript
import { Handler } from 'aws-lambda'
|
|
import lunr, { Index } from 'lunr'
|
|
|
|
import idxJson from '../build/idx.json'
|
|
import { dbPost, initDatabase } from '../server/db'
|
|
|
|
let idx: Index
|
|
|
|
export const handler: Handler = async (evt) => {
|
|
const { q = '', tag, page: _page = '1' } = evt.queryStringParameters || {}
|
|
const perPage = 5
|
|
const offset = (parseInt(_page) - 1) * perPage
|
|
|
|
idx = idx || lunr.Index.load(idxJson)
|
|
await initDatabase()
|
|
|
|
let cond = dbPost.chain()
|
|
|
|
if (q) {
|
|
cond = cond.find({
|
|
path: { $in: idx.search(q).map(({ ref }) => ref) },
|
|
})
|
|
}
|
|
|
|
if (tag) {
|
|
cond = cond.find({
|
|
tag: { $contains: tag },
|
|
})
|
|
}
|
|
|
|
const count = cond.branch().count()
|
|
const result = cond
|
|
.offset(offset)
|
|
.limit(5)
|
|
.data()
|
|
.map(({ title, path, date, excerptHtml }) => ({
|
|
title,
|
|
path,
|
|
date,
|
|
excerptHtml,
|
|
}))
|
|
|
|
return {
|
|
statusCode: 200,
|
|
body: JSON.stringify({
|
|
count,
|
|
result,
|
|
}),
|
|
}
|
|
}
|