hono
在使用 hono 时,入参需要正常注册到 c.req.valid 中,建议使用官方推荐的类型方案。
请参考用例:
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { serve } from '@hono/node-server'
import type { z } from 'zod'
import type {
userSchema,
} from './hono.pub'
import {
UserRole,
createUserSchema,
getUsersQuerySchema,
updateUserSchema,
} from './hono.pub'
const app = new Hono()
// 模拟数据库
const users: z.infer<typeof userSchema>[] = []
app
.get('/users', zValidator('query', getUsersQuerySchema), (c) => {
const { limit, offset, role } = c.req.valid('query')
let filteredUsers = users
if (role) {
filteredUsers = filteredUsers.filter(user => user.role === role)
}
const paginatedUsers = filteredUsers.slice(offset || 0, limit)
/**
* @define GetUsersResponse
*/
return c.json({
success: true,
data: paginatedUsers,
total: filteredUsers.length,
})
})
.get('/users/:id', (c) => {
const id = c.req.param('id')
const user = users.find(u => u.id === id)
if (!user) {
/**
* @ignore
*/
return c.json({ success: false, message: 'User not found' }, 404)
}
/**
* @define GetUserResponse
*/
return c.json({ success: true, data: user })
})
.post('/users', zValidator('json', createUserSchema), (c) => {
const newUser = c.req.valid('json')
const id = Date.now().toString()
const user = { id, ...newUser }
// 确保新用户的角色是有效的 UserRole
if (!Object.values(UserRole).includes(user.role)) {
/**
* @ignore
*/
return c.json({ success: false, message: 'Invalid user role' }, 400)
}
users.push(user)
/**
* @define CreateUserResponse
*/
return c.json({ success: true, data: user }, 201)
})
.put('/users/:id', zValidator('json', updateUserSchema), (c) => {
const id = c.req.param('id')
const updateData = c.req.valid('json')
const userIndex = users.findIndex(u => u.id === id)
if (userIndex === -1) {
/**
* @ignore
*/
return c.json({ success: false, message: 'User not found' }, 404)
}
// 如果更新包括角色,确保它是有效的 UserRole
if (updateData.role && !Object.values(UserRole).includes(updateData.role)) {
/**
* @ignore
*/
return c.json({ success: false, message: 'Invalid user role' }, 400)
}
users[userIndex] = { ...users[userIndex], ...updateData }
/**
* @define UpdateUserResponse
*/
return c.json({ success: true, data: users[userIndex] })
})
.delete('/users/:id', (c) => {
const id = c.req.param('id')
const userIndex = users.findIndex(u => u.id === id)
if (userIndex === -1) {
/**
* @ignore
*/
return c.json({ success: false, message: 'User not found' }, 404)
}
const deletedUser = users.splice(userIndex, 1)[0]
/**
* @define DeleteUserResponse
*/
return c.json({ success: true, data: deletedUser })
})
serve(app)