api/src/lib/openapi.ts
31 lines · 1035 bytes
4 symbols in this file
1/**
2 * OpenAPI Hono factory used by every public route module
3 * Also wires a shared zod validation hook, for 400 responses
4 */
5
6import { OpenAPIHono } from '@hono/zod-openapi'
7import type { Context } from 'hono'
8import { envelope } from '@/lib/errors'
9import type { HonoEnv } from '@/types'
10
11interface ZodIssue {
12 path: (string | number)[]
13 message: string
14}
15interface ZodLike {
16 issues?: ZodIssue[]
17}
18
19// Translate zod validation failures into the shared error envelope
20const defaultHook = (result: { success: boolean; error?: unknown }, c: Context) => {
21 if (result.success) return
22 const issues = (result.error as ZodLike).issues ?? []
23 const message = issues.length
24 ? issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`).join('; ')
25 : 'Invalid input'
26 return c.json(envelope('BAD_REQUEST', message, 400), 400)
27}
28
29// Build a fresh OpenAPIHono, optionally with extra Hono options like strict
30export const newApp = (opts: { strict?: boolean } = {}) =>
31 new OpenAPIHono<HonoEnv>({ defaultHook, ...opts })