Files
zhdiary/packages/next/server/index.ts
T
2020-12-17 23:44:06 +07:00

44 lines
717 B
TypeScript

import { dbPost, idx, initDatabase, initLunr } from './db'
export async function doSearch ({
q,
tag,
page = 1
}: {
q?: string
tag?: string
page?: number
}) {
await initDatabase()
await initLunr()
const perPage = 5
const offset = (page - 1) * perPage
let cond = dbPost.chain().find({
date: { $exists: true } as any
})
if (q) {
cond = cond.find({
path: { $in: idx.search(q).map(({ ref }) => ref) }
})
}
if (tag) {
cond = cond.find({
tag: { $contains: tag }
})
}
cond = cond.simplesort('date', { desc: true })
const count = cond.branch().count()
const result = cond.offset(offset).limit(perPage).data()
return {
count,
result
}
}