import type { Context } from 'hono'; import { z } from 'zod'; import type { Config } from './config.ts'; import type { DB } from './db.ts'; /** Everything a route needs. Built once in main.ts (or per test). */ export interface AppContext { db: DB; config: Config; log: (level: 'info' | 'warn' | 'error', message: string, extra?: unknown) => void; } export class HttpError extends Error { status: number; code: string; details?: unknown; constructor(status: number, code: string, message: string, details?: unknown) { super(message); this.name = 'HttpError'; this.status = status; this.code = code; this.details = details; } } export const notFound = (what = 'Item') => new HttpError(404, 'not_found', `${what} not found`); export const badRequest = (message: string, details?: unknown) => new HttpError(400, 'bad_request', message, details); export const conflict = (message: string) => new HttpError(409, 'conflict', message); export interface FieldIssue { path: string; message: string; } export function zodIssues(error: z.ZodError): FieldIssue[] { return error.issues.map((i) => ({ path: i.path.join('.'), message: i.message })); } export function parse(schema: S, data: unknown): z.output { const result = schema.safeParse(data); if (!result.success) { const issues = zodIssues(result.error); const first = issues[0]; throw new HttpError(422, 'validation', first ? `${first.path ? `${first.path}: ` : ''}${first.message}` : 'Invalid input', issues); } return result.data; } export async function readBody(c: Context, schema: S): Promise> { let json: unknown; try { json = await c.req.json(); } catch { throw badRequest('Request body must be JSON'); } return parse(schema, json); } export const idParam = (c: Context, name = 'id'): string => { const v = c.req.param(name); if (!v || v.length > 64) throw badRequest('Invalid id'); return v; };