app-cloudep-tweeting-service/internal/logic/postservice/create_post_logic.go

96 lines
2.6 KiB
Go
Raw Normal View History

package postservicelogic
import (
"app-cloudep-tweeting-service/internal/domain"
model "app-cloudep-tweeting-service/internal/model/mongo"
"app-cloudep-tweeting-service/gen_result/pb/tweeting"
"app-cloudep-tweeting-service/internal/svc"
"context"
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"`
2024-09-03 09:47:34 +00:00
MediaURL []string `json:"media_url"`
IsAd bool `json:"is_ad"` // default false
}
// 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 {
// 錯誤代碼 05-021-02
e := domain.CommentErrorL(
domain.CreatePostError,
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)
2024-09-03 09:47:34 +00:00
return nil, e
}
return &tweeting.PostResp{
PostId: tweet.ID.Hex(),
}, nil
}