| | | 1 | | using RoleRadar.Application.Abstractions; |
| | | 2 | | |
| | | 3 | | namespace RoleRadar.Application.Decorators; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Runs every registered <see cref="ICommandValidator{TCommand}"/>, checks store readiness, then runs the inner |
| | | 7 | | /// handler inside one repository transaction. It does not write audit entries itself: the handler or the |
| | | 8 | | /// repository write port appends them inside this transaction, so a write and its audit entry commit or roll |
| | | 9 | | /// back together (ADR 0002, ADR 0006). |
| | | 10 | | /// </summary> |
| | | 11 | | public sealed class TransactionCommandDecorator<TCommand, TResponse> : ICommandHandler<TCommand, TResponse> |
| | | 12 | | where TCommand : ICommand<TResponse> |
| | | 13 | | { |
| | | 14 | | private readonly ICommandHandler<TCommand, TResponse> _inner; |
| | | 15 | | private readonly INoteRepository _repository; |
| | | 16 | | private readonly IEnumerable<ICommandValidator<TCommand>> _validators; |
| | | 17 | | |
| | 2276 | 18 | | public TransactionCommandDecorator( |
| | 2276 | 19 | | ICommandHandler<TCommand, TResponse> inner, |
| | 2276 | 20 | | INoteRepository repository, |
| | 2276 | 21 | | IEnumerable<ICommandValidator<TCommand>> validators) |
| | | 22 | | { |
| | 2276 | 23 | | ArgumentNullException.ThrowIfNull(inner); |
| | 2276 | 24 | | ArgumentNullException.ThrowIfNull(repository); |
| | 2276 | 25 | | ArgumentNullException.ThrowIfNull(validators); |
| | | 26 | | |
| | 2276 | 27 | | _inner = inner; |
| | 2276 | 28 | | _repository = repository; |
| | 2276 | 29 | | _validators = validators; |
| | 2276 | 30 | | } |
| | | 31 | | |
| | | 32 | | public async Task<Result<TResponse>> HandleAsync( |
| | | 33 | | TCommand command, |
| | | 34 | | CancellationToken cancellationToken = default) |
| | | 35 | | { |
| | 714 | 36 | | ArgumentNullException.ThrowIfNull(command); |
| | | 37 | | |
| | 2736 | 38 | | foreach (var validator in _validators) |
| | | 39 | | { |
| | 658 | 40 | | var validationError = validator.Validate(command); |
| | 658 | 41 | | if (validationError is not null) |
| | | 42 | | { |
| | 8 | 43 | | return Result<TResponse>.Failure(validationError.Value); |
| | | 44 | | } |
| | | 45 | | } |
| | | 46 | | |
| | 706 | 47 | | var readiness = await _repository.CheckReadinessAsync(cancellationToken); |
| | 706 | 48 | | if (!readiness.IsSuccess) |
| | | 49 | | { |
| | 2 | 50 | | return Result<TResponse>.Failure(readiness.Error!.Value); |
| | | 51 | | } |
| | | 52 | | |
| | 704 | 53 | | return await _repository.ExecuteInTransactionAsync( |
| | 842 | 54 | | (_, ct) => _inner.HandleAsync(command, ct), |
| | 704 | 55 | | cancellationToken); |
| | 712 | 56 | | } |
| | | 57 | | } |