59 lines
971 B
TypeScript
59 lines
971 B
TypeScript
import express from 'express'
|
|
import * as z from 'zod'
|
|
|
|
import { Database } from './db'
|
|
|
|
const app = express()
|
|
const db = new Database({ readonly: true })
|
|
|
|
app.get('/', (req, res) => {
|
|
const { id } = z
|
|
.object({
|
|
id: z.string(),
|
|
})
|
|
.parse(req.query)
|
|
|
|
const r = db.get(id)
|
|
if (!r) {
|
|
res.sendStatus(404)
|
|
return
|
|
}
|
|
|
|
res.json(r)
|
|
})
|
|
|
|
app.get('/q', (req, res) => {
|
|
const { q, tag, page: _page = '1' } = z
|
|
.object({
|
|
q: z.string().optional(),
|
|
tag: z.string().optional(),
|
|
page: z
|
|
.string()
|
|
.refine((s) => /^\d+$/.test(s))
|
|
.optional(),
|
|
})
|
|
.parse(req.query)
|
|
|
|
const perPage = 5
|
|
const offset = (parseInt(_page) - 1) * perPage
|
|
|
|
if (q) {
|
|
res.json(
|
|
db.q(`${q} ${tag ? `tag:${tag}` : ''}`, {
|
|
offset,
|
|
limit: perPage,
|
|
})
|
|
)
|
|
return
|
|
}
|
|
|
|
res.json(
|
|
db.by(tag ? `tag:${tag}` : '', {
|
|
offset,
|
|
limit: perPage,
|
|
})
|
|
)
|
|
})
|
|
|
|
export default app
|