package postservicelogic import ( "app-cloudep-tweeting-service/gen_result/pb/tweeting" "app-cloudep-tweeting-service/internal/domain" model "app-cloudep-tweeting-service/internal/model/mongo" "app-cloudep-tweeting-service/internal/svc" "context" ers "code.30cm.net/digimon/library-go/errs" "github.com/zeromicro/go-zero/core/logx" ) type NewPostLogic struct { ctx context.Context svcCtx *svc.ServiceContext logx.Logger } func NewNewPostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NewPostLogic { return &NewPostLogic{ ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx), } } 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 } // NewPost 新增貼文 func (l *NewPostLogic) NewPost(in *tweeting.NewPostReq) (*tweeting.PostResp, error) { // 驗證資料 if err := l.svcCtx.Validate.ValidateAll(&newTweetingReq{ UID: in.GetUid(), Content: in.GetContent(), }); err != nil { 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.Media = media } // ============ insert ============ err := l.svcCtx.PostModel.Insert(l.ctx, tweet) if err != nil { e := domain.PostMongoErrorL( 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 }