app-cloudep-tweeting-service/internal/logic/commentservice/new_comment_logic.go

96 lines
2.4 KiB
Go
Raw Normal View History

2024-08-30 06:30:39 +00:00
package commentservicelogic
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"
"errors"
"github.com/zeromicro/go-zero/core/logx"
)
type NewCommentLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewNewCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NewCommentLogic {
return &NewCommentLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// 輸入的定義 -> 檢查用
type newCommentReq struct {
UID string `json:"uid" validate:"required"`
Content string `json:"content" validate:"required,lte=500"` // 貼文限制 500 字內
PostID string `json:"post_id" validate:"required"`
}
// NewComment 發表評論
func (l *NewCommentLogic) NewComment(in *tweeting.CommentPostReq) (*tweeting.CommentPostResp, error) {
// 驗證資料
if err := l.svcCtx.Validate.ValidateAll(&newCommentReq{
UID: in.GetUid(),
Content: in.GetContent(),
PostID: in.GetPostId(),
}); err != nil {
// 錯誤代碼 05-011-00
return nil, ers.InvalidFormat(err.Error())
}
// 檢查是否有這個文章
_, err := l.svcCtx.PostModel.FindOne(l.ctx, in.GetPostId())
if err != nil {
if errors.Is(model.ErrNotFound, err) {
// 錯誤代碼 05-031-00
return nil, ers.ResourceNotFound("failed to find post: ", in.GetPostId())
}
// 錯誤代碼 05-021-10
e := domain.CommentErrorL(
domain.CommentFoundErrorCode,
logx.WithContext(l.ctx),
[]logx.LogField{
{Key: "req", Value: in},
{Key: "func", Value: "PostModel.FindOne"},
{Key: "err", Value: err},
},
"failed to find post:", in.GetPostId()).Wrap(err)
return nil, e
}
data := &model.Comment{
PostID: in.GetPostId(),
UID: in.GetUid(),
Content: in.GetContent(),
LikeCount: 0,
DisLikeCount: 0,
}
err = l.svcCtx.CommentModel.Insert(l.ctx, data)
if err != nil {
// 錯誤代碼 05-021-11
e := domain.CommentErrorL(
domain.CommentInsertErrorCode,
logx.WithContext(l.ctx),
[]logx.LogField{
{Key: "req", Value: in},
{Key: "func", Value: "CommentModel.Insert"},
{Key: "err", Value: err},
},
"failed to insert comment:", in.GetPostId()).Wrap(err)
return nil, e
}
return &tweeting.CommentPostResp{
CommentId: data.ID.Hex(),
}, nil
}