| 1 | using ChapterX.Application.Abstractions;
|
|---|
| 2 | using ChapterX.Domain.Repositories;
|
|---|
| 3 | using MediatR;
|
|---|
| 4 | using Microsoft.Extensions.Logging;
|
|---|
| 5 |
|
|---|
| 6 | namespace ChapterX.Application.Story.Commands
|
|---|
| 7 | {
|
|---|
| 8 | public class AddHandler : IRequestHandler<AddRequest, AddResponse>
|
|---|
| 9 | {
|
|---|
| 10 | private readonly IStoryRepository _storyRepository;
|
|---|
| 11 | private readonly IGenreRepository _genreRepository;
|
|---|
| 12 | private readonly IHasGenreRepository _hasGenreRepository;
|
|---|
| 13 | private readonly IApplicationDbContext _context;
|
|---|
| 14 | private readonly ILogger<AddHandler> _logger;
|
|---|
| 15 |
|
|---|
| 16 | public AddHandler(IStoryRepository storyRepository, IGenreRepository genreRepository, IHasGenreRepository hasGenreRepository, IApplicationDbContext context, ILogger<AddHandler> logger)
|
|---|
| 17 | {
|
|---|
| 18 | _storyRepository = storyRepository;
|
|---|
| 19 | _genreRepository = genreRepository;
|
|---|
| 20 | _hasGenreRepository = hasGenreRepository;
|
|---|
| 21 | _context = context;
|
|---|
| 22 | _logger = logger;
|
|---|
| 23 | }
|
|---|
| 24 |
|
|---|
| 25 | public async Task<AddResponse> Handle(AddRequest request, CancellationToken cancellationToken)
|
|---|
| 26 | {
|
|---|
| 27 | await using var transaction = await _context.BeginTransactionAsync(cancellationToken);
|
|---|
| 28 | try
|
|---|
| 29 | {
|
|---|
| 30 | var story = new Domain.Entities.Story
|
|---|
| 31 | {
|
|---|
| 32 | MatureContent = request.MatureContent,
|
|---|
| 33 | Title = request.Title,
|
|---|
| 34 | ShortDescription = request.ShortDescription,
|
|---|
| 35 | Image = request.Image,
|
|---|
| 36 | Content = request.Content,
|
|---|
| 37 | UserId = request.UserId,
|
|---|
| 38 | CreatedAt = DateTime.UtcNow,
|
|---|
| 39 | UpdatedAt = DateTime.UtcNow
|
|---|
| 40 | };
|
|---|
| 41 |
|
|---|
| 42 | await _storyRepository.AddAsync(story, cancellationToken);
|
|---|
| 43 |
|
|---|
| 44 | foreach (var genreName in request.Genres ?? [])
|
|---|
| 45 | {
|
|---|
| 46 | var genre = await _genreRepository.GetByNameAsync(genreName, cancellationToken);
|
|---|
| 47 | if (genre == null) continue;
|
|---|
| 48 | await _hasGenreRepository.AddAsync(new Domain.Entities.HasGenre { StoryId = story.Id, GenreId = genre.Id }, cancellationToken);
|
|---|
| 49 | }
|
|---|
| 50 |
|
|---|
| 51 | await transaction.CommitAsync(cancellationToken);
|
|---|
| 52 | return new AddResponse(story.Id);
|
|---|
| 53 | }
|
|---|
| 54 | catch
|
|---|
| 55 | {
|
|---|
| 56 | await transaction.RollbackAsync(cancellationToken);
|
|---|
| 57 | throw;
|
|---|
| 58 | }
|
|---|
| 59 | }
|
|---|
| 60 | }
|
|---|
| 61 | }
|
|---|