get.ts 2.5 KB

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