recommender/internal/service/post/posts.go
2024-11-10 03:49:53 +08:00

87 lines
2.4 KiB
Go

package post
import (
"context"
"github.com/iVampireSP/pkg/page"
"leafdev.top/Ecosystem/recommender/internal/entity"
"leafdev.top/Ecosystem/recommender/internal/schema"
"leafdev.top/Ecosystem/recommender/pkg/consts"
)
func (s *Service) ListPosts(c context.Context, pagedResult *page.PagedResult[*entity.Post], category *entity.Category, application *entity.Application) error {
var q = s.dao.WithContext(c).Post
if application != nil {
q = q.Preload(s.dao.Post.Application).Where(s.dao.Post.ApplicationId.Eq(application.Id.Uint()))
}
if category != nil {
q = q.Preload(s.dao.Post.Category).Where(s.dao.Post.CategoryId.Eq(category.Id.Uint()))
}
posts, count, err := q.FindByPage(pagedResult.Offset(), pagedResult.PageSize)
if err != nil {
return err
}
pagedResult.Data = posts
pagedResult.TotalCount = count
return nil
}
func (s *Service) TargetIdExists(c context.Context, application *entity.Application, targetId string) (bool, error) {
count, err := s.dao.WithContext(c).Post.Where(s.dao.Post.TargetId.Eq(targetId)).
Where(s.dao.Post.ApplicationId.Eq(application.Id.Uint())).
Count()
return count > 0, err
}
func (s *Service) CreatePost(c context.Context, applicationEntity *entity.Application, post *entity.Post) error {
// 检测 target_id 是否存在
exists, err := s.TargetIdExists(c, applicationEntity, post.TargetId)
if exists {
return consts.ErrPostTargetIdExists
}
post.ApplicationId = applicationEntity.Id
err = s.dao.WithContext(c).Post.Create(post)
if err != nil {
return err
}
return s.stream.SendEvent(c, s.config.Kafka.WorkerTopic, &schema.ProcessPostRequest{
PostId: post.Id.String(),
Content: post.Content,
})
}
func (s *Service) DeletePost(c context.Context, post *entity.Post) error {
_, err := s.dao.WithContext(c).Post.Delete(post)
return err
}
func (s *Service) GetPostById(c context.Context, postId schema.EntityId) (*entity.Post, error) {
return s.dao.WithContext(c).Post.Preload(s.dao.Post.Application).Where(s.dao.Post.Id.Eq(postId.Uint())).First()
}
func (s *Service) GetPostTags(c context.Context, postEntity *entity.Post) ([]*entity.Tag, error) {
postTags, err := s.dao.WithContext(c).PostTag.Preload(s.dao.PostTag.Tag).
Where(s.dao.PostTag.PostId.Eq(postEntity.Id.Uint())).Find()
if err != nil {
return nil, err
}
var tags []*entity.Tag
for _, postTag := range postTags {
tags = append(tags, postTag.Tag)
}
return tags, err
}