Handler.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using Application.Abstractions.Messaging;
  2. using Application.Abstractions.Data;
  3. using SharedKernel.Storage;
  4. using Microsoft.EntityFrameworkCore;
  5. namespace Application.Features.Forum.Post.Update;
  6. public sealed class Handler(IAppDbContext db, IFileStorage fileStorage) : ICommandHandler<Command>
  7. {
  8. public async Task Handle(Command request, CancellationToken ct)
  9. {
  10. var post = await db.Post.FirstOrDefaultAsync(x => x.ID == request.ID, ct);
  11. if (post is null)
  12. {
  13. throw new KeyNotFoundException("게시글을 찾을 수 없습니다.");
  14. }
  15. post.Subject = request.Subject;
  16. post.Content = request.Content ?? string.Empty;
  17. post.IsNotice = request.IsNotice;
  18. post.IsSecret = request.IsSecret;
  19. post.IsAnonymous = request.IsAnonymous;
  20. post.UpdatedAt = DateTime.UtcNow;
  21. if (request.ThumbnailFile is not null)
  22. {
  23. FileStoragePath uploadPath = new(UploadTarget.Upload, UploadFolder.Post, post.ID);
  24. string[] allowedFileExtensions = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"];
  25. if (!string.IsNullOrEmpty(post.Thumbnail))
  26. {
  27. fileStorage.DeleteByUrl(post.Thumbnail);
  28. }
  29. var result = await fileStorage.SaveFileAsync(request.ThumbnailFile, uploadPath, allowedFileExtensions, ct);
  30. post.Thumbnail = result?.Url;
  31. }
  32. await db.SaveChangesAsync(ct);
  33. }
  34. }