Files
webapp-starter/src/server/api/users/get.ts
D8D Developer 71aaeb9424 ci: 添加 Docker 构建和推送工作流
- 新增 Dockerfile 和 .dockerignore 文件
- 添加 Gitea 持续集成工作流,用于构建和推送 Docker 镜像
- 新增 .gitignore 文件,忽略构建和配置文件
- 添加项目结构和规范文档,包括 TypeScript、模块化、API、数据库等规范
- 新增前端和后端的基础代码结构
2025-06-11 09:35:39 +00:00

77 lines
2.0 KiB
TypeScript

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<AuthContext>().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;