nquest/pkg/service/file.go

75 lines
1.5 KiB
Go

package service
import (
"context"
"fmt"
"io"
"mime/multipart"
"github.com/google/uuid"
"github.com/spf13/afero"
"gitrepo.ru/neonxp/nquest/pkg/models"
"gorm.io/gorm"
)
type File struct {
DB *gorm.DB
store afero.Fs
}
func NewFile(db *gorm.DB, store afero.Fs) *File {
return &File{
DB: db,
store: store,
}
}
func (u *File) Upload(
ctx context.Context,
filename string,
contentType string,
size int,
questID uuid.UUID,
r multipart.File,
) (uuid.UUID, error) {
defer r.Close()
file := &models.File{
ID: uuid.New(),
Filename: filename,
ContentType: contentType,
QuestID: questID,
Size: size,
}
if err := u.store.MkdirAll(questID.String(), 0755); err != nil {
return file.ID, err
}
filePath := fmt.Sprintf("%s/%s", questID.String(), filename)
if err := afero.WriteReader(u.store, filePath, r); err != nil {
return file.ID, err
}
return file.ID, u.DB.WithContext(ctx).Create(file).Error
}
func (u *File) GetFile(ctx context.Context, uid uuid.UUID) (*models.File, io.ReadCloser, error) {
f := new(models.File)
if err := u.DB.WithContext(ctx).First(f, uid).Error; err != nil {
return nil, nil, err
}
filePath := fmt.Sprintf("%s/%s", f.QuestID.String(), f.Filename)
file, err := u.store.Open(filePath)
if err != nil {
return nil, nil, err
}
return f, file, nil
}
func (u *File) GetFilesByQuest(ctx context.Context, quest uuid.UUID) ([]*models.File, error) {
list := make([]*models.File, 0)
return list, u.DB.WithContext(ctx).Find(&list, `quest_id = ?`, quest.String()).Error
}