import { createRoute, OpenAPIHono } from '@hono/zod-openapi'; import { UserService } from '../../modules/users/user.service'; import { z } from 'zod'; import { authMiddleware } from '../../middleware/auth.middleware'; import { ErrorSchema } from '../../utils/errorHandler'; import { AppDataSource } from '../../data-source'; import { AuthContext } from '../../types/context'; const userService = new UserService(AppDataSource); const UserSchema = z.object({ id: z.number().openapi({ example: 1 }), username: z.string().openapi({ example: 'john_doe' }), email: z.string().email().openapi({ example: 'john@example.com' }), createdAt: z.string().datetime().openapi({ example: '2025-05-28T00:00:00Z' }) }); const GetUserRoute = createRoute({ method: 'get', path: '/{id}', middleware: authMiddleware, request: { params: z.object({ id: z.string().openapi({ param: { name: 'id', in: 'path' }, example: '1', description: '用户ID' }) }) }, responses: { 200: { description: '获取用户成功', content: { 'application/json': { schema: UserSchema } } }, 404: { description: '用户不存在', content: { 'application/json': { schema: ErrorSchema } } }, 500: { description: '服务器错误', content: { 'application/json': { schema: ErrorSchema } } } } }); const app = new OpenAPIHono().openapi(GetUserRoute, async (c) => { try { const { id } = c.req.valid('param'); const user = await userService.getUserById(parseInt(id)); if (!user) { return c.json({ code: 404, message: '用户不存在' }, 404); } return c.json({ id: user.id, username: user.username, email: user.email, createdAt: user.createdAt.toISOString() }, 200); } catch (error) { return c.json({ code: 500, message: '服务器错误' }, 500); } }); export default app;