feat: community RPC 从内存存储迁移到 ent 数据库
This commit is contained in:
@@ -4,8 +4,11 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"juwan-backend/app/community/rpc/internal/models/postlikes"
|
||||
"juwan-backend/app/community/rpc/internal/models/posts"
|
||||
"juwan-backend/app/community/rpc/internal/svc"
|
||||
"juwan-backend/app/community/rpc/pb"
|
||||
"juwan-backend/app/snowflake/rpc/snowflake"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
@@ -26,31 +29,43 @@ func NewAddPostLikesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddP
|
||||
|
||||
// -----------------------postLikes-----------------------
|
||||
func (l *AddPostLikesLogic) AddPostLikes(in *pb.AddPostLikesReq) (*pb.AddPostLikesResp, error) {
|
||||
// todo: add your logic here and delete this line
|
||||
if in.GetPostId() <= 0 || in.GetUserId() <= 0 {
|
||||
return nil, errors.New("postId and userId are required")
|
||||
}
|
||||
|
||||
store := l.svcCtx.Store
|
||||
store.Mu.Lock()
|
||||
defer store.Mu.Unlock()
|
||||
|
||||
post, ok := store.Posts[in.GetPostId()]
|
||||
if !ok || post.GetDeletedAt() > 0 {
|
||||
exists, err := l.svcCtx.CommunityModelRO.Posts.Query().
|
||||
Where(posts.IDEQ(in.GetPostId()), posts.DeletedAtIsNil()).
|
||||
Exist(l.ctx)
|
||||
if err != nil || !exists {
|
||||
return nil, errors.New("post not found")
|
||||
}
|
||||
|
||||
key := postLikeKey(in.GetPostId(), in.GetUserId())
|
||||
if _, exists := store.PostLikes[key]; exists {
|
||||
dup, _ := l.svcCtx.CommunityModelRO.PostLikes.Query().
|
||||
Where(postlikes.PostIDEQ(in.GetPostId()), postlikes.UserIDEQ(in.GetUserId())).
|
||||
Exist(l.ctx)
|
||||
if dup {
|
||||
return &pb.AddPostLikesResp{}, nil
|
||||
}
|
||||
|
||||
store.PostLikes[key] = &pb.PostLikes{
|
||||
PostId: in.GetPostId(),
|
||||
UserId: in.GetUserId(),
|
||||
CreatedAt: nowUnix(in.GetCreatedAt()),
|
||||
idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{})
|
||||
if err != nil {
|
||||
return nil, errors.New("create post like id failed")
|
||||
}
|
||||
post.LikeCount++
|
||||
|
||||
_, err = l.svcCtx.CommunityModelRW.PostLikes.Create().
|
||||
SetID(idResp.Id).
|
||||
SetPostID(in.GetPostId()).
|
||||
SetUserID(in.GetUserId()).
|
||||
Save(l.ctx)
|
||||
if err != nil {
|
||||
logx.Errorf("addPostLikes err: %v", err)
|
||||
return nil, errors.New("add post like failed")
|
||||
}
|
||||
|
||||
l.svcCtx.CommunityModelRW.Posts.Update().
|
||||
Where(posts.IDEQ(in.GetPostId())).
|
||||
AddLikeCount(1).
|
||||
Exec(l.ctx)
|
||||
|
||||
return &pb.AddPostLikesResp{}, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user