nquest/pkg/service/file.go

60 lines
1.1 KiB
Go
Raw Normal View History

2024-01-20 21:37:49 +03:00
package service
import (
"context"
"fmt"
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) 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
}