package photo import ( "context" "database/sql" "time" "photography-backend/internal/model" "photography-backend/internal/svc" "photography-backend/internal/types" "photography-backend/pkg/errorx" "github.com/zeromicro/go-zero/core/logx" ) type UpdatePhotoLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } // 更新照片 func NewUpdatePhotoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePhotoLogic { return &UpdatePhotoLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *UpdatePhotoLogic) UpdatePhoto(req *types.UpdatePhotoRequest) (resp *types.UpdatePhotoResponse, err error) { // 1. 获取当前用户ID (从JWT中间件获取) userID := l.ctx.Value("userID") if userID == nil { return nil, errorx.NewWithCode(errorx.AuthError) } currentUserID := userID.(int64) // 2. 查询照片是否存在 photo, err := l.svcCtx.PhotoModel.FindOne(l.ctx, req.Id) if err != nil { if err == model.ErrNotFound { return nil, errorx.NewWithCode(errorx.PhotoNotFound) } logx.Errorf("查询照片失败: %v", err) return nil, errorx.NewWithCode(errorx.ServerError) } // 3. 检查权限 - 只有照片所有者可以更新 if photo.UserId != currentUserID { return nil, errorx.NewWithCode(errorx.Forbidden) } // 4. 验证分类是否存在 (如果要更新分类) if req.CategoryId > 0 { _, err = l.svcCtx.CategoryModel.FindOne(l.ctx, req.CategoryId) if err != nil { if err == model.ErrNotFound { return nil, errorx.NewWithCode(errorx.CategoryNotFound) } logx.Errorf("查询分类失败: %v", err) return nil, errorx.NewWithCode(errorx.ServerError) } } // 5. 更新照片信息 if req.Title != "" { photo.Title = req.Title } if req.Description != "" { photo.Description = sql.NullString{String: req.Description, Valid: true} } if req.CategoryId > 0 { photo.CategoryId = req.CategoryId } photo.UpdatedAt = time.Now() // 6. 保存到数据库 err = l.svcCtx.PhotoModel.Update(l.ctx, photo) if err != nil { logx.Errorf("更新照片失败: %v", err) return nil, errorx.NewWithCode(errorx.ServerError) } // 7. 构造响应 return &types.UpdatePhotoResponse{ BaseResponse: types.BaseResponse{ Code: errorx.Success, Message: "照片更新成功", }, Data: types.Photo{ Id: photo.Id, Title: photo.Title, Description: photo.Description.String, FilePath: photo.FilePath, ThumbnailPath: photo.ThumbnailPath, UserId: photo.UserId, CategoryId: photo.CategoryId, CreatedAt: photo.CreatedAt.Unix(), UpdatedAt: photo.UpdatedAt.Unix(), }, }, nil }