Handler.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using Application.Abstractions.Messaging;
  2. using Domain.Entities.Donations.ValueObject;
  3. using SharedKernel.Results;
  4. using SharedKernel.Storage;
  5. namespace Application.Features.Api.DonationAlert.UploadMedia;
  6. internal sealed class Handler(IFileStorage fileStorage) : ICommandHandler<Command, Result<string>>
  7. {
  8. private static readonly string[] ImageExtensions = [".jpg", ".jpeg", ".png", ".gif"];
  9. private static readonly string[] SoundExtensions = [".mp3", ".ogg", ".wav", ".m4a"];
  10. public async Task<Result<string>> Handle(Command r, CancellationToken ct)
  11. {
  12. string[] extensions;
  13. int maxSizeMB;
  14. switch (r.Type)
  15. {
  16. case "image":
  17. extensions = ImageExtensions;
  18. maxSizeMB = DonationConstants.Alert.MaxImageFileSizeMB;
  19. break;
  20. case "sound":
  21. extensions = SoundExtensions;
  22. maxSizeMB = DonationConstants.Alert.MaxSoundFileSizeMB;
  23. break;
  24. default:
  25. return Result.Failure<string>(Error.Problem("UploadMedia.InvalidType", "유효하지 않은 파일 타입입니다."));
  26. }
  27. if (r.File.Length > maxSizeMB * 1024 * 1024)
  28. {
  29. return Result.Failure<string>(Error.Problem("UploadMedia.FileTooLarge", $"파일 크기는 {maxSizeMB}MB 이하여야 합니다."));
  30. }
  31. var path = new FileStoragePath(UploadTarget.Upload, UploadFolder.DonationAlert, r.ChannelID);
  32. var result = await fileStorage.SaveFileAsync(r.File, path, extensions, ct);
  33. if (result is null)
  34. {
  35. return Result.Failure<string>(Error.Problem("UploadMedia.Failed", "파일 업로드에 실패했습니다. 허용된 확장자를 확인하세요."));
  36. }
  37. return Result.Success(result.Url);
  38. }
  39. }