source: ChapterX.Application/Story/Commands/AddHandler.cs@ e882b92

main
Last change on this file since e882b92 was e882b92, checked in by kikisrbinoska <srbinoskakristina07@…>, 13 days ago

Added corrected entitef from the ER diagram and changes for the logic to be coresponding to the ddl

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