| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
- import { UserService } from '../../modules/users/user.service';
- import { z } from '@hono/zod-openapi';
- import { authMiddleware } from '../../middleware/auth.middleware';
- import { ErrorSchema } from '../../utils/errorHandler';
- import { AppDataSource } from '../../data-source';
- import { AuthContext } from '../../types/context';
- import { UserListResponse, UserSchema } from '../../modules/users/user.schema';
- import { parseWithAwait } from '@/server/utils/parseWithAwait';
- 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 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: await parseWithAwait(z.array(UserSchema), 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;
|