add backend data-query
This commit is contained in:
1 parent
186b2661e8
commit
abcfddfab8
3 files changed
+46
No files matched your search
@@ -2,9 +2,14 @@ import fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
import { Router } from 'express'
|
||||
import bodyParser from 'body-parser'
|
||||
import QSearch from '@patarapolw/qsearch'
|
||||
|
||||
import MakeHtml from '../utils/make-html'
|
||||
import { db } from '../global'
|
||||
|
||||
const dataRouter = Router()
|
||||
dataRouter.use(bodyParser.json())
|
||||
|
||||
dataRouter.get('/*', (req, res) => {
|
||||
const p = path.join('../../data', `${req.params[0]}.md`)
|
||||
@@ -19,4 +24,39 @@ dataRouter.get('/*', (req, res) => {
|
||||
}
|
||||
})
|
||||
|
||||
dataRouter.post('/', async (req, res, next) => {
|
||||
try {
|
||||
const { q, project, offset, limit } = req.body
|
||||
let cond = q
|
||||
if (typeof q === 'string') {
|
||||
const parser = new QSearch({
|
||||
dialect: 'nedb',
|
||||
schema: {
|
||||
filename: {},
|
||||
excerpt: {},
|
||||
date: { type: 'date' }
|
||||
}
|
||||
})
|
||||
cond = parser.parse(q)
|
||||
}
|
||||
|
||||
const count = await db.count(cond)
|
||||
|
||||
let c = db.find(cond).skip(offset || 0)
|
||||
if (project) {
|
||||
c = c.projection(project)
|
||||
}
|
||||
if (limit !== null) {
|
||||
c = c.limit(limit || 5)
|
||||
}
|
||||
|
||||
res.json({
|
||||
data: await c,
|
||||
count
|
||||
})
|
||||
} catch (e) {
|
||||
next(e)
|
||||
}
|
||||
})
|
||||
|
||||
export default dataRouter
|
||||
@@ -6,6 +6,9 @@ const apiRouter = Router()
|
||||
apiRouter.use(cors())
|
||||
|
||||
apiRouter.get('/', (req, res) => res.sendStatus(200))
|
||||
apiRouter.get('/api/favicon.ico', (req, res) => {
|
||||
res.sendFile('../../data/favicon.ico')
|
||||
})
|
||||
|
||||
apiRouter.use('/data', dataRouter)
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
import DataStore from 'nedb-promises'
|
||||
|
||||
export const db = new DataStore('assets/data.nedb')
|
||||
Reference in new issue
Block a user