Handler.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using Application.Abstractions.Messaging;
  2. using Application.Abstractions.Data;
  3. using SharedKernel.Storage;
  4. using Microsoft.EntityFrameworkCore;
  5. namespace Application.Features.Admin.Forum.Post.Create;
  6. public sealed class Handler(IAppDbContext db, IFileStorage fileStorage) : ICommandHandler<Command>
  7. {
  8. public async Task Handle(Command request, CancellationToken ct)
  9. {
  10. if (!await db.Board.AnyAsync(x => x.ID == request.BoardID, ct))
  11. {
  12. throw new KeyNotFoundException("게시판을 찾을 수 없습니다.");
  13. }
  14. var post = new Domain.Entities.Forum.Posts.Post
  15. {
  16. BoardID = request.BoardID,
  17. MemberID = null,
  18. Subject = request.Subject,
  19. Content = request.Content ?? string.Empty,
  20. IsNotice = request.IsNotice,
  21. IsSecret = request.IsSecret,
  22. IsAnonymous = request.IsAnonymous,
  23. Name = "관리자"
  24. };
  25. await db.Post.AddAsync(post, ct);
  26. await db.SaveChangesAsync(ct);
  27. if (request.ThumbnailFile is not null)
  28. {
  29. FileStoragePath uploadPath = new(UploadTarget.Upload, UploadFolder.Post, post.ID);
  30. string[] allowedFileExtensions = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"];
  31. var result = await fileStorage.SaveFileAsync(request.ThumbnailFile, uploadPath, allowedFileExtensions, ct);
  32. post.Thumbnail = result?.Url;
  33. await db.SaveChangesAsync(ct);
  34. }
  35. // Board 게시글 카운트 증가
  36. var board = await db.Board.FirstOrDefaultAsync(x => x.ID == request.BoardID, ct);
  37. if (board is not null)
  38. {
  39. board.Posts++;
  40. board.UpdatedAt = DateTime.UtcNow;
  41. // BoardGroup 게시글 카운트 증가
  42. var boardGroup = await db.BoardGroup.FirstOrDefaultAsync(x => x.ID == board.BoardGroupID, ct);
  43. if (boardGroup is not null)
  44. {
  45. boardGroup.Posts++;
  46. boardGroup.UpdatedAt = DateTime.UtcNow;
  47. }
  48. await db.SaveChangesAsync(ct);
  49. }
  50. }
  51. }