update-me.route.ts 2.2 KB

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