get.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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, UserSchema } 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. } catch (error) {
  76. if (error instanceof z.ZodError) {
  77. return c.json({ code: 400, message: '参数错误' }, 400);
  78. }
  79. return c.json({
  80. code: 500,
  81. message: error instanceof Error ? error.message : '获取用户列表失败'
  82. }, 500);
  83. }
  84. });
  85. export default app;