From abcfddfab844f338d71825cf0fbeaa31312d774b Mon Sep 17 00:00:00 2001 From: Pacharapol Withayasakpunt Date: Thu, 27 Feb 2020 16:55:49 +0700 Subject: [PATCH] add backend data-query --- web/backend/src/api/data.ts | 40 ++++++++++++++++++++++++++++++++++++ web/backend/src/api/index.ts | 3 +++ web/backend/src/global.ts | 3 +++ 3 files changed, 46 insertions(+) create mode 100644 web/backend/src/global.ts diff --git a/web/backend/src/api/data.ts b/web/backend/src/api/data.ts index 9d4dc79..8045499 100644 --- a/web/backend/src/api/data.ts +++ b/web/backend/src/api/data.ts @@ -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 diff --git a/web/backend/src/api/index.ts b/web/backend/src/api/index.ts index e067cc2..eebd8af 100644 --- a/web/backend/src/api/index.ts +++ b/web/backend/src/api/index.ts @@ -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) diff --git a/web/backend/src/global.ts b/web/backend/src/global.ts new file mode 100644 index 0000000..8fc3702 --- /dev/null +++ b/web/backend/src/global.ts @@ -0,0 +1,3 @@ +import DataStore from 'nedb-promises' + +export const db = new DataStore('assets/data.nedb')