nquest/pkg/service/file.go

76 lines
1.5 KiB
Go
Raw Normal View History

2024-01-20 21:37:49 +03:00
package service
import (
"context"
"fmt"
"io"
2024-01-20 21:37:49 +03:00
"mime/multipart"
"github.com/google/uuid"
"github.com/spf13/afero"
2024-01-20 21:37:49 +03:00
"gitrepo.ru/neonxp/nquest/pkg/models"
"gorm.io/gorm"
)
type File struct {
DB *gorm.DB
store afero.Fs
2024-01-20 21:37:49 +03:00
}
func NewFile(db *gorm.DB, store afero.Fs) *File {
2024-01-20 21:37:49 +03:00
return &File{
DB: db,
store: store,
2024-01-20 21:37:49 +03:00
}
}
func (u *File) Upload(
ctx context.Context,
filename string,
contentType string,
size int,
questID uuid.UUID,
2024-01-20 21:37:49 +03:00
r multipart.File,
) (uuid.UUID, error) {
defer r.Close()
2024-01-20 21:37:49 +03:00
file := &models.File{
2024-01-28 22:19:41 +03:00
ID: uuid.New(),
2024-01-20 21:37:49 +03:00
Filename: filename,
ContentType: contentType,
QuestID: questID,
2024-01-20 21:37:49 +03:00
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
2024-01-20 21:37:49 +03:00
}
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) {
2024-01-20 21:37:49 +03:00
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)
2024-01-20 21:37:49 +03:00
return list, u.DB.WithContext(ctx).Find(&list, `quest_id = ?`, quest.String()).Error
2024-01-20 21:37:49 +03:00
}