| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi'
- import { ErrorSchema } from '../../../utils/errorHandler'
- import { authMiddleware } from '../../../middleware/auth.middleware'
- import { AuthContext } from '../../../types/context'
- import { UserSchema , UpdateUserDto} from '../../../modules/users/user.schema'
- import { UserService } from '../../../modules/users/user.service'
- import { AppDataSource } from '../../../data-source'
- import { parseWithAwait } from '../../../utils/parseWithAwait'
- // 定义响应schema,排除密码
- const UserResponseSchema = UserSchema.omit({
- password: true
- })
- const routeDef = createRoute({
- method: 'put',
- path: '/me',
- middleware: [authMiddleware],
- request: {
- body: {
- content: {
- 'application/json': {
- schema: UpdateUserDto
- }
- }
- }
- },
- responses: {
- 200: {
- description: '用户信息更新成功',
- content: {
- 'application/json': {
- schema: UserResponseSchema
- }
- }
- },
- 400: {
- description: '请求参数错误',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- },
- 401: {
- description: '未授权',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- },
- 404: {
- description: '用户不存在',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- },
- 500: {
- description: '服务器错误',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- }
- }
- })
- const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
- try {
- const user = c.get('user')
- const updateData = c.req.valid('json')
-
- const userService = new UserService(AppDataSource)
-
- // 更新用户信息
- const updatedUser = await userService.updateUser(user.id, updateData)
-
- if (!updatedUser) {
- return c.json({ code: 404, message: '用户不存在' }, 404)
- }
-
- // 返回更新后的用户信息(不包含密码)
- return c.json(await parseWithAwait(UserResponseSchema, updatedUser), 200)
-
- } catch (error) {
- console.error('更新用户信息失败:', error)
- return c.json({
- code: 500,
- message: error instanceof Error ? error.message : '更新用户信息失败'
- }, 500)
- }
- })
- export default app
|