put.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi'
  2. import { ErrorSchema } from '../../../utils/errorHandler'
  3. import { authMiddleware } from '../../../middleware/auth.middleware'
  4. import { AuthContext } from '../../../types/context'
  5. import { UserSchema , UpdateUserDto} from '../../../modules/users/user.schema'
  6. import { UserService } from '../../../modules/users/user.service'
  7. import { AppDataSource } from '../../../data-source'
  8. import { parseWithAwait } from '../../../utils/parseWithAwait'
  9. // 定义响应schema,排除密码
  10. const UserResponseSchema = UserSchema.omit({
  11. password: true
  12. })
  13. const routeDef = createRoute({
  14. method: 'put',
  15. path: '/me',
  16. middleware: [authMiddleware],
  17. request: {
  18. body: {
  19. content: {
  20. 'application/json': {
  21. schema: UpdateUserDto
  22. }
  23. }
  24. }
  25. },
  26. responses: {
  27. 200: {
  28. description: '用户信息更新成功',
  29. content: {
  30. 'application/json': {
  31. schema: UserResponseSchema
  32. }
  33. }
  34. },
  35. 400: {
  36. description: '请求参数错误',
  37. content: {
  38. 'application/json': {
  39. schema: ErrorSchema
  40. }
  41. }
  42. },
  43. 401: {
  44. description: '未授权',
  45. content: {
  46. 'application/json': {
  47. schema: ErrorSchema
  48. }
  49. }
  50. },
  51. 404: {
  52. description: '用户不存在',
  53. content: {
  54. 'application/json': {
  55. schema: ErrorSchema
  56. }
  57. }
  58. },
  59. 500: {
  60. description: '服务器错误',
  61. content: {
  62. 'application/json': {
  63. schema: ErrorSchema
  64. }
  65. }
  66. }
  67. }
  68. })
  69. const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  70. try {
  71. const user = c.get('user')
  72. const updateData = c.req.valid('json')
  73. const userService = new UserService(AppDataSource)
  74. // 更新用户信息
  75. const updatedUser = await userService.updateUser(user.id, updateData)
  76. if (!updatedUser) {
  77. return c.json({ code: 404, message: '用户不存在' }, 404)
  78. }
  79. // 返回更新后的用户信息(不包含密码)
  80. return c.json(await parseWithAwait(UserResponseSchema, updatedUser), 200)
  81. } catch (error) {
  82. console.error('更新用户信息失败:', error)
  83. return c.json({
  84. code: 500,
  85. message: error instanceof Error ? error.message : '更新用户信息失败'
  86. }, 500)
  87. }
  88. })
  89. export default app