Переписаны модули, тесты, обработка ошибок
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
using System.Text.Json;
|
||||
using MediatR;
|
||||
using MediatR;
|
||||
using Nashel.BuildingBlocks.Application.Abstractions;
|
||||
using Nashel.BuildingBlocks.Domain;
|
||||
using Nashel.Modules.Catalog.Domain.Aggregates;
|
||||
|
||||
@@ -1,33 +1,47 @@
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Nashel.BuildingBlocks.Application.Abstractions;
|
||||
using Nashel.BuildingBlocks.Application.Configurations;
|
||||
using Nashel.BuildingBlocks.Application.Exceptions;
|
||||
|
||||
namespace Nashel.Modules.Catalog.Application.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Команда загрузки изображения услуги.
|
||||
/// </summary>
|
||||
public record UploadOfferImageCommand(byte[] Content, string FileName) : IRequest<string>;
|
||||
|
||||
public class UploadOfferImageCommandHandler : IRequestHandler<UploadOfferImageCommand, string>
|
||||
{
|
||||
private const long MaxFileSize = 5 * 1024 * 1024; // 5MB
|
||||
private static readonly string[] AllowedExtensions = { ".jpg", ".jpeg", ".png", ".webp" };
|
||||
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly MediaSettings _settings;
|
||||
|
||||
public UploadOfferImageCommandHandler(ICurrentUserService currentUserService)
|
||||
public UploadOfferImageCommandHandler(
|
||||
ICurrentUserService currentUserService,
|
||||
IOptions<MediaSettings> settings)
|
||||
{
|
||||
_currentUserService = currentUserService;
|
||||
_settings = settings.Value;
|
||||
}
|
||||
|
||||
public Task<string> Handle(UploadOfferImageCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var userId = _currentUserService.UserId;
|
||||
if (userId == null) throw new UnauthorizedAccessException();
|
||||
if (userId == null)
|
||||
{
|
||||
throw new UnauthorizedAccessException();
|
||||
}
|
||||
|
||||
if (request.Content.Length > MaxFileSize)
|
||||
throw new InvalidOperationException("Размер файла не должен превышать 5 МБ");
|
||||
if (request.Content.Length > _settings.MaxFileSizeInBytes)
|
||||
{
|
||||
throw new BusinessRuleException($"Размер файла слишком велик. Максимум: {_settings.MaxFileSizeInBytes / 1024 / 1024} МБ.");
|
||||
}
|
||||
|
||||
var extension = Path.GetExtension(request.FileName).ToLowerInvariant();
|
||||
if (Array.IndexOf(AllowedExtensions, extension) == -1)
|
||||
throw new InvalidOperationException("Допустимые форматы: JPG, PNG, WEBP");
|
||||
if (!_settings.AllowedExtensions.Contains(extension))
|
||||
{
|
||||
throw new BusinessRuleException($"Допустимые форматы: {string.Join(", ", _settings.AllowedExtensions)}.");
|
||||
}
|
||||
|
||||
var base64String = Convert.ToBase64String(request.Content);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user