get.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { UserService } from '../../modules/users/user.service';
  3. import { z } from '@hono/zod-openapi';
  4. import { authMiddleware } from '../../middleware/auth.middleware';
  5. import { ErrorSchema } from '../../utils/errorHandler';
  6. import { AppDataSource } from '../../data-source';
  7. import { AuthContext } from '../../types/context';
  8. import { UserSchema } from '../../modules/users/user.entity';
  9. const userService = new UserService(AppDataSource);
  10. const PaginationQuery = z.object({
  11. page: z.coerce.number().int().positive().default(1).openapi({
  12. example: 1,
  13. description: '页码,从1开始'
  14. }),
  15. pageSize: z.coerce.number().int().positive().default(10).openapi({
  16. example: 10,
  17. description: '每页数量'
  18. }),
  19. keyword: z.string().optional().openapi({
  20. example: 'admin',
  21. description: '搜索关键词(用户名/昵称/手机号)'
  22. })
  23. });
  24. const UserListResponse = z.object({
  25. data: z.array(UserSchema),
  26. pagination: z.object({
  27. total: z.number().openapi({
  28. example: 100,
  29. description: '总记录数'
  30. }),
  31. current: z.number().openapi({
  32. example: 1,
  33. description: '当前页码'
  34. }),
  35. pageSize: z.number().openapi({
  36. example: 10,
  37. description: '每页数量'
  38. })
  39. })
  40. });
  41. const listUsersRoute = createRoute({
  42. method: 'get',
  43. path: '/',
  44. middleware: [authMiddleware],
  45. request: {
  46. query: PaginationQuery
  47. },
  48. responses: {
  49. 200: {
  50. description: '成功获取用户列表',
  51. content: {
  52. 'application/json': {
  53. schema: UserListResponse
  54. }
  55. }
  56. },
  57. 400: {
  58. description: '参数错误',
  59. content: {
  60. 'application/json': {
  61. schema: ErrorSchema
  62. }
  63. }
  64. },
  65. 500: {
  66. description: '获取用户列表失败',
  67. content: {
  68. 'application/json': {
  69. schema: ErrorSchema
  70. }
  71. }
  72. }
  73. }
  74. });
  75. const app = new OpenAPIHono<AuthContext>().openapi(listUsersRoute, async (c) => {
  76. try {
  77. const { page, pageSize, keyword } = c.req.valid('query');
  78. const [users, total] = await userService.getUsersWithPagination({
  79. page,
  80. pageSize,
  81. keyword
  82. });
  83. return c.json({
  84. data: users,
  85. pagination: {
  86. total,
  87. current: page,
  88. pageSize
  89. }
  90. }, 200);
  91. } catch (error) {
  92. if (error instanceof z.ZodError) {
  93. return c.json({ code: 400, message: '参数错误' }, 400);
  94. }
  95. return c.json({
  96. code: 500,
  97. message: error instanceof Error ? error.message : '获取用户列表失败'
  98. }, 500);
  99. }
  100. });
  101. export default app;