package commentservicelogic import ( "app-cloudep-tweeting-service/internal/domain" model "app-cloudep-tweeting-service/internal/model/mongo" "context" ers "code.30cm.net/digimon/library-go/errs" "app-cloudep-tweeting-service/gen_result/pb/tweeting" "app-cloudep-tweeting-service/internal/svc" "github.com/zeromicro/go-zero/core/logx" ) type GetCommentsLogic struct { ctx context.Context svcCtx *svc.ServiceContext logx.Logger } func NewGetCommentsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCommentsLogic { return &GetCommentsLogic{ ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx), } } // 只列出要驗證的資料 type listReq struct { PostID string `json:"post_id" validate:"required"` PageSize int64 `json:"page_size" validate:"required"` PageIndex int64 `json:"page_index" validate:"required"` } // 將單個 Post 轉換為 PostDetailItem func convertToCommentDetailItem(item *model.Comment) *tweeting.CommentDetail { return &tweeting.CommentDetail{ CommentId: item.ID.Hex(), Uid: item.UID, Content: item.Content, CreatedAt: item.CreateAt, LikeCount: item.LikeCount, DislikeCount: item.DisLikeCount, } } // GetComments 查詢評論 // 目前應該是沒有需求是要看 uid 在哪裡留過言,如果未來業務邏輯有再新增 func (l *GetCommentsLogic) GetComments(in *tweeting.GetCommentsReq) (*tweeting.GetCommentsResp, error) { // 將 PageSize 和 PageIndex 提前轉換為 int64 pageSize := int64(in.GetPageSize()) pageIndex := int64(in.GetPageIndex()) // 驗證資料 if err := l.svcCtx.Validate.ValidateAll(&listReq{ PageSize: pageSize, PageIndex: pageIndex, PostID: in.GetPostId(), }); err != nil { // 錯誤代碼 05-011-00 return nil, ers.InvalidFormat(err.Error()) } // 構建查詢條件 query := &model.QueryCommentModelReq{ PostID: in.GetPostId(), PageSize: pageSize, PageIndex: pageIndex, } // 執行查詢 find, count, err := l.svcCtx.CommentModel.Find(l.ctx, query) if err != nil { e := domain.CommentErrorL( domain.CommentListErrorCode, logx.WithContext(l.ctx), []logx.LogField{ {Key: "query", Value: query}, {Key: "func", Value: "CommentModel.Find"}, {Key: "err", Value: err}, }, "failed to find comment").Wrap(err) return nil, e } // 將查詢結果轉換為 API 回應格式 result := make([]*tweeting.CommentDetail, 0, count) for _, item := range find { result = append(result, convertToCommentDetailItem(item)) } // 返回結果 return &tweeting.GetCommentsResp{ Comments: result, Page: &tweeting.Pager{ Total: count, Index: pageIndex, Size: pageSize, }, }, nil }