get.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 { UserListResponse } from '../../modules/users/user.schema';
  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 listUsersRoute = createRoute({
  25. method: 'get',
  26. path: '/',
  27. middleware: [authMiddleware],
  28. request: {
  29. query: PaginationQuery
  30. },
  31. responses: {
  32. 200: {
  33. description: '成功获取用户列表',
  34. content: {
  35. 'application/json': {
  36. schema: UserListResponse
  37. }
  38. }
  39. },
  40. 400: {
  41. description: '参数错误',
  42. content: {
  43. 'application/json': {
  44. schema: ErrorSchema
  45. }
  46. }
  47. },
  48. 500: {
  49. description: '获取用户列表失败',
  50. content: {
  51. 'application/json': {
  52. schema: ErrorSchema
  53. }
  54. }
  55. }
  56. }
  57. });
  58. const app = new OpenAPIHono<AuthContext>().openapi(listUsersRoute, async (c) => {
  59. try {
  60. const { page, pageSize, keyword } = c.req.valid('query');
  61. const [users, total] = await userService.getUsersWithPagination({
  62. page,
  63. pageSize,
  64. keyword
  65. });
  66. return c.json({
  67. data: users,
  68. pagination: {
  69. total,
  70. current: page,
  71. pageSize
  72. }
  73. }, 200);
  74. } catch (error) {
  75. if (error instanceof z.ZodError) {
  76. return c.json({ code: 400, message: '参数错误' }, 400);
  77. }
  78. return c.json({
  79. code: 500,
  80. message: error instanceof Error ? error.message : '获取用户列表失败'
  81. }, 500);
  82. }
  83. });
  84. export default app;