Hono 路由、类型安全 RPC、验证和错误响应模式。
| 文件 | 路由 | 说明 |
|---|---|---|
| api/posts.ts | /api/posts | Posts API(Hono 子应用) |
| api/posts/[id].ts | /api/posts/:id | 单个 post API |
| api/users/index.ts | /api/users | 用户列表 API |
KISS 利用 Hono RPC 实现端到端类型安全。无需代码生成:
// 服务端:app/routes/api/posts.ts
import { Hono } from 'hono'
const app = new Hono()
.get('/', (c) => c.json([{ id: 1, title: 'Hello' }]))
.post('/', async (c) => {
const body = await c.req.json()
return c.json({ ok: true }, 201)
})
export default app
export type AppType = typeof app// 客户端:app/islands/post-list.ts
import { hc } from 'hono/client'
import type { AppType } from '../routes/api/posts.ts'
const client = hc<AppType>('/api/posts')
const res = await client.index.$get()
const posts = await res.json() // 完全类型化!Zod 和 @hono/zod-validator 不是框架依赖——它们是你的项目级选择:
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'
const schema = z.object({ title: z.string(), body: z.string() })
app.post('/', zValidator('json', schema), async (c) => {
const data = c.req.valid('json') // 有类型!
return c.json({ ok: true, data }, 201)
})所有 KISS 错误产生一致的 JSON 响应:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Title is required",
"status": 400
}
}