blog/internal/service/text_content_service.go

64 lines
1.9 KiB
Go

package service
import (
"Blog/internal/client"
"Blog/internal/consts"
"Blog/internal/model"
"Blog/internal/repository"
"context"
"time"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)
var TextContentService *textContentService = newTextContentService()
type textContentService struct {
}
func initContentData() {
var slices []model.BlogTextContent = repository.TextContentRepository.FindList(nil, "state = ?", consts.CONTENT_STATE_PUBLISH)
logrus.Info("大文本初始化数据加载量:", len(slices))
for _, content := range slices {
client.RedisClient.Set(context.Background(), consts.REDIS_BLOG_CONTENT+content.RelId, &content, time.Duration(0))
}
}
func newTextContentService() *textContentService {
go initContentData()
return &textContentService{}
}
func (*textContentService) GetContent(relId string) *model.BlogTextContent {
ctx := context.Background()
var content *model.BlogTextContent = &model.BlogTextContent{}
err := client.RedisClient.Get(ctx, consts.REDIS_BLOG_CONTENT+relId).Scan(content)
if err != nil {
// err = repository.TextContentRepository.Table(consts.TABLE_BLOG_TEXT_CONTENT).Where("rel_id = ?", relId).First(content).Error
content = repository.TextContentRepository.FindOne("rel_id = ?", relId)
}
return content
}
func (*textContentService) SaveContent(relId string, content string) *model.BlogTextContent {
cnt := model.BlogTextContent{Id: uuid.NewString(), RelId: relId, Content: content, State: consts.CONTENT_STATE_PUBLISH}
txErr := repository.TextContentRepository.WGorm(func(tx *gorm.DB) error {
err := tx.Table(consts.TABLE_BLOG_TEXT_CONTENT).Create(cnt).Error
return err
})
if txErr != nil {
return nil
}
return &cnt
}
func (*textContentService) UpdataState(relId string, state string) error {
err := repository.TextContentRepository.Table(consts.TABLE_BLOG_TEXT_CONTENT).Where("rel_id = ?", relId).UpdateColumn("state", state).Error
return err
}