package postservicelogic import ( "app-cloudep-tweeting-service/internal/domain" model "app-cloudep-tweeting-service/internal/model/mongo" "context" "fmt" "strings" ers "code.30cm.net/digimon/library-go/errs" "code.30cm.net/digimon/library-go/errs/code" "go.mongodb.org/mongo-driver/bson/primitive" "app-cloudep-tweeting-service/gen_result/pb/tweeting" "app-cloudep-tweeting-service/internal/svc" "github.com/zeromicro/go-zero/core/logx" ) type UpdatePostLogic struct { ctx context.Context svcCtx *svc.ServiceContext logx.Logger } func NewUpdatePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePostLogic { return &UpdatePostLogic{ ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx), } } type checkPostId struct { PostID string `validate:"required"` Content string `json:"content,omitempty" validate:"lte=500"` } // UpdatePostError 0502104 資料庫錯誤 func UpdatePostError(s ...string) *ers.LibError { return ers.NewError(code.CloudEPTweeting, code.DBError, domain.UpdatePostError.ToUint32(), fmt.Sprintf("%s", strings.Join(s, " "))) } // UpdatePostErrorL logs error message and returns Error func UpdatePostErrorL(l logx.Logger, filed []logx.LogField, s ...string) *ers.LibError { e := UpdatePostError(s...) l.WithCallerSkip(1).WithFields(filed...).Error(e.Error()) return e } // UpdatePost 更新貼文 func (l *UpdatePostLogic) UpdatePost(in *tweeting.UpdatePostReq) (*tweeting.OKResp, error) { // 驗證資料 if err := l.svcCtx.Validate.ValidateAll(&checkPostId{ PostID: in.GetPostId(), Content: in.GetContent(), }); err != nil { // 錯誤代碼 05-011-00 return nil, ers.InvalidFormat(err.Error()) } // 沒有就沒有,有就走全覆蓋 update := model.Post{} oid, err := primitive.ObjectIDFromHex(in.GetPostId()) if err != nil { // 錯誤代碼 05-011-00 return nil, ers.InvalidFormat("failed to get correct post id") } update.ID = oid update.Tags = in.GetTags() // 將 Media 存入 var media []model.Media for _, item := range in.GetMedia() { media = append(media, model.Media{ Links: item.Url, Type: item.Type, }) } update.MediaURL = media update.Content = in.GetContent() update.Like = uint64(in.GetLikeCount()) update.DisLike = uint64(in.GetDislikeCount()) _, err = l.svcCtx.PostModel.UpdateOptional(l.ctx, &update) if err != nil { e := UpdatePostErrorL( logx.WithContext(l.ctx), []logx.LogField{ {Key: "req", Value: in}, {Key: "func", Value: "PostModel.UpdateOptional"}, {Key: "err", Value: err}, }, "failed to update post", in.PostId).Wrap(err) return nil, e } return &tweeting.OKResp{}, nil }