package photo import ( "context" "database/sql" "errors" "time" "photography-backend/internal/model" "photography-backend/internal/svc" "photography-backend/internal/types" "github.com/zeromicro/go-zero/core/logx" ) type UploadPhotoLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } // 上传照片 func NewUploadPhotoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadPhotoLogic { return &UploadPhotoLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *UploadPhotoLogic) UploadPhoto(req *types.UploadPhotoRequest) (resp *types.UploadPhotoResponse, err error) { // 1. 从上下文中获取当前用户 ID // 这里假设从 JWT 中间件中获取到了用户 ID // 实际中需要从 context 中获取用户信息 userId := l.ctx.Value("userId") if userId == nil { return nil, errors.New("未登录或登录已过期") } // 2. 验证分类是否存在 _, err = l.svcCtx.CategoryModel.FindOne(l.ctx, req.CategoryId) if err != nil { return nil, errors.New("分类不存在") } // 3. 创建照片记录 // 注意:这里的文件上传和处理需要在 handler 层处理 // 业务逻辑层只处理数据库操作 photo := &model.Photo{ Title: req.Title, Description: sql.NullString{String: req.Description, Valid: req.Description != ""}, UserId: userId.(int64), CategoryId: req.CategoryId, CreatedAt: time.Now(), UpdatedAt: time.Now(), } _, err = l.svcCtx.PhotoModel.Insert(l.ctx, photo) if err != nil { return nil, err } // 4. 返回上传结果 return &types.UploadPhotoResponse{ BaseResponse: types.BaseResponse{ Code: 200, 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 }