使用 Hono 创建后端端点——KISS 的 HTTP 层。
// app/routes/api/posts.ts
import { Hono } from 'hono'
const app = new Hono()
app.get('/', (c) => {
return c.json([
{ id: 1, title: 'Hello KISS' }
])
})
app.post('/', async (c) => {
const body = await c.req.json()
return c.json({ id: 2, ...body }, 201)
})
export default app// app/routes/api/posts.ts
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'
const app = new Hono()
const schema = z.object({
title: z.string().min(1),
body: z.string(),
})
app.post('/', zValidator('json', schema), (c) => {
const data = c.req.valid('json')
return c.json({ id: 1, ...data }, 201)
})
export default app使用 @kissjs/rpc 实现端到端类型安全:
// 服务端:导出类型
export type AppType = typeof app
// 客户端:在 Island 中
import { RpcController } from '@kissjs/rpc'
import { hc } from 'hono/client'
import type { AppType } from '../routes/api/posts'
class MyIsland extends LitElement {
private rpc = new RpcController(this)
private client = hc<AppType>('/')
async loadPosts() {
const res = await this.rpc.call(() =>
this.client.api.posts.$get()
)
}
}