/
comment.go
87 lines (76 loc) · 1.95 KB
/
comment.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package data
import (
"context"
"encoding/json"
"github.com/go-kratos/kratos/v2/log"
"github.com/segmentio/kafka-go"
"github.com/yogerhub/kratos-news-system/app/news/service/internal/biz"
"gorm.io/gorm"
)
type Comment struct {
gorm.Model
UserId int64 `json:"user_id"`
ArticleId int64 `json:"article_id"`
Content string `json:"content"`
}
type commentRepo struct {
data *Data
log *log.Helper
}
// NewCommentRepo .
func NewCommentRepo(data *Data, logger log.Logger) biz.CommentRepo {
return &commentRepo{
data: data,
log: log.NewHelper(logger),
}
}
func (r *commentRepo) AddComment(ctx context.Context, comment *biz.Comment) (*biz.Comment, error) {
co := Comment{
UserId: comment.UserId,
ArticleId: comment.ArticleId,
Content: comment.Content,
}
result := r.data.db.Create(&co) // 通过数据的指针来创建
if result.Error != nil {
return nil, result.Error
}
commentJson, err := json.Marshal(co)
if err != nil {
log.Error("Marshal error", commentJson, err)
}
r.data.kp.WriteMessages(ctx, kafka.Message{
Key: []byte("kratos"),
Value: commentJson,
})
return &biz.Comment{
ID: int64(co.ID),
UserId: co.UserId,
ArticleId: co.ArticleId,
Content: co.Content,
CreatedAt: co.CreatedAt,
}, nil
}
// GetComments 获取评论列表
func (r *commentRepo) GetComments(ctx context.Context, articleId int64) ([]*biz.Comment, error) {
var comments []Comment
result := r.data.db.Where("article_id = ?", articleId).Find(&comments)
if result.Error != nil {
return nil, result.Error
}
log.Info("comment list:", comments, result)
rs := make([]*biz.Comment, len(comments))
for i, x := range comments {
rs[i] = &biz.Comment{
ID: int64(x.ID),
UserId: x.UserId,
ArticleId: x.ArticleId,
Content: x.Content,
CreatedAt: x.CreatedAt,
}
}
return rs, nil
}
func (r *commentRepo) DeleteComment(ctx context.Context, id int64) error {
rv := r.data.db.Delete(&Comment{}, id)
return rv.Error
}