api/src/routes/public/categories.ts
108 lines · 2642 bytes
1// Category and section lookup routes
2import { createRoute, z } from '@hono/zod-openapi'
3import { categories, findCategory, findSection, slugify } from '@/lib/data'
4import { ApiError } from '@/lib/errors'
5import { newApp } from '@/lib/openapi'
6import {
7 CategorySchema,
8 Envelope,
9 ErrorResponse,
10 ListEnvelope,
11 Ok,
12 SectionSchema,
13} from '@/schemas'
14import type { Category } from '@/types'
15
16const app = newApp()
17
18const sectionSummary = (category: Category) =>
19 (category.sections ?? []).map((section) => ({
20 name: section.name,
21 slug: slugify(section.name),
22 }))
23
24const listCategories = createRoute({
25 method: 'get',
26 path: '/categories',
27 tags: ['Public'],
28 summary: 'List categories',
29 responses: {
30 200: Ok(ListEnvelope(CategorySchema)),
31 },
32})
33
34// Categories with their section names plus slugs, no service payload
35app.openapi(listCategories, (c) => {
36 const data = categories().map((category) => ({
37 name: category.name,
38 slug: slugify(category.name),
39 sections: sectionSummary(category),
40 }))
41 return c.json({
42 data,
43 pagination: { page: 1, limit: data.length, total: data.length, hasMore: false },
44 })
45})
46
47const oneCategory = createRoute({
48 method: 'get',
49 path: '/categories/{slug}',
50 tags: ['Public'],
51 summary: 'Get category',
52 request: { params: z.object({ slug: z.string() }) },
53 responses: {
54 200: Ok(Envelope(CategorySchema)),
55 404: ErrorResponse,
56 },
57})
58
59app.openapi(oneCategory, (c) => {
60 const { slug } = c.req.valid('param')
61 const category = findCategory(slug)
62 if (!category) throw new ApiError('NOT_FOUND', `Category '${slug}' not found`, 404)
63 return c.json(
64 {
65 data: {
66 name: category.name,
67 slug: slugify(category.name),
68 sections: sectionSummary(category),
69 },
70 },
71 200,
72 )
73})
74
75const oneSection = createRoute({
76 method: 'get',
77 path: '/sections/{slug}',
78 tags: ['Public'],
79 summary: 'Get section',
80 request: { params: z.object({ slug: z.string() }) },
81 responses: {
82 200: Ok(Envelope(SectionSchema)),
83 404: ErrorResponse,
84 },
85})
86
87app.openapi(oneSection, (c) => {
88 const { slug } = c.req.valid('param')
89 const hit = findSection(slug)
90 if (!hit) throw new ApiError('NOT_FOUND', `Section '${slug}' not found`, 404)
91 const { section } = hit
92 return c.json(
93 {
94 data: {
95 name: section.name,
96 slug: slugify(section.name),
97 intro: section.intro,
98 furtherInfo: section.furtherInfo,
99 wordOfWarning: section.wordOfWarning,
100 alternativeTo: section.alternativeTo,
101 services: section.services ?? [],
102 },
103 },
104 200,
105 )
106})
107
108export default app