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" ers "code.30cm.net/digimon/library-go/errs" "context" "google.golang.org/protobuf/proto" "github.com/zeromicro/go-zero/core/logx" ) type ListPostsLogic struct { ctx context.Context svcCtx *svc.ServiceContext logx.Logger } func NewListPostsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListPostsLogic { return &ListPostsLogic{ ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx), } } type listReq struct { OnlyAdds int32 `json:"only_adds" validate:"oneof=0 1 2 3"` PageSize int64 `json:"page_size" validate:"required"` PageIndex int64 `json:"page_index" validate:"required"` } // ListPosts 查詢貼文 func (l *ListPostsLogic) ListPosts(in *tweeting.QueryPostsReq) (*tweeting.ListPostsResp, error) { // 驗證資料 if err := l.svcCtx.Validate.ValidateAll(&listReq{ PageSize: int64(in.GetPageSize()), PageIndex: int64(in.GetPageIndex()), OnlyAdds: in.GetOnlyAds(), }); err != nil { return nil, ers.InvalidFormat(err.Error()) } query := &model.QueryPostModelReq{ UID: in.GetUid(), Id: in.GetId(), PageSize: int64(in.GetPageSize()), PageIndex: int64(in.GetPageIndex()), } if in.OnlyAds != nil { switch in.GetOnlyAds() { case domain.AdTypeOnlyAd.ToInt32(): query.OnlyAds = proto.Bool(true) case domain.AdTypeOnlyNotAd.ToInt32(): query.OnlyAds = proto.Bool(false) default: } } find, count, err := l.svcCtx.PostModel.Find(l.ctx, query) if err != nil { e := domain.PostMongoErrorL( logx.WithContext(l.ctx), []logx.LogField{ {Key: "query", Value: query}, {Key: "func", Value: "PostModel.Find"}, {Key: "err", Value: err}, }, "failed to add new post").Wrap(err) return nil, e } result := make([]*tweeting.PostDetailItem, 0, count) for _, item := range find { media := make([]*tweeting.Media, 0, len(item.Media)) for _, subItem := range item.Media { media = append(media, &tweeting.Media{ Type: subItem.Type, Url: subItem.Links, }) } result = append(result, &tweeting.PostDetailItem{ PostId: item.ID.Hex(), Uid: item.UID, Content: item.Content, Tags: item.Tags, Media: media, IsAd: item.IsAd, CreatedAt: item.CreateAt, UpdateAt: item.UpdateAt, LikeCount: int64(item.Like), DislikeCount: int64(item.DisLike), }) } return &tweeting.ListPostsResp{ Posts: result, Page: &tweeting.Pager{ Total: count, Index: int64(in.GetPageIndex()), Size: int64(in.GetPageSize()), }, }, nil }