This commit is contained in:
D8D Developer
2025-06-27 03:31:29 +00:00
commit d371fbaefa
68 changed files with 11263 additions and 0 deletions

108
src/server/api/users/get.ts Normal file
View File

@@ -0,0 +1,108 @@
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';
import { UserSchema } from '../../modules/users/user.entity';
const userService = new UserService(AppDataSource);
const PaginationQuery = z.object({
page: z.coerce.number().int().positive().default(1).openapi({
example: 1,
description: '页码从1开始'
}),
pageSize: z.coerce.number().int().positive().default(10).openapi({
example: 10,
description: '每页数量'
}),
keyword: z.string().optional().openapi({
example: 'admin',
description: '搜索关键词(用户名/昵称/手机号)'
})
});
const UserListResponse = z.object({
data: z.array(UserSchema),
pagination: z.object({
total: z.number().openapi({
example: 100,
description: '总记录数'
}),
current: z.number().openapi({
example: 1,
description: '当前页码'
}),
pageSize: z.number().openapi({
example: 10,
description: '每页数量'
})
})
});
const listUsersRoute = createRoute({
method: 'get',
path: '/',
middleware: [authMiddleware],
request: {
query: PaginationQuery
},
responses: {
200: {
description: '成功获取用户列表',
content: {
'application/json': {
schema: UserListResponse
}
}
},
400: {
description: '参数错误',
content: {
'application/json': {
schema: ErrorSchema
}
}
},
500: {
description: '获取用户列表失败',
content: {
'application/json': {
schema: ErrorSchema
}
}
}
}
});
const app = new OpenAPIHono<AuthContext>().openapi(listUsersRoute, async (c) => {
try {
const { page, pageSize, keyword } = c.req.valid('query');
const [users, total] = await userService.getUsersWithPagination({
page,
pageSize,
keyword
});
return c.json({
data: users,
pagination: {
total,
current: page,
pageSize
}
}, 200);
} catch (error) {
if (error instanceof z.ZodError) {
return c.json({ code: 400, message: '参数错误' }, 400);
}
return c.json({
code: 500,
message: error instanceof Error ? error.message : '获取用户列表失败'
}, 500);
}
});
export default app;