nquest/pkg/service/file.go

50 lines
845 B
Go
Raw Normal View History

2024-01-20 21:37:49 +03:00
package service
import (
"context"
"mime/multipart"
"github.com/google/uuid"
"gitrepo.ru/neonxp/nquest/pkg/models"
"gorm.io/gorm"
)
type File struct {
DB *gorm.DB
}
func NewFile(db *gorm.DB) *File {
return &File{
DB: db,
}
}
func (u *File) Upload(
ctx context.Context,
filename string,
contentType string,
size int,
r multipart.File,
) (uuid.UUID, error) {
buf := make([]byte, size)
if _, err := r.Read(buf); err != nil {
return uuid.UUID{}, err
}
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,
Size: size,
Body: buf,
}
return file.ID, u.DB.WithContext(ctx).Create(file).Error
}
func (u *File) GetFile(ctx context.Context, uid uuid.UUID) (*models.File, error) {
f := new(models.File)
return f, u.DB.WithContext(ctx).First(f, uid).Error
}