package postservicelogic import ( "app-cloudep-tweeting-service/internal/domain" model "app-cloudep-tweeting-service/internal/model/mongo" "code.30cm.net/digimon/library-go/errs/code" "context" "fmt" "strings" "app-cloudep-tweeting-service/gen_result/pb/tweeting" "app-cloudep-tweeting-service/internal/svc" ers "code.30cm.net/digimon/library-go/errs" "github.com/zeromicro/go-zero/core/logx" ) type CreatePostLogic struct { ctx context.Context svcCtx *svc.ServiceContext logx.Logger } func NewCreatePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePostLogic { return &CreatePostLogic{ ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx), } } // TODO 要調查一下內容如果存 html 是否有需要Encode // 輸入的定義 -> 檢查用 type newTweetingReq struct { UID string `json:"uid" validate:"required"` Content string `json:"content" validate:"required,lte=500"` // 貼文限制 500 字內 Tags []string `json:"tags"` MediaUrl []string `json:"media_url"` IsAd bool `json:"is_ad"` // default false } // 定義 Error // CreatePostError 0502102 資料庫錯誤 func CreatePostError(s ...string) *ers.LibError { return ers.NewError(code.CloudEPTweeting, code.DBError, domain.CreatePostError.ToUint32(), fmt.Sprintf("%s", strings.Join(s, " "))) } // CreatePostErrorL logs error message and returns Error func CreatePostErrorL(l logx.Logger, filed []logx.LogField, s ...string) *ers.LibError { e := CreatePostError(s...) l.WithCallerSkip(1).WithFields(filed...).Error(e.Error()) return e } // CreatePost 新增貼文 func (l *CreatePostLogic) CreatePost(in *tweeting.NewPostReq) (*tweeting.PostResp, error) { // 驗證資料 if err := l.svcCtx.Validate.ValidateAll(&newTweetingReq{ UID: in.GetUid(), Content: in.GetContent(), }); err != nil { // 錯誤代碼 05-011-00 return nil, ers.InvalidFormat(err.Error()) } // ============ prepare ============ // 新增資料 tweet := &model.Post{ UID: in.GetUid(), Content: in.GetContent(), Status: domain.TweetingStatusNotReviewedYet.ToInt8(), IsAd: in.IsAd, } if len(in.GetTags()) > 0 { // 存在貼文內的不提供搜尋,純顯示用,只不過在原始的tag 發生變動的時候,並不會一起改變 // 搜尋會貼文與Tag 的表會再另外一邊做關聯 // 暫時業務邏輯上tag 只提供新增,不提供修改以及刪除,故目前版本可行 tweet.Tags = in.GetTags() } if len(in.Media) > 0 { // 將 Media 存入 var media []model.Media for _, item := range in.GetMedia() { media = append(media, model.Media{ Links: item.Url, Type: item.Type, }) } tweet.MediaURL = media } // ============ insert ============ err := l.svcCtx.PostModel.Insert(l.ctx, tweet) if err != nil { e := CreatePostErrorL( logx.WithContext(l.ctx), []logx.LogField{ {Key: "req", Value: in}, {Key: "func", Value: "PostModel.Insert"}, {Key: "err", Value: err}, }, "failed to add new post").Wrap(err) return nil, e } return &tweeting.PostResp{ PostId: tweet.ID.Hex(), }, nil }