98 lines
2.6 KiB
Go
98 lines
2.6 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 FileService *fileService = newFileService()
|
||
|
||
type fileService struct {
|
||
}
|
||
|
||
func newFileService() *fileService {
|
||
return &fileService{}
|
||
}
|
||
|
||
func (*fileService) GetFile(id string) (*model.UploadFile, error) {
|
||
ctx := context.Background()
|
||
var file *model.UploadFile = &model.UploadFile{}
|
||
var bytes []byte
|
||
err := client.RedisClient().Get(ctx, consts.REDIS_FILE+id).Scan(file)
|
||
//如果缓存不存在,则查数据库并存入Redis
|
||
if err != nil || file.Id == "" {
|
||
// repository.FileRepository.Table(consts.TABLE_UPLOAD_FILE).Where("id = ?", id).First(&file)
|
||
file := repository.FileRepository().GetById(id)
|
||
bytes = file.Data
|
||
err = client.RedisClient().Set(ctx, consts.REDIS_FILE+id, file, time.Duration(0)).Err()
|
||
if err != nil {
|
||
logrus.Info(err)
|
||
}
|
||
err = client.RedisClient().Set(ctx, consts.REDIS_FILE_BYTES+id, bytes, time.Duration(0)).Err()
|
||
if err != nil {
|
||
logrus.Info(err)
|
||
}
|
||
return file, nil
|
||
}
|
||
bytes, err = client.RedisClient().Get(ctx, consts.REDIS_FILE_BYTES+id).Bytes()
|
||
file.Data = bytes
|
||
return file, err
|
||
}
|
||
|
||
func (*fileService) PageFiles(page int, itemsPerPage int) model.Page[model.UploadFile] {
|
||
var content []model.UploadFile
|
||
var totalElements int64
|
||
repository.FileRepository().Table(consts.TABLE_UPLOAD_FILE).Count(&totalElements)
|
||
repository.FileRepository().Table(consts.TABLE_UPLOAD_FILE).
|
||
Where("del != ?", 1).
|
||
Offset((page - 1) * itemsPerPage).
|
||
Limit(itemsPerPage).
|
||
Order("create_time DESC").
|
||
Find(&content)
|
||
|
||
pre := int(totalElements) % itemsPerPage
|
||
if pre > 0 {
|
||
pre = 1
|
||
}
|
||
var totalPages int = int(totalElements)/itemsPerPage + pre
|
||
|
||
return model.Page[model.UploadFile]{TotalElements: totalElements, TotalPages: totalPages, Number: page, Content: content}
|
||
}
|
||
|
||
func (*fileService) SaveFile(fileName string, data []byte, uploader string) *model.UploadFile {
|
||
// extLastIndex := strings.LastIndex(fileName, ".")
|
||
// ext := fileName[extLastIndex:]
|
||
fileSize := int64(len(data))
|
||
|
||
fileId := uuid.NewString()
|
||
// fileIds = append(fileId, fileId+ext)
|
||
file := model.UploadFile{
|
||
Id: fileId,
|
||
FileName: fileName,
|
||
FileSize: fileSize,
|
||
CreateBy: uploader,
|
||
CreateTime: time.Now().UnixMilli(),
|
||
Data: data,
|
||
State: "1",
|
||
Del: 0,
|
||
}
|
||
|
||
err := repository.FileRepository().WGorm(func(tx *gorm.DB) error {
|
||
err2 := tx.Table(consts.TABLE_UPLOAD_FILE).Create(file).Error
|
||
return err2
|
||
})
|
||
if err != nil {
|
||
return nil
|
||
}
|
||
|
||
return &file
|
||
}
|