refac: allowed image types and the size limit are a domain rule checked by the use case, not by the persistence layer

This commit is contained in:
fsylvain committed 2026-09-24 00:03:29 +02:00
1 parent 8a8a24434a
commit 5992c8598b
7 files changed
+249 -17

No files matched your search

+25
View File
@@ -3,10 +3,35 @@ package image
import (
"errors"
"io"
"sort"
"time"
)
var ErrImageNotFound = errors.New("image not found")
var ErrImageTypeNotAllowed = errors.New("the file must be a PNG, JPEG, WEBP, or SVG image")
var ErrImageTooLarge = errors.New("the file exceeds the maximum upload size")
const MaxImageSize int64 = 10485760
var allowedContentTypes = map[string]bool{
"image/png": true,
"image/jpeg": true,
"image/webp": true,
"image/svg+xml": true,
}
func IsAllowedContentType(contentType string) bool {
return allowedContentTypes[contentType]
}
func AllowedContentTypes() []string {
types := make([]string, 0, len(allowedContentTypes))
for contentType := range allowedContentTypes {
types = append(types, contentType)
}
sort.Strings(types)
return types
}
type ImageInput struct {
Content io.Reader
@@ -4,7 +4,6 @@ import (
domain "RenewCMS/internal/domain/image"
"RenewCMS/internal/infrastructure/persistence/mappers"
entity "RenewCMS/internal/infrastructure/persistence/models"
"errors"
"io"
"os"
"path/filepath"
@@ -42,9 +41,6 @@ func (i ImageRepository) Create(input domain.ImageInput) (domain.Image, error) {
}
extension := contentTypeExtensions[input.ContentType]
if extension == "" {
return domain.Image{}, errors.New("the file must be a PNG, JPEG, WEBP, or SVG image")
}
newName := uuid.NewString() + extension
finalPath := filepath.Join(uploadDir, newName)
@@ -13,5 +13,11 @@ func NewCreateImageUseCase(imageRepository image.Repository) *CreateImageUseCase
}
func (g *CreateImageUseCase) CreateImage(input image.ImageInput) (image.Image, error) {
if !image.IsAllowedContentType(input.ContentType) {
return image.Image{}, image.ErrImageTypeNotAllowed
}
if input.Size > image.MaxImageSize {
return image.Image{}, image.ErrImageTooLarge
}
return g.imageRepository.Create(input)
}