api/src/routes/public/search.ts

48 lines · 1138 bytes

3 symbols in this file
 1// Full-text search via MiniSearch
 2import { createRoute, z } from '@hono/zod-openapi'
 3import { search } from '@/lib/search'
 4import { newApp } from '@/lib/openapi'
 5import { ErrorResponse, ListEnvelope, Ok, SearchHitSchema } from '@/schemas'
 6
 7const app = newApp()
 8
 9const querySchema = z.object({
10  q: z.string().min(1),
11  limit: z.coerce.number().int().min(1).max(100).default(20),
12})
13
14const route = createRoute({
15  method: 'get',
16  path: '/search',
17  tags: ['Public'],
18  summary: 'Search',
19  request: { query: querySchema },
20  responses: {
21    200: Ok(ListEnvelope(SearchHitSchema)),
22    400: ErrorResponse,
23  },
24})
25
26app.openapi(route, (c) => {
27  const { q, limit } = c.req.valid('query')
28  const hits = search(q, limit).map((hit) => ({
29    slug: hit.slug,
30    name: hit.name,
31    url: hit.url,
32    description: hit.description,
33    category: hit.category,
34    categorySlug: hit.categorySlug,
35    section: hit.section,
36    sectionSlug: hit.sectionSlug,
37    score: hit.score,
38  }))
39  return c.json(
40    {
41      data: hits,
42      pagination: { page: 1, limit, total: hits.length, hasMore: false },
43    },
44    200,
45  )
46})
47
48export default app