diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md new file mode 100644 index 00000000..68f31844 --- /dev/null +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md @@ -0,0 +1,134 @@ +# Architecture Decision Record (ADR): 0011 - Replace MediatR with Custom CQRS Abstractions + +## Status + +**Accepted** (2026-08-13) + +## Context + +The solution uses MediatR as a lightweight mediator to encapsulate command and query handling across the application layer. Following MediatR's shift to a commercial licensing model starting with .NET 8, continued use introduces an unacceptable external dependency on a paid third-party library for functionality that is entirely implementable in-house. + +Key constraints that shaped this decision: + +1. **Licensing Change**: MediatR became a commercial product for .NET 8+ projects, requiring a paid license for continued use in production systems. + +2. **Narrow Usage Scope**: MediatR is used for command and query dispatching, with a single pipeline behavior (automatic application validation) and no stream requests. Its notification publishing is used for domain event publishing, which is outside the scope of this ADR and is replaced separately (see ADR-0013). + +3. **Zero Abstraction Value at Scale**: With only a validation pipeline behavior registered, the command and query dispatching provides no runtime value beyond a dispatch indirection that can be replaced by direct handler injection. It actually hurts performance by runtime dispatching of handlers via reflection. + +4. **Ownership and Transparency**: A custom implementation is fully owned, inspectable, and carries no transitive dependency risk or future licensing exposure. + +## Decision + +Replace MediatR with minimal, hand-written CQRS abstractions placed in `Lumina.Application.Common.CQRS`. Handlers are resolved directly via the .NET dependency injection container - no mediator object, no runtime reflection dispatch. + +### Core Abstractions + +```csharp +// src/Lumina.Application/Common/CQRS/ICommand.cs + +/// +/// Marker interface for command types handled by . +/// +public interface ICommand +{ +} + +/// +/// Defines a contract for handling commands in the application layer. +/// Commands represent operations that modify application state. +/// +/// The type of command to handle. +/// The type of result returned after handling the command. +public interface ICommandHandler where TCommand : ICommand +{ + Task HandleAsync(TCommand command, CancellationToken cancellationToken = default); +} +``` + +```csharp +// src/Lumina.Application/Common/CQRS/IQuery.cs + +/// +/// Marker interface for query types handled by . +/// +public interface IQuery +{ +} + +/// +/// Defines a contract for handling queries in the application layer. +/// Queries represent read operations that do not modify application state. +/// +/// The type of query to handle. +/// The type of result returned after handling the query. +public interface IQueryHandler where TQuery : IQuery +{ + Task HandleAsync(TQuery query, CancellationToken cancellationToken = default); +} +``` + +### Usage at Call Site + +Handlers are injected directly - no `ISender` or mediator intermediary: + +```csharp +// Before (MediatR) +internal sealed record GetConfiguredNismsQuery : IRequest>>; +internal sealed class GetConfiguredNismsEndpoint : IGetConfiguredNismsEndpoint +{ + private readonly ISender _sender; + + public GetConfiguredNismsEndpoint(ISender sender) + { + _sender = sender; + } + + public async Task>> ExecuteAsync(CancellationToken cancellationToken) + { + return await _sender.Send(new GetConfiguredNismsQuery(), cancellationToken).ConfigureAwait(false); + } +} + +// After (custom abstraction) +internal sealed record GetConfiguredNismsQuery : IQuery; +internal sealed class GetConfiguredNismsEndpoint : IGetConfiguredNismsEndpoint +{ + private readonly IQueryHandler>> _handler; + + public GetConfiguredNismsEndpoint(IQueryHandler>> handler) + { + _handler = handler; + } + + public async Task>> ExecuteAsync(CancellationToken cancellationToken) + { + return await _handler.HandleAsync(new GetConfiguredNismsQuery(), cancellationToken).ConfigureAwait(false); + } +} +``` + +## Consequences + +### Positive Outcomes + +| Aspect | Benefit | +|---|---| +| Licensing | Eliminates commercial dependency and associated cost/compliance risk | +| Simplicity | Removes an indirection layer unused beyond basic dispatch | +| Transparency | Full ownership of dispatch logic; no hidden reflection or dynamic proxy behavior | +| Testability | Handlers are tested directly via their interface, no mock mediator required | +| DI Alignment | Leverages the existing .NET DI container idioms already present in the solution | +| Performance | No runtime reflection, other than the startup registration of application use case handlers | + +### Risks and Mitigations + +| Risk | Mitigation Strategy | +|---|---| +| Loss of pipeline behavior support | Application validation will be performed manually, as an orchestration step | +| Handler resolution errors surfacing at runtime | Covered by existing integration test suite that exercises the DI container on startup | +| Increased boilerplate per feature | Marginal - one interface injection vs. `ISender`; offset by elimination of `IRequest` marker on every command/query | + +## Alternatives Considered + +No alternative libraries were evaluated. The sole driver for replacing MediatR was the licensing change, and the solution's usage is narrow enough that a first-party implementation is both sufficient and lower risk than adopting a different third-party mediator library. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0012.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0012.md new file mode 100644 index 00000000..27bf386e --- /dev/null +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0012.md @@ -0,0 +1,184 @@ +# Architecture Decision Record (ADR): 0012 - Replace FluentValidation with Custom Validation Abstractions + +## Status + +**Accepted** (2026-08-13) + +## Context + +The solution uses FluentValidation to validate commands and queries at the application boundary. A review of its usage across the codebase reveals a deliberately constrained subset of its feature set: + +1. **Narrow API Surface**: Only `RuleFor`, `Must`, `When`, and `WithMessage`-equivalent patterns are used. Advanced FluentValidation features - cascading rules, `RuleSets`, async validators, `SetValidator`, `Transform`, and the `AbstractValidator` inheritance tree beyond basic use - are absent throughout. + +2. **`Error`-typed Results**: The solution uses `ErrorOr` as its result type. FluentValidation returns `ValidationResult` / `ValidationFailure`, requiring a translation layer on every usage site to produce `Error` values, with some information loss in the process. A first-party validator can return `ErrorOr.Error` directly, with full metadata, eliminating that friction. + +3. **External Dependency Surface**: FluentValidation is a well-maintained library, but the danger of it going commercial, like other open source popular libraries in recent times, and the lack of usage of its advanced features mandates an in-house replacement. + +4. **Placement in SharedKernel**: Validation logic is cross-cutting and lives in `Lumina.Application.Common.Infrastructure.Validation`. Owning the abstraction entirely means the validation model stays aligned with the domain's `Error` type without any adapter. + +## Decision + +Replace FluentValidation with a minimal, first-party validation framework placed in `Lumina.Application.Common.Infrastructure.Validation`. The API mirrors FluentValidation's familiar fluent surface (`RuleFor`, `Must`, `When`, `WithError`) to minimize migration friction. + +### Core Abstractions + +```csharp +// IValidator.cs - public contract consumed by application handlers +public interface IValidator +{ + List Validate(TRequest instance); +} + +// IValidationRule.cs - internal rule evaluation contract +internal interface IValidationRule +{ + Error? Validate(TRequest instance); +} + +// IRuleBuilder.cs - fluent configuration surface +public interface IRuleBuilder +{ + IRuleBuilder Must(Func predicate); + IRuleBuilder When(Func condition); + IRuleBuilder WithError(Error error); +} +``` + +### Base Validator + +```csharp +// AbstractValidator.cs +public abstract class AbstractValidator : IValidator +{ + private readonly List> _rules = []; + + protected IRuleBuilder RuleFor( + Func propertySelector) + { + ValidationRule rule = new(propertySelector); + _rules.Add(rule); + return rule; + } + + public List Validate(TRequest instance) + { + List errors = []; + foreach (IValidationRule rule in _rules) + { + Error? error = rule.Validate(instance); + if (error.HasValue) + errors.Add(error.Value); + } + return errors; + } +} +``` + +### Concrete Rule Implementation + +```csharp +// ValidationRule.cs - internal sealed, not exposed to consumers +internal sealed class ValidationRule + : IValidationRule, IRuleBuilder +{ + private readonly Func _propertySelector; + private readonly List> _predicates = []; + private Error _error = Error.Validation(); + private Func? _condition; + + public ValidationRule(Func propertySelector) + => _propertySelector = propertySelector; + + public IRuleBuilder Must(Func predicate) + { + _predicates.Add(predicate); + return this; + } + + public IRuleBuilder When(Func condition) + { + _condition = condition; + return this; + } + + public IRuleBuilder WithError(Error error) + { + _error = error; + return this; + } + + public Error? Validate(TRequest instance) + { + if (_condition is not null && !_condition(instance)) + return null; + + TProperty value = _propertySelector(instance); + foreach (var predicate in _predicates) + if (!predicate(value)) + return _error; + + return null; + } +} +``` + +### Built-in Extension Methods + +Common predicates are provided as extension methods on `IRuleBuilder` via `ValidatorUtilities`, placed in `Lumina.Application.Common.Utilities`: + +| Extension | Overloads | Behaviour | +|---|---|---| +| `NotEmpty()` | `string`, `List` | Fails if `null`, empty, or whitespace-only | +| `GreaterThan(value)` | `int`, `int?`, `TimeSpan` | Fails if property ≤ value; nullable variant passes on `null` | +| `IsInEnum()` | `TEnum`, `TEnum?` | Fails if value is not a defined enum member; nullable variant passes on `null` | + +### Usage Example + +```csharp +internal sealed class CreateSensorCommandValidator : AbstractValidator +{ + public CreateSensorCommandValidator() + { + RuleFor(x => x.Name) + .NotEmpty() + .WithError(Errors.Sensor.NameRequired); + + RuleFor(x => x.IntervalSeconds) + .GreaterThan(0) + .WithError(Errors.Sensor.InvalidInterval); + + RuleFor(x => x.Type) + .IsInEnum() + .WithError(Errors.Sensor.InvalidType); + + RuleFor(x => x.ThresholdOverride) + .GreaterThan(0) + .When(x => x.ThresholdOverride.HasValue) + .WithError(Errors.Sensor.InvalidThreshold); + } +} +``` + +## Consequences + +### Positive Outcomes + +| Aspect | Benefit | +|---|---| +| `Error` Alignment | Validators return `List` directly - no `ValidationResult` → `Error` translation layer at call sites | +| Dependency Reduction | Removes FluentValidation NuGet package and all transitive dependencies | +| API Ownership | Full control over rule semantics, error shape, and future extension | +| Familiar Surface | `RuleFor` / `Must` / `When` / `WithError` pattern is intentionally close to FluentValidation, minimising cognitive load during migration | +| Encapsulation | `IValidationRule` and `ValidationRule` are `internal`; consumers only interact with `IValidator` and `IRuleBuilder` | + +### Risks and Mitigations + +| Risk | Mitigation Strategy | +|---|---| +| Missing built-in rules surfacing post-migration | Audit all existing FluentValidation rule usages before removal; add corresponding `ValidatorUtilities` extensions as needed | +| Async validation not supported | No async validators exist, because this pertains to application use cases validation concerns (user input, etc), not business rules validations or invariants, which might require asynchronous or IO operations | +| Loss of FluentValidation test helpers (`TestValidate`) | Replace with direct `ValidatorTestExtensions.TestValidate` calls in unit tests | + +## Alternatives Considered + +No alternative third-party validation libraries were evaluated, as this decision was not about replacing the FluentValidation libary with another library. The solution's validation usage is sufficiently narrow (property-level predicates, conditional execution, typed error results) that the cost of adopting and adapting another external library exceeds the cost of ownership of a purpose-built implementation aligned with the `ErrorOr` result model already in use. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0013.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0013.md new file mode 100644 index 00000000..74e21de2 --- /dev/null +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0013.md @@ -0,0 +1,76 @@ +# Architecture Decision Record (ADR): 0013 - Replace Mediator Domain Event Publishing with a Custom Implementation + +## Status + +**Accepted** (2026-08-13) + +## Context + +Domain event publishing, the mechanism that fires the `IDomainEvent` objects raised by aggregates to their handlers, depends on the Mediator library (`Mediator.Abstractions` and `Mediator.SourceGenerator`). + +1. **Event contract**: `IDomainEvent` implements Mediator's `INotification` marker interface. + +2. **Handler registration**: Domain event handlers implements Mediator's `INotificationHandler` and are registered by the source-generated `AddMediator` call. + +3. **Publishing sites**: Mediator's `IPublisher` is used from `EventualConsistencyMiddleware` (queued events, published after the transaction commits), from `MediaLibraryScanningService` (scan start events), and from the scan jobs and `ScanFailurePublisher` (progress and failure events). + +The remaining publish half carries the same third-party dependency and source-generated registration that ADR-0011 removed from the dispatch half. + +## Decision + +Replace Mediator's notification publishing with a first-party domain event publisher. + +### New Abstractions (in `Lumina.Domain.Common.Events`) + +- `IDomainEvent` no longer inherits `INotification`. +- `IDomainEventPublisher` exposes `ValueTask PublishAsync(IDomainEvent domainEvent, CancellationToken cancellationToken = default)`. +- `IDomainEventHandler` exposes `ValueTask HandleAsync(TDomainEvent domainEvent, CancellationToken cancellationToken)`. The type parameter is invariant so handlers stay mockable by dynamic proxy libraries. + +### Publisher Implementation (`DomainEventPublisher` in Infrastructure) + +- Scoped, resolving handlers for the event's runtime type from the DI container. +- Dispatches through a compiled delegate cached per event type in a static `ConcurrentDictionary`, built once via `MakeGenericMethod` over a generic dispatch helper. Handlers run sequentially in registration order, exceptions propagate, and events without handlers are no-ops. +- Registered next to the existing `IDomainEventsQueue`. + +### Registration (Application DI) + +The existing assembly scan that registers `ICommandHandler<>`, `IQueryHandler<>`, and `IValidator<>` now also registers `IDomainEventHandler<>` as scoped, replacing the source-generated `AddMediator`. + +### Consistency Guarantees Preserved + +- Commit-before-publish ordering in `EventualConsistencyMiddleware` is unchanged (see ADR-0002). +- Re-entrant publishing (a handler publishing another event) is safe: each publish resolves handlers fresh from the scoped provider. +- Jobs publish from their own scopes, so handlers receive a fresh unit of work and `DbContext`. + +## Consequences + +### Positive Outcomes + +| Aspect | Benefit | +|---|---| +| Dependency reduction | Removes `Mediator.Abstractions` and `Mediator.SourceGenerator` from the entire solution | +| Transparency | Dispatch logic is fully owned and inspectable; no generated code | +| Consistency | Domain event handlers join the same explicit registration scan as the CQRS handlers | +| Single event contract | `IDomainEvent` remains the sole contract until a real cross-bounded-context consumer exists | + +### Risks and Mitigations + +| Risk | Mitigation Strategy | +|---|---| +| Handler resolution failures surface at runtime | Existing integration test suite exercises the DI container on startup | +| Reflection-based dispatch per event type | Compiled delegate cache makes dispatch cheap after the first publish of each type | +| Dynamic proxy cannot proxy generic interfaces | `IDomainEventHandler` is deliberately invariant so handlers remain mockable in unit tests | + +## Alternatives Considered + +### 1. Domain versus Integration Event Split + +Introduce `IIntegrationEvent` now, with a durable outbox, for inter-bounded-context propagation. + +**Rejected**: there are no cross-bounded-context consumers today - every event lives in the `LibraryManagementBoundedContext` and is handled in-process. The outbox machinery (durability, retries, idempotency) is speculative until the first real consumer appears, and forcing every existing event into one of two buckets would produce classification with no basis. The seam is documented on `IDomainEvent` itself so the split stays cheap to introduce later. + +### 2. Keeping Mediator for Publishing + +Keep the Mediator library for the domain event publishing half. + +**Rejected**: for the same reason ADR-0011 rejected it for command and query dispatching - an external dependency, with source-generated registration, for functionality that is fully implementable in-house. diff --git a/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs b/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs deleted file mode 100644 index de644cc6..00000000 --- a/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs +++ /dev/null @@ -1,53 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using FluentValidation; -using Mediator; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Application.Common.Behaviors; - -/// -/// Represents a validation behavior in the Mediator pipeline for handling requests and responses. -/// -/// The type representing a request. It should implement . -/// The type representing a response. It should implement interface. -public class ValidationBehavior : IPipelineBehavior where TRequest : IRequest - where TResponse : IErrorOr -{ - private readonly IValidator? _validator; - - /// - /// Initializes a new instance of the class. - /// - /// The validator used in this behavior pipeline for the Mediator commands and queries. - public ValidationBehavior(IValidator? validator = null) - { - _validator = validator; - } - - /// - /// Pipeline handler. Perform any additional behavior and await the delegate as necessary. - /// - /// Incoming request. - /// Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler. - /// Cancellation token that can be used to stop the execution. - public async ValueTask Handle(TRequest request, MessageHandlerDelegate next, CancellationToken cancellationToken) - { - // if there is no validator, just invoke the handler - if (_validator is null) - return await next(request, cancellationToken).ConfigureAwait(false); - // before the handler of the command is executed - FluentValidation.Results.ValidationResult validationResult = await _validator.ValidateAsync(request, cancellationToken).ConfigureAwait(false); - // if there are no validation errors, invoke the command handler - if (validationResult.IsValid) - return await next(request, cancellationToken).ConfigureAwait(false); - // after the command handler is executed - List errors = validationResult.Errors.ConvertAll(validationFailure => Error.Validation(description: validationFailure.ErrorMessage)); - // the compiler doesn't know there is an implicit converter from a list of errors to the ErrorOr object, and unfortunately, there is no way around this but to use some magic - // this is acceptable because we DO know that we will always have a list of errors of type ErrorOr (check the generic constraint at the top of the class!) - return (dynamic)errors; - } -} diff --git a/src/Lumina.Application/Common/CQRS/ICommand.cs b/src/Lumina.Application/Common/CQRS/ICommand.cs new file mode 100644 index 00000000..c74204dc --- /dev/null +++ b/src/Lumina.Application/Common/CQRS/ICommand.cs @@ -0,0 +1,8 @@ +namespace Lumina.Application.Common.CQRS; + +/// +/// Marker interface for command types handled by . +/// +public interface ICommand +{ +} diff --git a/src/Lumina.Application/Common/CQRS/ICommandHandler.cs b/src/Lumina.Application/Common/CQRS/ICommandHandler.cs new file mode 100644 index 00000000..19e0018d --- /dev/null +++ b/src/Lumina.Application/Common/CQRS/ICommandHandler.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.CQRS; + +/// +/// Defines a contract for handling commands in the application layer. +/// Commands represent operations that modify application state. +/// +/// The type of command to handle. +/// The type of result returned after handling the command. +public interface ICommandHandler where TCommand : ICommand +{ + /// + /// Handles the specified command and returns a result. + /// + /// The command to handle. + /// Token to monitor for cancellation requests. + /// A task that represents the asynchronous operation, containing the result of the command execution. + Task HandleAsync(TCommand command, CancellationToken cancellationToken = default); +} diff --git a/src/Lumina.Application/Common/CQRS/IQuery.cs b/src/Lumina.Application/Common/CQRS/IQuery.cs new file mode 100644 index 00000000..dd2f42ed --- /dev/null +++ b/src/Lumina.Application/Common/CQRS/IQuery.cs @@ -0,0 +1,8 @@ +namespace Lumina.Application.Common.CQRS; + +/// +/// Marker interface for query types handled by . +/// +public interface IQuery +{ +} diff --git a/src/Lumina.Application/Common/CQRS/IQueryHandler.cs b/src/Lumina.Application/Common/CQRS/IQueryHandler.cs new file mode 100644 index 00000000..8b5fadde --- /dev/null +++ b/src/Lumina.Application/Common/CQRS/IQueryHandler.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.CQRS; + +/// +/// Defines a contract for handling queries in the application layer. +/// Queries represent read-only operations that retrieve data without modifying application state. +/// +/// The type of query to handle. +/// The type of result returned after handling the query. +public interface IQueryHandler where TQuery : IQuery +{ + /// + /// Handles the specified query and returns a result. + /// + /// The query to handle. + /// Token to monitor for cancellation requests. + /// A task that represents the asynchronous operation, containing the result of the query execution. + Task HandleAsync(TQuery query, CancellationToken cancellationToken = default); +} diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index 905573aa..229555a5 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -1,9 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; -using Lumina.Application.Common.Behaviors; -using Mediator; +using Lumina.Domain.Common.Events; using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; #endregion namespace Lumina.Application.Common.DependencyInjection; @@ -21,17 +23,33 @@ public static class ApplicationLayerServices /// The updated . public static IServiceCollection AddApplicationLayerServices(this IServiceCollection services) { - // register Mediator - services.AddMediator(options => + Type[] handlerContractTypes = + [ + typeof(CQRS.ICommandHandler<,>), + typeof(CQRS.IQueryHandler<,>), + typeof(Infrastructure.Validation.IValidator<>), + typeof(IDomainEventHandler<>), + ]; + + IEnumerable concreteTypes = Assembly.GetExecutingAssembly() + .GetTypes() + .Where(type => !type.IsInterface && !type.IsAbstract && !type.IsGenericTypeDefinition); + + var handlerRegistrations = concreteTypes + .SelectMany(implementation => implementation.GetInterfaces(), + (implementation, contract) => new { Contract = contract, Implementation = implementation }) + .Where(registration => registration.Contract.IsGenericType && handlerContractTypes.Contains(registration.Contract.GetGenericTypeDefinition())); + + foreach (var registration in handlerRegistrations) { - options.ServiceLifetime = ServiceLifetime.Scoped; - }); + if (services.Any(service => service.ServiceType == registration.Contract)) + continue; - // register the validation behavior - services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); - - // register fluent validators - services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly); + if (registration.Contract.GetGenericTypeDefinition() == typeof(Infrastructure.Validation.IValidator<>)) + services.AddSingleton(registration.Contract, registration.Implementation); + else + services.AddScoped(registration.Contract, registration.Implementation); + } return services; } diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/AbstractValidator.cs b/src/Lumina.Application/Common/Infrastructure/Validation/AbstractValidator.cs new file mode 100644 index 00000000..cb40c867 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Validation/AbstractValidator.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Validation; + +/// +/// Base class for creating validators for commands and queries. +/// +/// The type of the request (command or query) to be validated. +public abstract class AbstractValidator : IValidator +{ + private readonly List> _rules = []; + + /// + /// Defines a validation rule for a specific property on the request being validated. + /// + /// The type of the property being validated. + /// A function that selects the property to validate from the request instance. + /// An instance to configure the rule fluently. + public IRuleBuilder RuleFor(Func propertySelector) + { + ValidationRule rule = new(propertySelector); + _rules.Add(rule); + return rule; + } + + /// + /// Defines a validation rule that is evaluated against each item within a collection property on the request being validated. + /// + /// The type of the items in the collection being validated. + /// A function that selects the collection to validate from the request instance. + /// An instance to configure the per-item rule fluently. + public IRuleBuilder RuleForEach(Func?> collectionSelector) + { + ValidationRuleForEach rule = new(collectionSelector); + _rules.Add(rule); + return rule; + } + + /// + /// Validates the specified request instance against all defined rules. + /// + /// The request instance to validate. + /// A list of validation errors. If the instance is valid, the list will be empty. + public List Validate(TRequest instance) + { + List errors = []; + + foreach (IValidationRule rule in _rules) + errors.AddRange(rule.Validate(instance)); + + return errors; + } +} diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs b/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs new file mode 100644 index 00000000..771dcf73 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using System; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Validation; + +/// +/// Provides a fluent API for building validation rules for commands and queries. +/// +/// The type of the request (command or query) being validated. +/// The type of the specific property on the request that the rule applies to. +public interface IRuleBuilder +{ + /// + /// Specifies a condition that the property must satisfy to be considered valid. + /// + /// A function to test the property value. + /// The current instance for method chaining. + IRuleBuilder Must(Func predicate); + + /// + /// Specifies a condition that both the request instance and the property value must satisfy to be considered valid. + /// + /// A function to test the request instance together with the property value. + /// The current instance for method chaining. + IRuleBuilder Must(Func predicate); + + /// + /// Specifies a condition that must be met for the validation rule to be executed. + /// + /// A function evaluating the request instance. + /// The current instance for method chaining. + IRuleBuilder When(Func condition); + + /// + /// Specifies a custom object to be returned when the validation fails. + /// + /// The specific error to return upon failure. + /// The current instance for method chaining. + IRuleBuilder WithError(Error error); + + /// + /// Defines nested validation rules for the complex property being validated. + /// + /// An action used to configure the inline validator for the property. + /// The current instance for method chaining. + IRuleBuilder ChildRules(Action> configure); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/IValidationRule.cs b/src/Lumina.Application/Common/Infrastructure/Validation/IValidationRule.cs new file mode 100644 index 00000000..a914dfd2 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Validation/IValidationRule.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Validation; + +/// +/// Interface for triggering commands and queries validator evaluation. +/// +/// The type of the request (command or query) being evaluated. +internal interface IValidationRule +{ + /// + /// Evaluates the validation rule against the specified request instance. + /// + /// The request instance to validate. + /// The s produced by this rule; empty if the rule passes. + IEnumerable Validate(TRequest instance); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/IValidator.cs b/src/Lumina.Application/Common/Infrastructure/Validation/IValidator.cs new file mode 100644 index 00000000..59467cb7 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Validation/IValidator.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Validation; + +/// +/// Interface for validating requests of commands and queries. +/// +/// The type of the request (command or query) to be validated. +public interface IValidator +{ + /// + /// Validates the specified request instance against the defined rules. + /// + /// The request instance to validate. + /// A list of validation errors. If the instance is valid, the list will be empty. + List Validate(TRequest instance); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/InlineValidator.cs b/src/Lumina.Application/Common/Infrastructure/Validation/InlineValidator.cs new file mode 100644 index 00000000..0a58b385 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Validation/InlineValidator.cs @@ -0,0 +1,12 @@ +#region ========================================================================= USING ===================================================================================== +#endregion + +namespace Lumina.Application.Common.Infrastructure.Validation; + +/// +/// Concrete used to declare validation rules inline for nested complex properties. +/// +/// The type of the request (command or query) to be validated. +public class InlineValidator : AbstractValidator +{ +} diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs new file mode 100644 index 00000000..fc07a557 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs @@ -0,0 +1,156 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Validation; + +/// +/// Defines a validation rule for commands and queries that evaluates a specific property of a request. +/// +/// The type of the request (command or query) being validated. +/// The type of the specific property on the request that the rule applies to. +internal sealed class ValidationRule : IValidationRule, IRuleBuilder +{ + private readonly Func _propertySelector; + + // Predicates and their errors are kept in two parallel lists (rather than a single list of tuples) + // so that Must() can append cheaply and WithError() can patch the *last* entry by index, without + // having to rebuild a composite struct each time. + private readonly List> _predicates = []; + private readonly List _predicateErrors = []; + + // instance-aware predicates get their own separate pair of lists instead of being merged into the + // lists above, because they have a different delegate signature (TRequest, TProperty) vs (TProperty). + // Keeping them separate avoids wrapping every plain predicate in an adapter, just to fit one shape. + private readonly List> _instanceAwarePredicates = []; + private readonly List _instanceAwarePredicateErrors = []; + + private Error currentError = Error.Validation(); + private Func? condition; + + // Tracks which list WithError() should patch, since it doesn't know on its own whether the + // most recent Must() call went to the plain-predicate list or the instance-aware list. + private bool lastAddedPredicateIsInstanceAware; + + private AbstractValidator? _childValidator; + + /// + /// Initializes a new instance of the class. + /// + /// A function that extracts the property value from the request instance. + public ValidationRule(Func propertySelector) + { + _propertySelector = propertySelector; + } + + /// + /// Adds a condition that the property must satisfy to be considered valid. + /// + /// A function to test the property value. + /// The current instance for method chaining. + public IRuleBuilder Must(Func predicate) + { + _predicates.Add(predicate); + // Every predicate is paired with whatever error is "current" at the time it's added, so that a + // subsequent WithError() call has something concrete to overwrite via index lookup. + _predicateErrors.Add(currentError); + lastAddedPredicateIsInstanceAware = false; + return this; + } + + /// + /// Adds a condition that the request instance together with the property must satisfy to be considered valid. + /// + /// A function to test the request instance together with the property value. + /// The current instance for method chaining. + public IRuleBuilder Must(Func predicate) + { + // This overload exists for cross-field rules (e.g. "EndDate must be after StartDate") where + // the check can't be expressed from the property value alone and needs the whole request. + _instanceAwarePredicates.Add(predicate); + _instanceAwarePredicateErrors.Add(currentError); + lastAddedPredicateIsInstanceAware = true; + return this; + } + + /// + /// Specifies a condition that must be met for the validation rule to be executed. + /// + /// A function evaluating the request instance. + /// The current instance for method chaining. + public IRuleBuilder When(Func condition) + { + this.condition = condition; + return this; + } + + /// + /// Specifies a custom object to be returned when the validation fails. + /// + /// The specific error to return upon failure. + /// The current instance for method chaining. + public IRuleBuilder WithError(Error error) + { + // Callers might pass in an error created with the wrong factory (e.g. Error.NotFound()) by mistake. + // Rebuilding it as Error.Validation() here guarantees every error surfaced by this class is + // consistently typed as a validation error, regardless of what the caller supplied. + Error validationError = Error.Validation(description: error.Description); + currentError = validationError; + + // WithError() is meant to apply to the predicate that was *just* added via Must(), not to all + // predicates registered so far. Since Must() can target either parallel-list pair, we use the + // flag set by the last Must() call to figure out which list's last slot to overwrite. + if (lastAddedPredicateIsInstanceAware && _instanceAwarePredicateErrors.Count > 0) + _instanceAwarePredicateErrors[^1] = validationError; + else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0) + _predicateErrors[^1] = validationError; + return this; + } + + /// + /// Defines nested validation rules for the complex property being validated. + /// + /// An action used to configure the inline validator for the property. + /// The current instance for method chaining. + public IRuleBuilder ChildRules(Action> configure) + { + // Lets a rule delegate to a fully separate validator for a complex nested object (e.g. validating + // an Address property's own fields) instead of forcing every nested check to be flattened into + // Must() predicates on this rule. + InlineValidator childValidator = new(); + configure(childValidator); + _childValidator = childValidator; + return this; + } + + /// + /// Evaluates all configured predicates against the specified request instance. + /// + /// The request instance to validate. + /// The of every predicate that fails; empty if the rule passes. + public IEnumerable Validate(TRequest instance) + { + // evaluate the condition first, if it returns false, skip validation entirely. + if (condition is not null && !condition(instance)) + yield break; + + TProperty value = _propertySelector(instance); + + // Deliberately does NOT stop at the first failure: every failing predicate contributes its own error, + // so a caller sees the full set of problems for // this property in one pass instead of having to fix + // and resubmit one error at a time. + for (int index = 0; index < _predicates.Count; index++) + if (!_predicates[index](value)) + yield return _predicateErrors[index]; + + for (int index = 0; index < _instanceAwarePredicates.Count; index++) + if (!_instanceAwarePredicates[index](instance, value)) + yield return _instanceAwarePredicateErrors[index]; + + if (_childValidator is not null && value is not null) + foreach (Error childError in _childValidator.Validate(value)) + yield return childError; + } +} diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs new file mode 100644 index 00000000..4a5e08cc --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Validation; + +/// +/// Defines a validation rule for commands and queries that evaluates each item within a collection property of a request. +/// +/// The type of the request (command or query) being validated. +/// The type of the items in the collection that the rule applies to. +internal sealed class ValidationRuleForEach : IValidationRule, IRuleBuilder +{ + private readonly Func?> _collectionSelector; + private readonly List> _predicates = []; + private readonly List _predicateErrors = []; + private readonly List> _instanceAwarePredicates = []; + private readonly List _instanceAwarePredicateErrors = []; + private Error currentError = Error.Validation(); + private Func? condition; + private bool lastAddedPredicateIsInstanceAware; + private AbstractValidator? _childValidator; + + /// + /// Initializes a new instance of the class. + /// + /// A function that extracts the collection to iterate from the request instance. + public ValidationRuleForEach(Func?> collectionSelector) + { + _collectionSelector = collectionSelector; + } + + /// + /// Adds a condition that each item in the collection must satisfy to be considered valid. + /// + /// A function to test each item value. + /// The current instance for method chaining. + public IRuleBuilder Must(Func predicate) + { + _predicates.Add(predicate); + _predicateErrors.Add(currentError); + lastAddedPredicateIsInstanceAware = false; + return this; + } + + /// + /// Adds a condition that the request instance together with each item must satisfy to be considered valid. + /// + /// A function to test the request instance together with each item value. + /// The current instance for method chaining. + public IRuleBuilder Must(Func predicate) + { + _instanceAwarePredicates.Add(predicate); + _instanceAwarePredicateErrors.Add(currentError); + lastAddedPredicateIsInstanceAware = true; + return this; + } + + /// + /// Specifies a condition that must be met for the validation rule to be executed. + /// + /// A function evaluating the request instance. + /// The current instance for method chaining. + public IRuleBuilder When(Func condition) + { + this.condition = condition; + return this; + } + + /// + /// Specifies a custom object to be returned when the validation fails. + /// + /// The specific error to return upon failure. + /// The current instance for method chaining. + public IRuleBuilder WithError(Error error) + { + // validation rules always produce validation errors, regardless of the error type of the source error + Error validationError = Error.Validation(description: error.Description); + currentError = validationError; + if (lastAddedPredicateIsInstanceAware && _instanceAwarePredicateErrors.Count > 0) + _instanceAwarePredicateErrors[^1] = validationError; + else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0) + _predicateErrors[^1] = validationError; + return this; + } + + /// + /// Defines nested validation rules for each item of the collection being validated. + /// + /// An action used to configure the inline validator for each item. + /// The current instance for method chaining. + public IRuleBuilder ChildRules(Action> configure) + { + InlineValidator childValidator = new(); + configure(childValidator); + _childValidator = childValidator; + return this; + } + + /// + /// Evaluates all configured predicates against each item in the collection. + /// + /// The request instance to validate. + /// One per failing predicate, per item; empty if every item passes. + public IEnumerable Validate(TRequest instance) + { + // evaluate the condition first, if it returns false, skip validation entirely. + if (condition is not null && !condition(instance)) + yield break; + + IEnumerable? collection = _collectionSelector(instance); + if (collection is null) + yield break; + + foreach (TItem item in collection) + { + for (int index = 0; index < _predicates.Count; index++) + if (!_predicates[index](item)) + yield return _predicateErrors[index]; + + for (int index = 0; index < _instanceAwarePredicates.Count; index++) + if (!_instanceAwarePredicates[index](instance, item)) + yield return _instanceAwarePredicateErrors[index]; + + if (_childValidator is not null && item is not null) + foreach (Error childError in _childValidator.Validate(item)) + yield return childError; + } + } +} diff --git a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs new file mode 100644 index 00000000..86912552 --- /dev/null +++ b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs @@ -0,0 +1,326 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using System; +using System.Collections; +using System.Text.RegularExpressions; +#endregion + +namespace Lumina.Application.Common.Utilities; + +/// +/// Validator extension methods for the to define common validation rules. +/// +public static class ValidatorUtilities +{ + /// + /// Defines a validation rule that ensures the integer property is greater than the specified value. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, int valueToCompare) + { + return ruleBuilder.Must(value => value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the nullable integer property is greater than the specified value. + /// + /// + /// If the property is , this rule passes (use to check for missing values). + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, int valueToCompare) + { + return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the decimal property is greater than the specified value. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, decimal valueToCompare) + { + return ruleBuilder.Must(value => value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the nullable decimal property is greater than the specified value. + /// + /// + /// If the property is , this rule passes (use to check for missing values). + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, decimal valueToCompare) + { + return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the time span property is greater than the specified value. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, TimeSpan valueToCompare) + { + return ruleBuilder.Must(value => value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the integer property is greater than or equal to the specified value. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than or equal to. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThanOrEqualTo(this IRuleBuilder ruleBuilder, int valueToCompare) + { + return ruleBuilder.Must(value => value >= valueToCompare); + } + + /// + /// Defines a validation rule that ensures the nullable integer property is greater than or equal to the specified value. + /// + /// + /// If the property is , this rule passes. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than or equal to. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThanOrEqualTo(this IRuleBuilder ruleBuilder, int valueToCompare) + { + return ruleBuilder.Must(value => !value.HasValue || value.Value >= valueToCompare); + } + + /// + /// Defines a validation rule that ensures the nullable decimal property is greater than or equal to the specified value. + /// + /// + /// If the property is , this rule passes. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than or equal to. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThanOrEqualTo(this IRuleBuilder ruleBuilder, decimal valueToCompare) + { + return ruleBuilder.Must(value => !value.HasValue || value.Value >= valueToCompare); + } + + /// + /// Defines a validation rule that ensures the property is not . + /// + /// + /// This rule checks reference/nullable-value nullness only. Combine with + /// to also reject empty values. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// The current instance for method chaining. + public static IRuleBuilder NotNull(this IRuleBuilder ruleBuilder) + { + return ruleBuilder.Must(value => value is not null); + } + + /// + /// Defines a validation rule that ensures the property is not empty. + /// + /// + /// This rule is type-aware: a is checked for white-space only content, a + /// is checked against , and any is checked for having at least + /// one item. If the property is , this rule fails. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// The current instance for method chaining. + public static IRuleBuilder NotEmpty(this IRuleBuilder ruleBuilder) + { + return ruleBuilder.Must(value => value switch + { + null => false, + string stringValue => stringValue.Trim().Length > 0, + Guid guidValue => guidValue != Guid.Empty, + IEnumerable enumerable => enumerable.GetEnumerator().MoveNext(), + _ => true + }); + } + + /// + /// Defines a validation rule that ensures the value is a defined member of the specified enumeration type. + /// + /// The type of the request being validated. + /// The type of the enumeration. + /// The rule builder instance. + /// The current instance for method chaining. + public static IRuleBuilder IsInEnum(this IRuleBuilder ruleBuilder) where TEnum : struct, Enum + { + return ruleBuilder.Must(value => Enum.IsDefined(value)); + } + + /// + /// Defines a validation rule that ensures a nullable enum value is either or a defined member of the specified enumeration type. + /// + /// The type of the request being validated. + /// The type of the enumeration. + /// The rule builder instance. + /// The current instance for method chaining. + public static IRuleBuilder IsInEnum(this IRuleBuilder ruleBuilder) where TEnum : struct, Enum + { + return ruleBuilder.Must(value => value.HasValue && Enum.IsDefined(value.Value)); + } + + /// + /// Defines a validation rule that ensures the string property does not exceed the specified maximum length. + /// + /// + /// If the property is or not a string, this rule passes. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// The maximum allowed length of the property. + /// The current instance for method chaining. + public static IRuleBuilder MaximumLength(this IRuleBuilder ruleBuilder, int maximumLength) + { + return ruleBuilder.Must(value => value is not string stringValue || stringValue.Length <= maximumLength); + } + + /// + /// Defines a validation rule that ensures the string property is at least the specified minimum length. + /// + /// + /// If the property is or not a string, this rule fails. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// The minimum allowed length of the property. + /// The current instance for method chaining. + public static IRuleBuilder MinimumLength(this IRuleBuilder ruleBuilder, int minimumLength) + { + return ruleBuilder.Must(value => value is string stringValue && stringValue.Length >= minimumLength); + } + + /// + /// Defines a validation rule that ensures the string property has exactly the specified length. + /// + /// + /// If the property is or not a string, this rule fails. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// The exact allowed length of the property. + /// The current instance for method chaining. + public static IRuleBuilder Length(this IRuleBuilder ruleBuilder, int length) + { + return ruleBuilder.Must(value => value is string stringValue && stringValue.Length == length); + } + + /// + /// Defines a validation rule that ensures the string property length is within the specified inclusive range. + /// + /// + /// If the property is or not a string, this rule fails. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// The minimum allowed length of the property. + /// The maximum allowed length of the property. + /// The current instance for method chaining. + public static IRuleBuilder Length(this IRuleBuilder ruleBuilder, int minimumLength, int maximumLength) + { + return ruleBuilder.Must(value => value is string stringValue && stringValue.Length >= minimumLength && stringValue.Length <= maximumLength); + } + + /// + /// Defines a validation rule that ensures the string property matches the specified regular expression pattern. + /// + /// + /// If the property is or not a string, this rule fails (use + /// to skip optional properties). + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// The regular expression pattern the property must match. + /// The current instance for method chaining. + public static IRuleBuilder Matches(this IRuleBuilder ruleBuilder, string regexPattern) + { + return ruleBuilder.Must(value => value is string stringValue && Regex.IsMatch(stringValue, regexPattern)); + } + + /// + /// Defines a validation rule that ensures the string property matches the regular expression pattern selected from the request instance. + /// + /// + /// If the property is or not a string, this rule fails. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// A function that selects the regular expression pattern to match against from the request instance. + /// The current instance for method chaining. + public static IRuleBuilder Matches(this IRuleBuilder ruleBuilder, Func regexPatternSelector) + { + return ruleBuilder.Must((instance, value) => value is string stringValue && Regex.IsMatch(stringValue, regexPatternSelector(instance))); + } + + /// + /// Defines a validation rule that ensures the integer property is within the specified inclusive range. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The minimum allowed value of the property. + /// The maximum allowed value of the property. + /// The current instance for method chaining. + public static IRuleBuilder InclusiveBetween(this IRuleBuilder ruleBuilder, int minimumValue, int maximumValue) + { + return ruleBuilder.Must(value => value >= minimumValue && value <= maximumValue); + } + + /// + /// Defines a validation rule that ensures the nullable integer property is within the specified inclusive range. + /// + /// + /// If the property is , this rule passes (use to check for missing values). + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The minimum allowed value of the property. + /// The maximum allowed value of the property. + /// The current instance for method chaining. + public static IRuleBuilder InclusiveBetween(this IRuleBuilder ruleBuilder, int minimumValue, int maximumValue) + { + return ruleBuilder.Must(value => !value.HasValue || (value.Value >= minimumValue && value.Value <= maximumValue)); + } + + /// + /// Defines a validation rule that ensures the property is equal to another property of the request. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// A function that selects the property the validated property must equal. + /// The current instance for method chaining. + public static IRuleBuilder Equal(this IRuleBuilder ruleBuilder, Func comparisonSelector) + { + return ruleBuilder.Must((instance, value) => Equals(value, comparisonSelector(instance))); + } +} diff --git a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQuery.cs b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQuery.cs index 93184771..3acbe0d2 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQuery.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQuery.cs @@ -1,8 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Authorization; -using Mediator; -using System.Collections.Generic; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions; @@ -10,4 +7,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPer /// /// Query for retrieving the list of authorization permissions. /// -public record GetPermissionsQuery : IRequest>>; +public record GetPermissionsQuery : IQuery; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs index 3b00e28f..c95dddb8 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; @@ -8,7 +9,6 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; -using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -19,7 +19,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPer /// /// Handler for the query to retrieve the list of authorization permissions. /// -public class GetPermissionsQueryHandler : IRequestHandler>> +public class GetPermissionsQueryHandler : IQueryHandler>> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; @@ -41,12 +41,12 @@ public class GetPermissionsQueryHandler : IRequestHandler /// Handles the query to retrieve the list of authorization permissions. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a collection of , or an error message. /// - public async ValueTask>> Handle(GetPermissionsQuery request, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetPermissionsQuery query, CancellationToken cancellationToken) { // only admins can see the list of authorization permissions bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommand.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommand.cs index bdbd33aa..840e75eb 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommand.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommand.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Authorization; -using Mediator; +using Lumina.Application.Common.CQRS; using System; using System.Collections.Generic; using System.Diagnostics; @@ -18,4 +16,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; public record AddRoleCommand( string RoleName, List Permissions -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs index 74c13ceb..ecc324ac 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs @@ -1,14 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; -using Mediator; +using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -19,11 +21,12 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; /// /// Handler for the command to add an authorization role. /// -public class AddRoleCommandHandler : IRequestHandler> +public class AddRoleCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IAuthorizationService _authorizationService; private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. @@ -31,11 +34,13 @@ public class AddRoleCommandHandler : IRequestHandlerInjected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected unit of work for interacting with the data access layer repositories. - public AddRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + /// Injected validator for application validation rules. + public AddRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) { _unitOfWork = unitOfWork; _authorizationService = authorizationService; _currentUserService = currentUserService; + _validator = validator; } /// @@ -46,8 +51,12 @@ public class AddRoleCommandHandler : IRequestHandler /// An containing either a successfully created , or an error message. /// - public async ValueTask> Handle(AddRoleCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(AddRoleCommand request, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(request); + if (validationResult.Count > 0) + return validationResult; + // only admins can create authorization roles bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) @@ -59,13 +68,13 @@ public class AddRoleCommandHandler : IRequestHandler new RolePermissionEntity() + RolePermissions = [.. request.Permissions.Select(permissionId => new RolePermissionEntity() { PermissionId = permissionId, Permission = null!, Role = null!, RoleId = default - }).ToList() + })] }; // save the new role in the repository ErrorOr insertRoleResult = await roleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidator.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidator.cs index a2b2f01f..ab5804db 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidator.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidator.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using System; #endregion @@ -17,14 +18,15 @@ public class AddRoleCommandValidator : AbstractValidator public AddRoleCommandValidator() { RuleFor(x => x.RoleName) - .NotNull().WithMessage(Errors.Authorization.RoleNameCannotBeNull.Description) - .NotEmpty().WithMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description); + .NotNull().WithError(Errors.Authorization.RoleNameCannotBeNull) + .NotEmpty().WithError(Errors.Authorization.RoleNameCannotBeEmpty); RuleFor(x => x.Permissions) - .NotNull().WithMessage(Errors.Authorization.PermissionsListCannotBeNull.Description) - .NotEmpty().WithMessage(Errors.Authorization.PermissionsListCannotBeEmpty.Description); + .NotNull().WithError(Errors.Authorization.PermissionsListCannotBeNull) + .NotEmpty().WithError(Errors.Authorization.PermissionsListCannotBeEmpty); + RuleForEach(x => x.Permissions) - .NotEmpty().WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description); + .NotEmpty().WithError(Errors.Authorization.PermissionIdCannotBeEmpty) + .Must(id => id != Guid.Empty).WithError(Errors.Authorization.PermissionIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommand.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommand.cs index 9cccdad1..af1d3265 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommand.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommand.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Mediator; +using Lumina.Application.Common.CQRS; using System; using System.Diagnostics; #endregion @@ -14,4 +13,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; [DebuggerDisplay("RoleId: {RoleId}")] public record DeleteRoleCommand( Guid RoleId -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs index df10ee28..a4de4b25 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs @@ -1,12 +1,13 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.Authorization; -using Mediator; using System; using System.Collections.Generic; using System.Linq; @@ -21,11 +22,12 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; /// /// Handler for the command to delete an authorization role. /// -public class DeleteRoleCommandHandler : IRequestHandler> +public class DeleteRoleCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IAuthorizationService _authorizationService; private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. @@ -33,21 +35,27 @@ public class DeleteRoleCommandHandler : IRequestHandlerInjected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected unit of work for interacting with the data access layer repositories. - public DeleteRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + /// Injected validator for application validation rules. + public DeleteRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) { _unitOfWork = unitOfWork; _authorizationService = authorizationService; _currentUserService = currentUserService; + _validator = validator; } /// /// Handles the command to delete an authorization role. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async ValueTask> Handle(DeleteRoleCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(DeleteRoleCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + // only admins can delete authorization roles bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) @@ -55,7 +63,7 @@ public class DeleteRoleCommandHandler : IRequestHandler(); - ErrorOr getExistingRoleResult = await roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false); + ErrorOr getExistingRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); if (getExistingRoleResult.IsError) return getExistingRoleResult.Errors; else if (getExistingRoleResult.Value is null) @@ -63,7 +71,7 @@ public class DeleteRoleCommandHandler : IRequestHandler deleteRoleResult = await roleRepository.DeleteByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false); + ErrorOr deleteRoleResult = await roleRepository.DeleteByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); if (deleteRoleResult.IsError) return deleteRoleResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidator.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidator.cs index a64205d5..8c5984d2 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidator.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidator.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using System; #endregion @@ -16,8 +17,8 @@ public class DeleteRoleCommandValidator : AbstractValidator /// public DeleteRoleCommandValidator() { - RuleFor(x => x.RoleId) - .NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description); + RuleFor(command => command.RoleId) + .NotEmpty().WithError(Errors.Authorization.RoleIdCannotBeEmpty) + .Must(id => id != Guid.Empty).WithError(Errors.Authorization.RoleIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs index 98ce2684..0b4fcd67 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Authorization; -using Mediator; +using Lumina.Application.Common.CQRS; using System; using System.Collections.Generic; using System.Diagnostics; @@ -20,4 +18,4 @@ public record UpdateRoleCommand( Guid RoleId, string RoleName, List Permissions -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs index 11ebe913..5534b42b 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs @@ -1,14 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; -using Mediator; +using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -19,11 +21,12 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; /// /// Handler for the command to update an authorization role. /// -public class UpdateRoleCommandHandler : IRequestHandler> +public class UpdateRoleCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IAuthorizationService _authorizationService; private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. @@ -31,23 +34,29 @@ public class UpdateRoleCommandHandler : IRequestHandlerInjected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected unit of work for interacting with the data access layer repositories. - public UpdateRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + /// Injected validator for application validation rules. + public UpdateRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) { _unitOfWork = unitOfWork; _authorizationService = authorizationService; _currentUserService = currentUserService; + _validator = validator; } /// /// Handles the command to update an authorization role. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a successfully updated , or an error message. /// - public async ValueTask> Handle(UpdateRoleCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(UpdateRoleCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + // only admins can update authorization roles bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) @@ -58,9 +67,9 @@ public class UpdateRoleCommandHandler : IRequestHandler new RolePermissionEntity() + Id = command.RoleId, + RoleName = command.RoleName, + RolePermissions = command.Permissions.Select(permissionId => new RolePermissionEntity() { PermissionId = permissionId, Permission = null!, @@ -74,7 +83,7 @@ public class UpdateRoleCommandHandler : IRequestHandler getRoleResult = await roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false); + ErrorOr getRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); if (getRoleResult.IsError) return getRoleResult.Errors; if (getRoleResult.Value is null) diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidator.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidator.cs index 4672ed03..af0253da 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidator.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidator.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using System; #endregion @@ -16,19 +17,20 @@ public class UpdateRoleCommandValidator : AbstractValidator /// public UpdateRoleCommandValidator() { - RuleFor(x => x.RoleId) - .NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description); + RuleFor(command => command.RoleId) + .NotEmpty().WithError(Errors.Authorization.RoleIdCannotBeEmpty) + .Must(id => id != Guid.Empty).WithError(Errors.Authorization.RoleIdCannotBeEmpty); - RuleFor(x => x.RoleName) - .NotNull().WithMessage(Errors.Authorization.RoleNameCannotBeNull.Description) - .NotEmpty().WithMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description); + RuleFor(command => command.RoleName) + .NotNull().WithError(Errors.Authorization.RoleNameCannotBeNull) + .NotEmpty().WithError(Errors.Authorization.RoleNameCannotBeEmpty); - RuleFor(x => x.Permissions) - .NotNull().WithMessage(Errors.Authorization.PermissionsListCannotBeNull.Description) - .NotEmpty().WithMessage(Errors.Authorization.PermissionsListCannotBeEmpty.Description); - RuleForEach(x => x.Permissions) - .NotEmpty().WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description); + RuleFor(command => command.Permissions) + .NotNull().WithError(Errors.Authorization.PermissionsListCannotBeNull) + .NotEmpty().WithError(Errors.Authorization.PermissionsListCannotBeEmpty); + + RuleForEach(command => command.Permissions) + .NotEmpty().WithError(Errors.Authorization.PermissionIdCannotBeEmpty) + .Must(id => id != Guid.Empty).WithError(Errors.Authorization.PermissionIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs index 6050dc46..38202928 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Authorization; -using Mediator; +using Lumina.Application.Common.CQRS; using System; using System.Diagnostics; #endregion @@ -15,4 +13,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermi [DebuggerDisplay("RoleId: {RoleId}")] public record GetRolePermissionsQuery( Guid RoleId -) : IRequest>; +) : IQuery; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs index 7305064c..c1735073 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs @@ -1,14 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; -using Mediator; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -18,11 +20,12 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermi /// /// Handler for the query to retrieve the list of authorization permissions for a role. /// -public class GetRolePermissionsQueryHandler : IRequestHandler> +public class GetRolePermissionsQueryHandler : IQueryHandler> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; private readonly IRoleRepository _roleRepository; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. @@ -30,11 +33,13 @@ public class GetRolePermissionsQueryHandler : IRequestHandlerInjected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected unit of work for interacting with the data access layer repositories. - public GetRolePermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + /// Injected validator for application validation rules. + public GetRolePermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) { _authorizationService = authorizationService; _currentUserService = currentUserService; _roleRepository = unitOfWork.GetRepository(); + _validator = validator; } /// @@ -45,8 +50,12 @@ public class GetRolePermissionsQueryHandler : IRequestHandler /// An containing either a collection of , or an error message. /// - public async ValueTask> Handle(GetRolePermissionsQuery request, CancellationToken cancellationToken) + public async Task> HandleAsync(GetRolePermissionsQuery request, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(request); + if (validationResult.Count > 0) + return validationResult; + // only admins can see the list of authorization roles bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidator.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidator.cs index 107b65d3..565cc7fb 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidator.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidator.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using System; #endregion @@ -17,7 +18,7 @@ public class GetRolePermissionsQueryValidator : AbstractValidator x.RoleId) - .NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description); + .NotEmpty().WithError(Errors.Authorization.RoleIdCannotBeEmpty) + .Must(id => id != Guid.Empty).WithError(Errors.Authorization.RoleIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQuery.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQuery.cs index 6a168b06..df96049a 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQuery.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQuery.cs @@ -1,8 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Authorization; -using Mediator; -using System.Collections.Generic; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; @@ -10,4 +7,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; /// /// Query for retrieving the list of authorization roles. /// -public record GetRolesQuery() : IRequest>>; +public record GetRolesQuery() : IQuery; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs index 405086ac..db716a4b 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; @@ -8,7 +9,6 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; -using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -19,7 +19,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; /// /// Handler for the query to retrieve the list of authorization roles. /// -public class GetRolesQueryHandler : IRequestHandler>> +public class GetRolesQueryHandler : IQueryHandler>> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; @@ -41,12 +41,12 @@ public class GetRolesQueryHandler : IRequestHandler /// Handles the query to retrieve the list of authorization roles. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a collection of , or an error message. /// - public async ValueTask>> Handle(GetRolesQuery request, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetRolesQuery query, CancellationToken cancellationToken) { // only admins can see the list of authorization roles bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs index c4be3e4b..86da3e1c 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs @@ -1,8 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileSystemManagement.Directories; -using Mediator; -using System.Collections.Generic; +using Lumina.Application.Common.CQRS; using System.Diagnostics; #endregion @@ -17,4 +14,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDi public record GetDirectoriesQuery( string? Path, bool IncludeHiddenElements -) : IRequest>>; +) : IQuery; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs index bfda1160..141362f8 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.FileSystemManagement.Directories; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; -using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -15,30 +16,37 @@ namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDi /// /// Handler for the query to get all directories. /// -public class GetDirectoriesQueryHandler : IRequestHandler>> +public class GetDirectoriesQueryHandler : IQueryHandler>> { private readonly IDirectoryService _directoryService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected service for handling directories. - public GetDirectoriesQueryHandler(IDirectoryService directoryService) + /// Injected validator for application validation rules. + public GetDirectoriesQueryHandler(IDirectoryService directoryService, IValidator validator) { _directoryService = directoryService; + _validator = validator; } /// /// Gets the list of directories at the specified path. /// - /// The query containing the requested path. + /// The query containing the requested path. /// Cancellation token that can be used to stop the execution. /// /// An containing either a collection of , or an error message. /// - public ValueTask>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken) + public Task>> HandleAsync(GetDirectoriesQuery query, CancellationToken cancellationToken) { - ErrorOr> getSubdirectoriesResult = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements); - return ValueTask.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return Task.FromResult>>(validationResult); + + ErrorOr> getSubdirectoriesResult = _directoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements); + return Task.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs index f7012600..601823c9 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; #endregion @@ -15,6 +16,8 @@ public class GetDirectoriesQueryValidator : AbstractValidator public GetDirectoriesQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + RuleFor(query => query.Path) + .NotEmpty() + .WithError(Errors.FileSystemManagement.PathCannotBeEmpty); } -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQuery.cs index 74b2c0b0..a9b8cd0a 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQuery.cs @@ -1,8 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Mediator; -using System.Collections.Generic; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; @@ -10,4 +7,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; /// /// Query for retrieving the list of drives. /// -public record GetDrivesQuery() : IRequest>>; \ No newline at end of file +public record GetDrivesQuery() : IQuery; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs index 287c3762..c509b39c 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -15,7 +15,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; /// /// Handler for the query to get all drives. /// -public class GetDrivesQueryHandler : IRequestHandler>> +public class GetDrivesQueryHandler : IQueryHandler>> { private readonly IDriveService _driveService; @@ -31,14 +31,14 @@ public class GetDrivesQueryHandler : IRequestHandler /// Gets the list of file system drives. /// - /// The query containing the requested path. + /// The query containing the requested path. /// Cancellation token that can be used to stop the execution. /// /// An containing either a collection of , or an error message. /// - public ValueTask>> Handle(GetDrivesQuery request, CancellationToken cancellationToken) + public Task>> HandleAsync(GetDrivesQuery query, CancellationToken cancellationToken) { ErrorOr> getDrivesResult = _driveService.GetDrives(); - return ValueTask.FromResult(getDrivesResult.Match(values => ErrorOrFactory.From(values.ToTreeNodeResponses()), errors => errors)); + return Task.FromResult(getDrivesResult.Match(values => ErrorOrFactory.From(values.ToTreeNodeResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQuery.cs index 512394b6..3ac8ace4 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQuery.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; -using Mediator; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; @@ -8,4 +7,4 @@ namespace Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFil /// /// Query for retrieving the file system type. /// -public record GetFileSystemQuery() : IRequest; +public record GetFileSystemQuery() : IQuery; diff --git a/src/Lumina.Application/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandler.cs index 255cafcd..3abb1c43 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandler.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; -using Mediator; using System.Threading; using System.Threading.Tasks; #endregion @@ -11,7 +11,7 @@ namespace Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFil /// /// Handler for the query to get the file system type. /// -public class GetFileSystemQueryHandler : IRequestHandler +public class GetFileSystemQueryHandler : IQueryHandler { private readonly IPlatformContext _platformContext; @@ -27,11 +27,11 @@ public class GetFileSystemQueryHandler : IRequestHandler /// Gets the type of the file system. /// - /// The query to be handled. + /// The query to be handled. /// Cancellation token that can be used to stop the execution. /// The type of the file system. - public ValueTask Handle(GetFileSystemQuery request, CancellationToken cancellationToken) + public Task HandleAsync(GetFileSystemQuery query, CancellationToken cancellationToken) { - return ValueTask.FromResult(new FileSystemTypeResponse(_platformContext.Platform)); + return Task.FromResult(new FileSystemTypeResponse(_platformContext.Platform)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQuery.cs index 52fc745b..b5351d79 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQuery.cs @@ -1,8 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileSystemManagement.Files; -using Mediator; -using System.Collections.Generic; +using Lumina.Application.Common.CQRS; using System.Diagnostics; #endregion @@ -17,4 +14,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; public record GetFilesQuery( string? Path, bool IncludeHiddenElements -) : IRequest>>; +) : IQuery; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs index 2f37dfa6..45d78a98 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Files; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.FileSystemManagement.Files; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -15,30 +16,37 @@ namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; /// /// Handler for the query to get all files. /// -public class GetFilesQueryHandler : IRequestHandler>> +public class GetFilesQueryHandler : IQueryHandler>> { private readonly IFileService _fileService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected service for handling files. - public GetFilesQueryHandler(IFileService fileService) + /// Injected validator for application validation rules. + public GetFilesQueryHandler(IFileService fileService, IValidator validator) { _fileService = fileService; + _validator = validator; } /// /// Gets the list of files at the specified path. /// - /// The query containing the requested path. + /// The query containing the requested path. /// Cancellation token that can be used to stop the execution. /// /// An containing either a collection of , or an error message. /// - public ValueTask>> Handle(GetFilesQuery request, CancellationToken cancellationToken) + public Task>> HandleAsync(GetFilesQuery query, CancellationToken cancellationToken) { - ErrorOr> getFilesResult = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements); - return ValueTask.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return Task.FromResult>>(validationResult); + + ErrorOr> getFilesResult = _fileService.GetFiles(query.Path!, query.IncludeHiddenElements); + return Task.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidator.cs index 0e1a77ce..3315dd6f 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; #endregion @@ -15,6 +16,8 @@ public class GetFilesQueryValidator : AbstractValidator /// public GetFilesQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + RuleFor(query => query.Path) + .NotEmpty() + .WithError(Errors.FileSystemManagement.PathCannotBeEmpty); } -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs index b31a5645..452debc6 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs @@ -1,8 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Mediator; -using System.Collections.Generic; +using Lumina.Application.Common.CQRS; using System.Diagnostics; #endregion @@ -17,4 +14,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFile public record GetTreeFilesQuery( string? Path, bool IncludeHiddenElements -) : IRequest>>; +) : IQuery; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs index 7bdd0799..68651cd0 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Files; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -15,30 +16,37 @@ namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFile /// /// Handler for the query to get all files. /// -public class GetTreeFilesQueryHandler : IRequestHandler>> +public class GetTreeFilesQueryHandler : IQueryHandler>> { private readonly IFileService _fileService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected service for handling files. - public GetTreeFilesQueryHandler(IFileService fileService) + /// Injected validator for application validation rules. + public GetTreeFilesQueryHandler(IFileService fileService, IValidator validator) { _fileService = fileService; + _validator = validator; } /// /// Gets the list of files at the specified path. /// - /// The query containing the requested path. + /// The query containing the requested path. /// Cancellation token that can be used to stop the execution. /// /// An containing either a collection of , or an error message. /// - public ValueTask>> Handle(GetTreeFilesQuery request, CancellationToken cancellationToken) + public Task>> HandleAsync(GetTreeFilesQuery query, CancellationToken cancellationToken) { - ErrorOr> getFilesResult = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements); - return ValueTask.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors)); + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return Task.FromResult>>(validationResult); + + ErrorOr> getFilesResult = _fileService.GetFiles(query.Path!, query.IncludeHiddenElements); + return Task.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidator.cs index efbedf60..30c51e7f 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; #endregion @@ -15,6 +16,8 @@ public class GetTreeFilesQueryValidator : AbstractValidator /// public GetTreeFilesQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + RuleFor(query => query.Path) + .NotEmpty() + .WithError(Errors.FileSystemManagement.PathCannotBeEmpty); } -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommand.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommand.cs index 56330289..1a9e66bc 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommand.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommand.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileSystemManagement.Path; -using Mediator; +using Lumina.Application.Common.CQRS; using System.Diagnostics; #endregion @@ -16,4 +14,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePat public record CombinePathCommand( string? OriginalPath, string? NewPath -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs index 00bd0d7c..b6d6e233 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs @@ -1,9 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Mediator; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -13,30 +15,37 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePat /// /// Handler for the command to split a file system path. /// -public class CombinePathCommandHandler : IRequestHandler> +public class CombinePathCommandHandler : ICommandHandler> { private readonly IPathService _pathService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected service for handling file system paths. - public CombinePathCommandHandler(IPathService pathService) + /// Injected validator for application validation rules. + public CombinePathCommandHandler(IPathService pathService, IValidator validator) { _pathService = pathService; + _validator = validator; } /// /// Combines two file system paths. /// - /// The command containing the requested paths. + /// The command containing the requested paths. /// Cancellation token that can be used to stop the execution. /// /// An containing either a , or an error message. /// - public ValueTask> Handle(CombinePathCommand request, CancellationToken cancellationToken) + public Task> HandleAsync(CombinePathCommand command, CancellationToken cancellationToken) { - ErrorOr combinePathResult = _pathService.CombinePath(request.OriginalPath!, request.NewPath!); - return ValueTask.FromResult(combinePathResult.Match(values => ErrorOrFactory.From(new PathSegmentResponse(combinePathResult.Value)), errors => errors)); + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return Task.FromResult>(validationResult); + + ErrorOr combinePathResult = _pathService.CombinePath(command.OriginalPath!, command.NewPath!); + return Task.FromResult(combinePathResult.Match(values => ErrorOrFactory.From(new PathSegmentResponse(combinePathResult.Value)), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandValidator.cs index 4d02f302..bfc496d9 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; #endregion @@ -15,7 +16,12 @@ public class CombinePathCommandValidator : AbstractValidator /// public CombinePathCommandValidator() { - RuleFor(x => x.OriginalPath).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); - RuleFor(x => x.NewPath).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + RuleFor(command => command.OriginalPath) + .NotEmpty() + .WithError(Errors.FileSystemManagement.PathCannotBeEmpty); + + RuleFor(command => command.NewPath) + .NotEmpty() + .WithError(Errors.FileSystemManagement.PathCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommand.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommand.cs index bc211fe8..07e1ac7d 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommand.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommand.cs @@ -1,8 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileSystemManagement.Path; -using Mediator; -using System.Collections.Generic; +using Lumina.Application.Common.CQRS; using System.Diagnostics; #endregion @@ -15,4 +12,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; [DebuggerDisplay("Path: {Path}")] public record SplitPathCommand( string? Path -) : IRequest>>; +) : ICommand; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs index 48f1675f..28332339 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -15,30 +16,37 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; /// /// Handler for the command to split a file system path. /// -public class SplitPathCommandHandler : IRequestHandler>> +public class SplitPathCommandHandler : ICommandHandler>> { private readonly IPathService _pathService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected service for handling file system paths. - public SplitPathCommandHandler(IPathService pathService) + /// Injected validator for application validation rules. + public SplitPathCommandHandler(IPathService pathService, IValidator validator) { _pathService = pathService; + _validator = validator; } /// /// Gets the path components of the specified path. /// - /// The command containing the requested path. + /// The command containing the requested path. /// Cancellation token that can be used to stop the execution. /// /// An containing either a collection of , or an error message. /// - public ValueTask>> Handle(SplitPathCommand request, CancellationToken cancellationToken) + public Task>> HandleAsync(SplitPathCommand command, CancellationToken cancellationToken) { - ErrorOr> parsePathResult = _pathService.ParsePath(request.Path!); - return ValueTask.FromResult(parsePathResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return Task.FromResult>>(validationResult); + + ErrorOr> parsePathResult = _pathService.ParsePath(command.Path!); + return Task.FromResult(parsePathResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandValidator.cs index 897c6e4d..001852f1 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; #endregion @@ -15,6 +16,8 @@ public class SplitPathCommandValidator : AbstractValidator /// public SplitPathCommandValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + RuleFor(command => command.Path) + .NotEmpty() + .WithError(Errors.FileSystemManagement.PathCannotBeEmpty); } -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs index 9c3db95b..02ce1e37 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileSystemManagement.Path; -using Mediator; +using Lumina.Application.Common.CQRS; using System.Diagnostics; #endregion @@ -16,4 +14,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathEx public record CheckPathExistsQuery( string? Path, bool IncludeHiddenElements -) : IRequest>; +) : IQuery; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs index df02b2eb..228cb273 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Mediator; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -12,29 +14,36 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathEx /// /// Handler for the query to check the existence a file system path. /// -public class CheckPathExistsQueryHandler : IRequestHandler> +public class CheckPathExistsQueryHandler : IQueryHandler> { private readonly IPathService _pathService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected service for managing file system paths. - public CheckPathExistsQueryHandler(IPathService pathService) + /// Injected validator for application validation rules. + public CheckPathExistsQueryHandler(IPathService pathService, IValidator validator) { _pathService = pathService; + _validator = validator; } /// /// Checks the existence of the specified file system path. /// - /// The query containing the request. + /// The query containing the request. /// Cancellation token that can be used to stop the execution. /// /// An containing either if the specified path exists, if it doesn't, or an error message. /// - public ValueTask> Handle(CheckPathExistsQuery request, CancellationToken cancellationToken) + public Task> HandleAsync(CheckPathExistsQuery query, CancellationToken cancellationToken) { - return ValueTask.FromResult(ErrorOrFactory.From(new PathExistsResponse(_pathService.Exists(request.Path!, request.IncludeHiddenElements)))); + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return Task.FromResult>(validationResult); + + return Task.FromResult(ErrorOrFactory.From(new PathExistsResponse(_pathService.Exists(query.Path!, query.IncludeHiddenElements)))); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidator.cs index 0cca72a6..f943d41b 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; #endregion @@ -15,6 +16,8 @@ public class CheckPathExistsQueryValidator : AbstractValidator public CheckPathExistsQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + RuleFor(query => query.Path) + .NotEmpty() + .WithError(Errors.FileSystemManagement.PathCannotBeEmpty); } -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQuery.cs index 6be2d6fc..40c35738 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQuery.cs @@ -1,8 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileSystemManagement.Path; -using Mediator; -using System.Collections.Generic; +using Lumina.Application.Common.CQRS; using System.Diagnostics; #endregion @@ -15,4 +12,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathPare [DebuggerDisplay("Path: {Path}")] public record GetPathParentQuery( string? Path -) : IRequest>>; +) : IQuery; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs index f17ef062..46c0216d 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -15,30 +16,37 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathPare /// /// Handler for the query to get the parent of a file system path. /// -public class GetPathParentQueryHandler : IRequestHandler>> +public class GetPathParentQueryHandler : IQueryHandler>> { private readonly IPathService _pathService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected service for managing file system paths. - public GetPathParentQueryHandler(IPathService pathService) + /// Injected validator for application validation rules. + public GetPathParentQueryHandler(IPathService pathService, IValidator validator) { _pathService = pathService; + _validator = validator; } /// /// Gets the parent of the specified file system path. /// - /// The query containing the requested path. + /// The query containing the requested path. /// Cancellation token that can be used to stop the execution. /// /// An containing either a collection of , or an error message. /// - public ValueTask>> Handle(GetPathParentQuery request, CancellationToken cancellationToken) + public Task>> HandleAsync(GetPathParentQuery query, CancellationToken cancellationToken) { - ErrorOr> goUpOneLevelResult = _pathService.GoUpOneLevel(request.Path!); - return ValueTask.FromResult(goUpOneLevelResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return Task.FromResult>>(validationResult); + + ErrorOr> goUpOneLevelResult = _pathService.GoUpOneLevel(query.Path!); + return Task.FromResult(goUpOneLevelResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidator.cs index c74379da..b1b903e1 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; #endregion @@ -15,6 +16,8 @@ public class GetPathParentQueryValidator : AbstractValidator /// public GetPathParentQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + RuleFor(query => query.Path) + .NotEmpty() + .WithError(Errors.FileSystemManagement.PathCannotBeEmpty); } -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQuery.cs index e3822cfc..0a18a626 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQuery.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileSystemManagement.Path; -using Mediator; +using Lumina.Application.Common.CQRS; using System.Diagnostics; #endregion @@ -14,4 +12,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot [DebuggerDisplay("Path: {Path}")] public record GetPathRootQuery( string? Path -) : IRequest>; +) : IQuery; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs index 98732e01..b9a57317 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Mediator; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -14,28 +16,35 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot /// /// Handler for the query to get the root of a file system path. /// -public class GetPathRootQueryHandler : IRequestHandler> +public class GetPathRootQueryHandler : IQueryHandler> { private readonly IPathService _pathService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected service for managing file system paths. - public GetPathRootQueryHandler(IPathService pathService) + /// Injected validator for application validation rules. + public GetPathRootQueryHandler(IPathService pathService, IValidator validator) { _pathService = pathService; + _validator = validator; } /// /// Gets the root of the specified file system path. /// - /// The query containing the requested path. + /// The query containing the requested path. /// Cancellation token that can be used to stop the execution. /// An containing either the root of the specified path, or an error. - public ValueTask> Handle(GetPathRootQuery request, CancellationToken cancellationToken) + public Task> HandleAsync(GetPathRootQuery query, CancellationToken cancellationToken) { - ErrorOr getPathRootResult = _pathService.GetPathRoot(request.Path!); - return ValueTask.FromResult(getPathRootResult.Match(values => ErrorOrFactory.From(values.ToResponse()), errors => errors)); + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return Task.FromResult>(validationResult); + + ErrorOr getPathRootResult = _pathService.GetPathRoot(query.Path!); + return Task.FromResult(getPathRootResult.Match(values => ErrorOrFactory.From(values.ToResponse()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidator.cs index a3b6043a..d7d81acb 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; #endregion @@ -15,6 +16,8 @@ public class GetPathRootQueryValidator : AbstractValidator /// public GetPathRootQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + RuleFor(query => query.Path) + .NotEmpty() + .WithError(Errors.FileSystemManagement.PathCannotBeEmpty); } -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQuery.cs index e8c318f6..496af4e6 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQuery.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileSystemManagement.Path; -using Mediator; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSeparator; @@ -8,4 +7,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSepa /// /// Query for retrieving the file system path separator. /// -public record GetPathSeparatorQuery() : IRequest; \ No newline at end of file +public record GetPathSeparatorQuery() : IQuery; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQueryHandler.cs index e57fc0b9..27bd46c9 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQueryHandler.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Mediator; using System.Threading; using System.Threading.Tasks; #endregion @@ -11,7 +11,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSepa /// /// Handler for the query to get the path separator character of a file system path. /// -public class GetPathSeparatorQueryHandler : IRequestHandler +public class GetPathSeparatorQueryHandler : IQueryHandler { private readonly IPathService _pathService; @@ -27,11 +27,11 @@ public class GetPathSeparatorQueryHandler : IRequestHandler /// Gets the path separator character of a file system path. /// - /// The query containing the request. + /// The query containing the request. /// Cancellation token that can be used to stop the execution. /// The file system path separator character. - public ValueTask Handle(GetPathSeparatorQuery request, CancellationToken cancellationToken) + public Task HandleAsync(GetPathSeparatorQuery query, CancellationToken cancellationToken) { - return ValueTask.FromResult(new PathSeparatorResponse(_pathService.PathSeparator.ToString())); + return Task.FromResult(new PathSeparatorResponse(_pathService.PathSeparator.ToString())); } } \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQuery.cs index c1e35376..f9c6dd0e 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQuery.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileSystemManagement.Path; -using Mediator; +using Lumina.Application.Common.CQRS; using System.Diagnostics; #endregion @@ -13,4 +12,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePat [DebuggerDisplay("Path: {Path}")] public record ValidatePathQuery( string? Path -) : IRequest; +) : IQuery; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandler.cs index 3553ade7..b53f1aa3 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandler.cs @@ -1,7 +1,10 @@ #region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Mediator; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -11,29 +14,36 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePat /// /// Handler for the query to validate a file system path. /// -public class ValidatePathQueryHandler : IRequestHandler +public class ValidatePathQueryHandler : IQueryHandler> { private readonly IPathService _pathService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected service for managing file system paths. - public ValidatePathQueryHandler(IPathService pathService) + /// Injected validator for application validation rules. + public ValidatePathQueryHandler(IPathService pathService, IValidator validator) { _pathService = pathService; + _validator = validator; } /// /// Validates the specified file system path. /// - /// The query containing the request. + /// The query containing the request. /// Cancellation token that can be used to stop the execution. /// - /// if the specified path is valid, otherwise. + /// An containing either if the specified path is valid, if it isn't, or an error message. /// - public ValueTask Handle(ValidatePathQuery request, CancellationToken cancellationToken) + public Task> HandleAsync(ValidatePathQuery query, CancellationToken cancellationToken) { - return ValueTask.FromResult(new PathValidResponse(_pathService.IsValidPath(request.Path!))); + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return Task.FromResult>(validationResult); + + return Task.FromResult(ErrorOrFactory.From(new PathValidResponse(_pathService.IsValidPath(query.Path!)))); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidator.cs index 7740d025..747a33d0 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; #endregion @@ -15,6 +16,8 @@ public class ValidatePathQueryValidator : AbstractValidator /// public ValidatePathQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + RuleFor(query => query.Path) + .NotEmpty() + .WithError(Errors.FileSystemManagement.PathCannotBeEmpty); } -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQuery.cs index 9b658739..3e8699fb 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQuery.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; -using Mediator; +using Lumina.Application.Common.CQRS; using System.Diagnostics; #endregion @@ -16,4 +14,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThu public record GetThumbnailQuery( string? Path, int Quality -) : IRequest>; +) : IQuery; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs index 1c884438..a7d2072c 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Mediator; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -14,28 +16,35 @@ namespace Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThu /// /// Handler for the query to get the file thumbnail. /// -public class GetThumbnailQueryHandler : IRequestHandler> +public class GetThumbnailQueryHandler : IQueryHandler> { private readonly IThumbnailService _thumbnailsService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected service for handling thumbnails. - public GetThumbnailQueryHandler(IThumbnailService thumbnailsService) + /// Injected validator for application validation rules. + public GetThumbnailQueryHandler(IThumbnailService thumbnailsService, IValidator validator) { _thumbnailsService = thumbnailsService; + _validator = validator; } /// /// Gets the thumbnail for a file located at the specified path, with the specified quality. /// - /// The query to be handled. + /// The query to be handled. /// Cancellation token that can be used to stop the execution. /// An containing either a thumbnail, or an error. - public async ValueTask> Handle(GetThumbnailQuery request, CancellationToken cancellationToken) + public async Task> HandleAsync(GetThumbnailQuery query, CancellationToken cancellationToken) { - ErrorOr getThumbnailResult = await _thumbnailsService.GetThumbnailAsync(request.Path!, request.Quality, cancellationToken); + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + ErrorOr getThumbnailResult = await _thumbnailsService.GetThumbnailAsync(query.Path!, query.Quality, cancellationToken); return await ValueTask.FromResult(getThumbnailResult.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs index c43cd478..37255df8 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; #endregion @@ -15,7 +16,12 @@ public class GetThumbnailQueryValidator : AbstractValidator /// public GetThumbnailQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); - RuleFor(x => x.Quality).InclusiveBetween(0, 100).WithMessage(Errors.Thumbnails.ImageQualityMustBeBetweenZeroAndOneHundred.Description); + RuleFor(query => query.Path) + .NotEmpty() + .WithError(Errors.FileSystemManagement.PathCannotBeEmpty); + + RuleFor(query => query.Quality) + .InclusiveBetween(0, 100) + .WithError(Errors.Thumbnails.ImageQualityMustBeBetweenZeroAndOneHundred); } } diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommand.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommand.cs index 8d9c161a..dc384283 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommand.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommand.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Authentication; -using Mediator; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; @@ -18,4 +16,4 @@ public record SetupApplicationCommand( string? Password, string? PasswordConfirm, bool Use2fa -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs index 428beefe..c80d4889 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.Seed; @@ -8,8 +9,8 @@ using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.Authentication; -using Mediator; using System; using System.Collections.Generic; using System.Linq; @@ -22,7 +23,7 @@ namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApp /// /// Handler for the command to perform the initial application setup. /// -public class SetupApplicationCommandHandler : IRequestHandler> +public class SetupApplicationCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IPasswordHashService _hashService; @@ -31,6 +32,7 @@ public class SetupApplicationCommandHandler : IRequestHandler _validator; /// /// Initializes a new instance of the class. @@ -42,6 +44,7 @@ public class SetupApplicationCommandHandler : IRequestHandlerInjected service for generating QR codes. /// Injected service for time related concerns. /// Injected service for the initial persistence medium data seed. + /// Injected validator for application validation rules. public SetupApplicationCommandHandler( IUnitOfWork unitOfWork, IPasswordHashService hashService, @@ -49,7 +52,8 @@ public class SetupApplicationCommandHandler : IRequestHandler validator) { _unitOfWork = unitOfWork; _hashService = hashService; @@ -58,18 +62,23 @@ public class SetupApplicationCommandHandler : IRequestHandler /// Handles the command to perform the initial application setup. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a successfully created , or an error message. /// - public async ValueTask> Handle(SetupApplicationCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(SetupApplicationCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + // check if any users already exists (admin account is only set once!) IUserRepository userRepository = _unitOfWork.GetRepository(); ErrorOr> selectUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); @@ -83,8 +92,8 @@ public class SetupApplicationCommandHandler : IRequestHandler public SetupApplicationCommandValidator() { - RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); - RuleFor(x => x.Password).NotEmpty().WithMessage(Errors.Authentication.PasswordCannotBeEmpty.Description) - .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description); - RuleFor(x => x.PasswordConfirm).NotEmpty().WithMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); - RuleFor(x => x.Password).Equal(x => x.PasswordConfirm).WithMessage(Errors.Authentication.PasswordsNotMatch.Description); + RuleFor(command => command.Username) + .NotEmpty() + .WithError(Errors.Authentication.UsernameCannotBeEmpty); + + RuleFor(command => command.Password) + .NotEmpty() + .WithError(Errors.Authentication.PasswordCannotBeEmpty) + .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$") + .WithError(Errors.Authentication.InvalidPassword); + + RuleFor(command => command.PasswordConfirm) + .NotEmpty() + .WithError(Errors.Authentication.PasswordConfirmCannotBeEmpty); + + RuleFor(command => command.Password) + .Equal(command => command.PasswordConfirm) + .WithError(Errors.Authentication.PasswordsNotMatch); } } diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQuery.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQuery.cs index 3400a137..6177e3c3 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQuery.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQuery.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.UsersManagement; -using Mediator; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; @@ -8,4 +7,4 @@ namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInit /// /// Query for checking the initialization of the application. /// -public record CheckInitializationQuery() : IRequest; +public record CheckInitializationQuery() : IQuery; diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs index 4ef82f25..6eec60bf 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Contracts.Responses.UsersManagement; -using Mediator; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -16,7 +16,7 @@ namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInit /// /// Handler for the query to check the initialization of the application. /// -public class CheckInitializationQueryHandler : IRequestHandler +public class CheckInitializationQueryHandler : IQueryHandler { private readonly IUnitOfWork _unitOfWork; @@ -31,12 +31,12 @@ public class CheckInitializationQueryHandler : IRequestHandler /// Checks the initialization status of the application. /// - /// The query containing the request. + /// The query containing the request. /// Cancellation token that can be used to stop the execution. /// /// if the application is initialized (the admin account is created), otherwise. /// - public async ValueTask Handle(CheckInitializationQuery request, CancellationToken cancellationToken) + public async Task HandleAsync(CheckInitializationQuery query, CancellationToken cancellationToken) { IUserRepository userRepository = _unitOfWork.GetRepository(); // if the repository reports an error, or there are no users, the application has not been initialized diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs index d520d53a..a9345eca 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.MediaLibrary.Management; -using Mediator; +using Lumina.Application.Common.CQRS; using System; using System.Diagnostics; #endregion @@ -31,4 +29,4 @@ public record AddLibraryCommand( bool DownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs index 36f8bbcc..7ce6ce44 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -1,11 +1,13 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; @@ -16,8 +18,8 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Mediator; using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -29,13 +31,14 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; /// /// Handler for the command to add a media library. /// -public class AddLibraryCommandHandler : IRequestHandler> +public class AddLibraryCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; private readonly IDomainEventsQueue _domainEventsQueue; private readonly IEnvironmentContext _environmentContext; private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. @@ -45,30 +48,36 @@ public class AddLibraryCommandHandler : IRequestHandlerInjected service for the queue of domain events. /// Injected facade service for environment contextual services. /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. public AddLibraryCommandHandler( IAuthorizationService authorizationService, ICurrentUserService currentUserService, IDomainEventsQueue domainEventsQueue, IEnvironmentContext environmentContext, - IUnitOfWork unitOfWork) + IUnitOfWork unitOfWork, + IValidator validator) { _unitOfWork = unitOfWork; _currentUserService = currentUserService; _domainEventsQueue = domainEventsQueue; _environmentContext = environmentContext; _authorizationService = authorizationService; + _validator = validator; } /// /// Handles the command to add a media library. /// - /// The request to be handled. + /// The command to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a successfully created , or an error message. /// - public async ValueTask> Handle(AddLibraryCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(AddLibraryCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; // if the user that made the request is not an Admin or they don't have the permission to manage media libraries, they do not have the right to create it if (!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false) && @@ -76,9 +85,9 @@ public class AddLibraryCommandHandler : IRequestHandler fileSystemPathIdResult = FileSystemPathId.Create(request.CoverImage); + ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage); if (fileSystemPathIdResult.IsError) return fileSystemPathIdResult.Errors; @@ -92,15 +101,15 @@ public class AddLibraryCommandHandler : IRequestHandler createLibraryResult = Library.Create( UserId.Create(_currentUserService.UserId!.Value), - request.Title!, - Enum.Parse(request.LibraryType!), - request.ContentLocations!, - request.CoverImage, - request.IsEnabled, - request.IsLocked, - request.DownloadMetadataFromWeb, - request.ShouldSaveMetadataInMediaDirectories, - request.ShouldSkipUnchangedDirectoriesDuringScan, + command.Title!, + Enum.Parse(command.LibraryType!), + command.ContentLocations!, + command.CoverImage, + command.IsEnabled, + command.IsLocked, + command.DownloadMetadataFromWeb, + command.ShouldSaveMetadataInMediaDirectories, + command.ShouldSkipUnchangedDirectoriesDuringScan, [] ); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs index 8a82e5cf..8e6f0bc2 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.SharedKernel.Common.Errors; using System; @@ -17,21 +18,28 @@ public class AddLibraryCommandValidator : AbstractValidator /// public AddLibraryCommandValidator() { - RuleFor(x => x.LibraryType) - .NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description) - .Must(x => Enum.TryParse(x, out _)) - .WithMessage(Errors.Library.UnknownLibraryType.Description); + RuleFor(command => command.LibraryType) + .NotNull() + .WithError(Errors.Library.LibraryTypeCannotBeNull) + .Must(libraryType => Enum.TryParse(libraryType, out _)) + .WithError(Errors.Library.UnknownLibraryType); - RuleFor(x => x.ContentLocations) - .NotNull().WithMessage(Errors.Library.PathsListCannotBeNull.Description) - .NotEmpty().WithMessage(Errors.Library.PathsListCannotBeEmpty.Description); + RuleFor(command => command.ContentLocations) + .NotNull() + .WithError(Errors.Library.PathsListCannotBeNull) + .NotEmpty() + .WithError(Errors.Library.PathsListCannotBeEmpty); - RuleForEach(x => x.ContentLocations) - .NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description) - .MaximumLength(260).WithMessage(Errors.FileSystemManagement.PathMustBeMaximum260CharactersLong.Description); + RuleForEach(command => command.ContentLocations) + .NotEmpty() + .WithError(Errors.FileSystemManagement.PathCannotBeEmpty) + .MaximumLength(260) + .WithError(Errors.FileSystemManagement.PathMustBeMaximum260CharactersLong); - RuleFor(x => x.Title) - .NotEmpty().WithMessage(Errors.Library.TitleCannotBeEmpty.Description) - .MaximumLength(255).WithMessage(Errors.Library.TitleMustBeMaximum255CharactersLong.Description); + RuleFor(command => command.Title) + .NotEmpty() + .WithError(Errors.Library.TitleCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Library.TitleMustBeMaximum255CharactersLong); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommand.cs index 1502b0dd..15f56d1d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommand.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Mediator; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; @@ -8,4 +7,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrari /// /// Command for canceling the previously started scan of all media libraries. /// -public record CancelLibrariesScanCommand : IRequest>; +public record CancelLibrariesScanCommand : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs index 93c46a87..2d9d60da 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; @@ -10,7 +11,6 @@ using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; -using Mediator; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -22,7 +22,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrari /// /// Handler for the command for canceling the scan of all media libraries. /// -public class CancelLibrariesScanCommandHandler : IRequestHandler> +public class CancelLibrariesScanCommandHandler : ICommandHandler> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; @@ -51,10 +51,10 @@ public class CancelLibrariesScanCommandHandler : IRequestHandler /// Handles the command for canceling the scan of all media libraries. /// - /// The request to be handled. + /// The command to be handled. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async ValueTask> Handle(CancelLibrariesScanCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(CancelLibrariesScanCommand command, CancellationToken cancellationToken) { ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommand.cs index 5171a9cb..c6761330 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommand.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Mediator; +using Lumina.Application.Common.CQRS; using System; using System.Diagnostics; #endregion @@ -16,4 +15,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrary public record CancelLibraryScanCommand( Guid LibraryId, Guid ScanId -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs index f0e7a489..c51a844a 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs @@ -1,15 +1,17 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; -using Mediator; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -21,12 +23,13 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrary /// /// Handler for the command for canceling the scan of a media library. /// -public class CancelLibraryScanCommandHandler : IRequestHandler> +public class CancelLibraryScanCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. @@ -35,30 +38,37 @@ public class CancelLibraryScanCommandHandler : IRequestHandlerInjected service to retrieve the current user information. /// Injected service for the queue of domain events. /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. public CancelLibraryScanCommandHandler( IAuthorizationService authorizationService, ICurrentUserService currentUserService, IDomainEventsQueue domainEventsQueue, - IUnitOfWork unitOfWork) + IUnitOfWork unitOfWork, + IValidator validator) { _authorizationService = authorizationService; _currentUserService = currentUserService; _domainEventsQueue = domainEventsQueue; _unitOfWork = unitOfWork; + _validator = validator; } /// /// Handles the command for canceling the scan of a media library. /// - /// The request to be handled. + /// The command to be handled. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async ValueTask> Handle(CancelLibraryScanCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(CancelLibraryScanCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); // get the library scan from the repository - ErrorOr getLibraryScansResult = await libraryScanRepository.GetByIdAsync(request.ScanId, cancellationToken).ConfigureAwait(false); + ErrorOr getLibraryScansResult = await libraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false); if (getLibraryScansResult.IsError) return getLibraryScansResult.Errors; if (getLibraryScansResult.Value is null) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs index 63d94dc0..05e15b60 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; using System; #endregion @@ -16,11 +17,16 @@ public class CancelLibraryScanCommandValidator : AbstractValidator public CancelLibraryScanCommandValidator() { - RuleFor(x => x.LibraryId) - .NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description); - RuleFor(x => x.ScanId) - .NotEmpty().WithMessage(Errors.LibraryScanning.ScanIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.LibraryScanning.ScanIdCannotBeEmpty.Description); + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.ScanId) + .NotEmpty() + .WithError(Errors.LibraryScanning.ScanIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.LibraryScanning.ScanIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommand.cs index 0f1932eb..022b4623 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommand.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Mediator; +using Lumina.Application.Common.CQRS; using System; using System.Diagnostics; #endregion @@ -14,4 +13,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary [DebuggerDisplay("Id: {Id}")] public record DeleteLibraryCommand( Guid Id -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs index 998e77b2..97c63bf2 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs @@ -1,15 +1,17 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; -using Mediator; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -21,12 +23,13 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary /// /// Handler for the command to delete a library by its Id. /// -public class DeleteLibraryCommandHandler : IRequestHandler> +public class DeleteLibraryCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. @@ -35,29 +38,36 @@ public class DeleteLibraryCommandHandler : IRequestHandlerInjected service to retrieve the current user information. /// Injected service for the queue of domain events. /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. public DeleteLibraryCommandHandler( IAuthorizationService authorizationService, ICurrentUserService currentUserService, IDomainEventsQueue domainEventsQueue, - IUnitOfWork unitOfWork) + IUnitOfWork unitOfWork, + IValidator validator) { _authorizationService = authorizationService; _currentUserService = currentUserService; _domainEventsQueue = domainEventsQueue; _unitOfWork = unitOfWork; + _validator = validator; } /// /// Handles the command to delete a library by its Id. /// - /// The request to be handled. + /// The command to be handled. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async ValueTask> Handle(DeleteLibraryCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(DeleteLibraryCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + // get the library with the specified id from the repository ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false); + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsError) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) @@ -83,7 +93,7 @@ public class DeleteLibraryCommandHandler : IRequestHandler deletePersistenceLibraryResult = await libraryRepository.DeleteByIdAsync(request.Id, cancellationToken).ConfigureAwait(false); + ErrorOr deletePersistenceLibraryResult = await libraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); if (deletePersistenceLibraryResult.IsError) return deletePersistenceLibraryResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandValidator.cs index af95943b..39847676 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; using System; #endregion @@ -16,8 +17,10 @@ public class DeleteLibraryCommandValidator : AbstractValidator public DeleteLibraryCommandValidator() { - RuleFor(x => x.Id) - .NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description); + RuleFor(command => command.Id) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs index f97762c4..b8efc82d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs @@ -1,8 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.MediaLibrary.Management; -using Mediator; -using System.Collections.Generic; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries; @@ -10,4 +7,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries /// /// Command for initiating the scan of all media libraries. /// -public record ScanLibrariesCommand() : IRequest>>; +public record ScanLibrariesCommand() : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs index aad83b67..ceda7784 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; @@ -13,7 +14,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Mediator; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -25,7 +25,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries /// /// Handler for the command for initiating the scan of all media libraries. /// -public class ScanLibrariesCommandHandler : IRequestHandler>> +public class ScanLibrariesCommandHandler : ICommandHandler>> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -54,10 +54,10 @@ public class ScanLibrariesCommandHandler : IRequestHandler /// Handles the command for initiating the scan of all media libraries. /// - /// The request to be handled. + /// The command to be handled. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async ValueTask>> Handle(ScanLibrariesCommand request, CancellationToken cancellationToken) + public async Task>> HandleAsync(ScanLibrariesCommand command, CancellationToken cancellationToken) { ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommand.cs index 51dec263..111221dd 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommand.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.MediaLibrary.Management; -using Mediator; +using Lumina.Application.Common.CQRS; using System; #endregion @@ -13,4 +11,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary; /// The unique identifier of the library to scan. public record ScanLibraryCommand( Guid Id -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs index 3c25cd1d..826ed966 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs @@ -1,11 +1,13 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Common.Events; @@ -14,7 +16,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Mediator; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -28,12 +29,13 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary; /// /// Handler for the command for initiating the scan of a media library. /// -public class ScanLibraryCommandHandler : IRequestHandler> +public class ScanLibraryCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. @@ -42,31 +44,38 @@ public class ScanLibraryCommandHandler : IRequestHandlerInjected service to retrieve the current user information. /// Injected service for the queue of domain events. /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. public ScanLibraryCommandHandler( IAuthorizationService authorizationService, ICurrentUserService currentUserService, IDomainEventsQueue domainEventsQueue, - IUnitOfWork unitOfWork) + IUnitOfWork unitOfWork, + IValidator validator) { _authorizationService = authorizationService; _currentUserService = currentUserService; _domainEventsQueue = domainEventsQueue; _unitOfWork = unitOfWork; + _validator = validator; } /// /// Handles the command for initiating the scan of a media library. /// - /// The request to be handled. + /// The command to be handled. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async ValueTask> Handle(ScanLibraryCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(ScanLibraryCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); // get the media library from the persistence medium - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false); + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsError) return getLibraryResult.Errors; @@ -91,7 +100,7 @@ public class ScanLibraryCommandHandler : IRequestHandler> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(request.Id, cancellationToken).ConfigureAwait(false); + ErrorOr> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, cancellationToken).ConfigureAwait(false); if (pastLibraryScansResult.IsError) return pastLibraryScansResult.Errors; @@ -103,7 +112,7 @@ public class ScanLibraryCommandHandler : IRequestHandler libraryScanResult = LibraryScan.Create( - LibraryId.Create(request.Id), + LibraryId.Create(command.Id), UserId.Create(_currentUserService.UserId!.Value), [.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)] ); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandValidator.cs index 8a91302e..f053e552 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; using System; #endregion @@ -16,8 +17,10 @@ public class ScanLibraryCommandValidator : AbstractValidator /// public ScanLibraryCommandValidator() { - RuleFor(x => x.Id) - .NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description); + RuleFor(command => command.Id) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs index 5ad5d779..7549e5c0 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.MediaLibrary.Management; -using Mediator; +using Lumina.Application.Common.CQRS; using System; using System.Diagnostics; #endregion @@ -35,4 +33,4 @@ public record UpdateLibraryCommand( bool DownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs index fc69d35e..5daac492 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -1,11 +1,13 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; @@ -18,8 +20,8 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Mediator; using System; +using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -32,13 +34,14 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary /// /// Handler for the command to update a media library. /// -public class UpdateLibraryCommandHandler : IRequestHandler> +public class UpdateLibraryCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; private readonly IDomainEventsQueue _domainEventsQueue; private readonly IEnvironmentContext _environmentContext; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. @@ -48,34 +51,41 @@ public class UpdateLibraryCommandHandler : IRequestHandlerInjected service for the queue of domain events. /// Injected facade service for environment contextual services. /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. public UpdateLibraryCommandHandler( IAuthorizationService authorizationService, ICurrentUserService currentUserService, IDomainEventsQueue domainEventsQueue, IEnvironmentContext environmentContext, - IUnitOfWork unitOfWork) + IUnitOfWork unitOfWork, + IValidator validator) { _authorizationService = authorizationService; _currentUserService = currentUserService; _unitOfWork = unitOfWork; _domainEventsQueue = domainEventsQueue; _environmentContext = environmentContext; + _validator = validator; } /// /// Handles the command to update a media library. /// - /// The request to be handled. + /// The command to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a successfully updated , or an error message. /// - public async ValueTask> Handle(UpdateLibraryCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(UpdateLibraryCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + // make sure the file is an actual supported image - if (request.CoverImage is not null) + if (command.CoverImage is not null) { - ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(request.CoverImage); + ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage); if (fileSystemPathIdResult.IsError) return fileSystemPathIdResult.Errors; @@ -88,7 +98,7 @@ public class UpdateLibraryCommandHandler : IRequestHandler(); - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false); + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsError) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) @@ -102,17 +112,17 @@ public class UpdateLibraryCommandHandler : IRequestHandler createLibraryResult = Library.Create( - LibraryId.Create(request.Id), - UserId.Create(request.OwnerId), - request.Title!, - Enum.Parse(request.LibraryType!), - request.ContentLocations!, - request.CoverImage, - request.IsEnabled, - request.IsLocked, - request.DownloadMetadataFromWeb, - request.ShouldSaveMetadataInMediaDirectories, - request.ShouldSkipUnchangedDirectoriesDuringScan, + LibraryId.Create(command.Id), + UserId.Create(command.OwnerId), + command.Title!, + Enum.Parse(command.LibraryType!), + command.ContentLocations!, + command.CoverImage, + command.IsEnabled, + command.IsLocked, + command.DownloadMetadataFromWeb, + command.ShouldSaveMetadataInMediaDirectories, + command.ShouldSkipUnchangedDirectoriesDuringScan, getLibraryResult.Value.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id)).ToList() ); if (createLibraryResult.IsError) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs index 430b5b5c..6d32e5eb 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.SharedKernel.Common.Errors; using System; @@ -17,29 +18,40 @@ public class UpdateLibraryCommandValidator : AbstractValidator public UpdateLibraryCommandValidator() { - RuleFor(x => x.Id) - .NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description); - - RuleFor(x => x.OwnerId) - .NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description); + RuleFor(command => command.Id) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); - RuleFor(x => x.LibraryType) - .NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description) - .Must(x => Enum.TryParse(x, out _)) - .WithMessage(Errors.Library.UnknownLibraryType.Description); + RuleFor(command => command.OwnerId) + .NotEmpty() + .WithError(Errors.Users.UserIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Users.UserIdCannotBeEmpty); - RuleFor(x => x.ContentLocations) - .NotNull().WithMessage(Errors.Library.PathsListCannotBeNull.Description) - .NotEmpty().WithMessage(Errors.Library.PathsListCannotBeEmpty.Description); + RuleFor(command => command.LibraryType) + .NotNull() + .WithError(Errors.Library.LibraryTypeCannotBeNull) + .Must(libraryType => Enum.TryParse(libraryType, out _)) + .WithError(Errors.Library.UnknownLibraryType); - RuleForEach(x => x.ContentLocations) - .NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description) - .MaximumLength(260).WithMessage(Errors.FileSystemManagement.PathMustBeMaximum260CharactersLong.Description); + RuleFor(command => command.ContentLocations) + .NotNull() + .WithError(Errors.Library.PathsListCannotBeNull) + .NotEmpty() + .WithError(Errors.Library.PathsListCannotBeEmpty); - RuleFor(x => x.Title) - .NotEmpty().WithMessage(Errors.Library.TitleCannotBeEmpty.Description) - .MaximumLength(255).WithMessage(Errors.Library.TitleMustBeMaximum255CharactersLong.Description); + RuleForEach(command => command.ContentLocations) + .NotEmpty() + .WithError(Errors.FileSystemManagement.PathCannotBeEmpty) + .MaximumLength(260) + .WithError(Errors.FileSystemManagement.PathMustBeMaximum260CharactersLong); + + RuleFor(command => command.Title) + .NotEmpty() + .WithError(Errors.Library.TitleCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Library.TitleMustBeMaximum255CharactersLong); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs index 7f7e91eb..5f4ab957 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs @@ -6,7 +6,7 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; -using Mediator; +using Lumina.Domain.Common.Events; using Microsoft.Extensions.Options; using System; using System.Threading; @@ -16,9 +16,9 @@ using System.Threading.Tasks; namespace Lumina.Application.Core.MediaLibrary.Management.Events; /// -/// Handler for the event raised when a media library is deleted. +/// Handler for the domain event raised when a media library is deleted. /// -public class LibraryDeletedDomainEventHandler : INotificationHandler +public class LibraryDeletedDomainEventHandler : IDomainEventHandler { private readonly IEnvironmentContext _environmentContext; private readonly IPathService _pathService; @@ -42,7 +42,7 @@ public class LibraryDeletedDomainEventHandler : INotificationHandler /// The domain event to be handled. /// Cancellation token that can be used to stop the execution. - public ValueTask Handle(LibraryDeletedDomainEvent domainEvent, CancellationToken cancellationToken) + public ValueTask HandleAsync(LibraryDeletedDomainEvent domainEvent, CancellationToken cancellationToken) { // delete the media library directory in the internal location for media library files ErrorOr libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs index 08f2cb79..e83e3411 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs @@ -5,12 +5,12 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; -using Mediator; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; @@ -23,9 +23,9 @@ using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; namespace Lumina.Application.Core.MediaLibrary.Management.Events; /// -/// Handler for the event raised when a media library is created or updated. +/// Handler for the domain event raised when a media library is created or updated. /// -public class LibrarySavedDomainEventHandler : INotificationHandler +public class LibrarySavedDomainEventHandler : IDomainEventHandler { private readonly IUnitOfWork _unitOfWork; private readonly IEnvironmentContext _environmentContext; @@ -56,7 +56,7 @@ public class LibrarySavedDomainEventHandler : INotificationHandler /// The domain event to be handled. /// Cancellation token that can be used to stop the execution. - public async ValueTask Handle(LibrarySavedDomainEvent domainEvent, CancellationToken cancellationToken) + public async ValueTask HandleAsync(LibrarySavedDomainEvent domainEvent, CancellationToken cancellationToken) { if (domainEvent.Library.CoverImage is not null) { diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs index 3137958f..0c176b68 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs @@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; @@ -13,7 +14,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Mediator; using System.Threading; using System.Threading.Tasks; #endregion @@ -21,9 +21,9 @@ using System.Threading.Tasks; namespace Lumina.Application.Core.MediaLibrary.Management.Events; /// -/// Handler for the event raised when a media library scan is cancelled. +/// Handler for the domain event raised when a media library scan is cancelled. /// -public class LibraryScanCancelledDomainEventHandler : INotificationHandler +public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler { private readonly IMediaLibraryScanningService _mediaLibraryScanningService; private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker; @@ -56,7 +56,7 @@ public class LibraryScanCancelledDomainEventHandler : INotificationHandler /// The domain event to be handled. /// Cancellation token that can be used to stop the execution. - public async ValueTask Handle(LibraryScanCancelledDomainEvent domainEvent, CancellationToken cancellationToken) + public async ValueTask HandleAsync(LibraryScanCancelledDomainEvent domainEvent, CancellationToken cancellationToken) { // get the library scan from the repository ErrorOr getLibraryScansResult = await _libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs index a6b68baa..8da1fdbf 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs @@ -6,12 +6,12 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Progress; using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; -using Mediator; using System.Threading; using System.Threading.Tasks; #endregion @@ -19,9 +19,9 @@ using System.Threading.Tasks; namespace Lumina.Application.Core.MediaLibrary.Management.Events; /// -/// Handler for the event raised when a media library scan has failed. +/// Handler for the domain event raised when a media library scan has failed. /// -public class LibraryScanFailedDomainEventHandler : INotificationHandler +public class LibraryScanFailedDomainEventHandler : IDomainEventHandler { private readonly IMediaLibraryScanProgressNotifier _debouncedLibraryScanProgressNotifier; private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker; @@ -52,7 +52,7 @@ public class LibraryScanFailedDomainEventHandler : INotificationHandler /// The domain event to be handled. /// Cancellation token that can be used to stop the execution. - public async ValueTask Handle(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken) + public async ValueTask HandleAsync(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken) { ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); ILibraryScanStagingResultsRepository stagingResultsRepository = _unitOfWork.GetRepository(); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs index 79726cea..a0b20187 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs @@ -6,12 +6,12 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Progress; using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; -using Mediator; using System.Threading; using System.Threading.Tasks; #endregion @@ -19,9 +19,9 @@ using System.Threading.Tasks; namespace Lumina.Application.Core.MediaLibrary.Management.Events; /// -/// Handler for the event raised when a media library scan is finished. +/// Handler for the domain event raised when a media library scan is finished. /// -public class LibraryScanFinishedDomainEventHandler : INotificationHandler +public class LibraryScanFinishedDomainEventHandler : IDomainEventHandler { private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker; @@ -52,7 +52,7 @@ public class LibraryScanFinishedDomainEventHandler : INotificationHandler /// The domain event to be handled. /// Cancellation token that can be used to stop the execution. - public async ValueTask Handle(LibraryScanFinishedDomainEvent domainEvent, CancellationToken cancellationToken) + public async ValueTask HandleAsync(LibraryScanFinishedDomainEvent domainEvent, CancellationToken cancellationToken) { ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanJobProgressChangedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanJobProgressChangedDomainEventHandler.cs index 47db2cf5..e0bd68b4 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanJobProgressChangedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanJobProgressChangedDomainEventHandler.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.MediaLibrary.Management.Progress; +using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; -using Mediator; using System.Threading; using System.Threading.Tasks; #endregion @@ -10,9 +10,9 @@ using System.Threading.Tasks; namespace Lumina.Application.Core.MediaLibrary.Management.Events; /// -/// Handler for the event raised when a media library's scan progress changes. +/// Handler for the domain event raised when a media library's scan progress changes. /// -public class LibraryScanJobProgressChangedDomainEventHandler : INotificationHandler +public class LibraryScanJobProgressChangedDomainEventHandler : IDomainEventHandler { private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; private readonly IMediaLibraryScanProgressNotifier _debouncedLibraryScanProgressNotifier; @@ -35,7 +35,7 @@ public class LibraryScanJobProgressChangedDomainEventHandler : INotificationHand /// /// The domain event to be handled. /// Cancellation token that can be used to stop the execution. - public async ValueTask Handle(LibraryScanJobProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken) + public async ValueTask HandleAsync(LibraryScanJobProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken) { _mediaLibrariesScanProgressTracker.UpdateScanJobProgress(domainEvent.LibraryId, domainEvent.MediaLibraryScanCompositeId, domainEvent.Progress); // notify SignalR clients that the library scan progress changed diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs index 42059d36..2934a173 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.MediaLibrary.Management.Progress; +using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; -using Mediator; using System.Threading; using System.Threading.Tasks; #endregion @@ -10,9 +10,9 @@ using System.Threading.Tasks; namespace Lumina.Application.Core.MediaLibrary.Management.Events; /// -/// Handler for the event raised when a media library's scan progress changes. +/// Handler for the domain event raised when a media library's scan progress changes. /// -public class LibraryScanProgressChangedDomainEventHandler : INotificationHandler +public class LibraryScanProgressChangedDomainEventHandler : IDomainEventHandler { private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; private readonly IMediaLibraryScanProgressNotifier _debouncedLibraryScanProgressNotifier; @@ -35,7 +35,7 @@ public class LibraryScanProgressChangedDomainEventHandler : INotificationHandler /// /// The domain event to be handled. /// Cancellation token that can be used to stop the execution. - public async ValueTask Handle(LibraryScanProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken) + public async ValueTask HandleAsync(LibraryScanProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken) { _mediaLibrariesScanProgressTracker.UpdateScanProgress(domainEvent.LibraryId, domainEvent.MediaLibraryScanCompositeId); // notify SignalR clients that the library scan progress changed diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs index 17ee8a78..adbaf656 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs @@ -12,7 +12,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Mediator; using System.Threading; using System.Threading.Tasks; #endregion @@ -20,9 +19,9 @@ using System.Threading.Tasks; namespace Lumina.Application.Core.MediaLibrary.Management.Events; /// -/// Handler for the event raised when a media library scan is queued. +/// Handler for the domain event raised when a media library scan is queued. /// -public class LibraryScanQueuedDomainEventHandler : INotificationHandler +public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler { private readonly IMediaLibraryScanningService _mediaLibraryScanningService; private readonly IDomainEventsQueue _domainEventsQueue; @@ -47,7 +46,7 @@ public class LibraryScanQueuedDomainEventHandler : INotificationHandler /// The domain event to be handled. /// Cancellation token that can be used to stop the execution. - public async ValueTask Handle(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken) + public async ValueTask HandleAsync(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken) { ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs index b6fcfa91..a6597e5e 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs @@ -3,9 +3,9 @@ using ErrorOr; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; -using Mediator; using System.Threading; using System.Threading.Tasks; #endregion @@ -13,9 +13,9 @@ using System.Threading.Tasks; namespace Lumina.Application.Core.MediaLibrary.Management.Events; /// -/// Handler for the event raised when a media library scan is started. +/// Handler for the domain event raised when a media library scan is started. /// -public class LibraryScanStartedDomainEventHandler : INotificationHandler +public class LibraryScanStartedDomainEventHandler : IDomainEventHandler { private readonly IUnitOfWork _unitOfWork; @@ -33,7 +33,7 @@ public class LibraryScanStartedDomainEventHandler : INotificationHandler /// The domain event to be handled. /// Cancellation token that can be used to stop the execution. - public async ValueTask Handle(LibraryScanStartedDomainEvent domainEvent, CancellationToken cancellationToken) + public async ValueTask HandleAsync(LibraryScanStartedDomainEvent domainEvent, CancellationToken cancellationToken) { ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQuery.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQuery.cs index 097948d6..0bce529e 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQuery.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.MediaLibrary.Management; -using Mediator; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibraries; @@ -9,4 +7,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibr /// /// Query for getting the list of enabled media libraries. /// -public record GetEnabledLibrariesQuery : IRequest>; +public record GetEnabledLibrariesQuery : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs index 8b09b26a..97ef688d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; @@ -7,7 +8,6 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; -using Mediator; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -19,7 +19,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibr /// /// Handler for the query to get the enabled media libraries. /// -public class GetEnabledLibrariesQueryHandler : IRequestHandler> +public class GetEnabledLibrariesQueryHandler : IQueryHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -44,12 +44,12 @@ public class GetEnabledLibrariesQueryHandler : IRequestHandler /// Handles the query to get the enabled media libraries. /// - /// The request to be handled. + /// The query to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a successfully created , or an error message. /// - public async ValueTask> Handle(GetEnabledLibrariesQuery request, CancellationToken cancellationToken) + public async Task> HandleAsync(GetEnabledLibrariesQuery query, CancellationToken cancellationToken) { // get the enabled libraries from the repository ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQuery.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQuery.cs index f774aefb..8c3cecd9 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQuery.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.MediaLibrary.Management; -using Mediator; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries; @@ -9,4 +7,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries; /// /// Query for getting the list of media libraries. /// -public record GetLibrariesQuery : IRequest>; +public record GetLibrariesQuery : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs index 3e911e30..ea39a937 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; @@ -7,7 +8,6 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; -using Mediator; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -19,7 +19,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries; /// /// Handler for the query to get the media libraries. /// -public class GetLibrariesQueryHandler : IRequestHandler> +public class GetLibrariesQueryHandler : IQueryHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -44,12 +44,12 @@ public class GetLibrariesQueryHandler : IRequestHandler /// Handles the query to get the media libraries. /// - /// The request to be handled. + /// The query to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a successfully created , or an error message. /// - public async ValueTask> Handle(GetLibrariesQuery request, CancellationToken cancellationToken) + public async Task> HandleAsync(GetLibrariesQuery query, CancellationToken cancellationToken) { // get the libraries from the repository ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQuery.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQuery.cs index 3775b7c7..1800eef6 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQuery.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.MediaLibrary.Management; -using Mediator; +using Lumina.Application.Common.CQRS; using System; using System.Diagnostics; #endregion @@ -15,4 +13,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary; [DebuggerDisplay("Id: {Id}")] public record GetLibraryQuery( Guid Id -) : IRequest>; +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs index d5aeff9a..1cb15caa 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs @@ -1,14 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; -using Mediator; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -20,11 +22,12 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary; /// /// Handler for the query to get a library by its Id. /// -public class GetLibraryQueryHandler : IRequestHandler> +public class GetLibraryQueryHandler : IQueryHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. @@ -32,29 +35,36 @@ public class GetLibraryQueryHandler : IRequestHandlerInjected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. public GetLibraryQueryHandler( IAuthorizationService authorizationService, ICurrentUserService currentUserService, - IUnitOfWork unitOfWork) + IUnitOfWork unitOfWork, + IValidator validator) { _authorizationService = authorizationService; _currentUserService = currentUserService; _unitOfWork = unitOfWork; + _validator = validator; } /// /// Handles the query to get a library by its Id. /// - /// The request to be handled. + /// The query to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a successfully created , or an error message. /// - public async ValueTask> Handle(GetLibraryQuery request, CancellationToken cancellationToken) + public async Task> HandleAsync(GetLibraryQuery query, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + // get the library with the specified id from the repository ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false); + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsError) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryValidator.cs index 73a0470f..7e2c54c4 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; using System; #endregion @@ -16,8 +17,10 @@ public class GetLibraryQueryValidator : AbstractValidator /// public GetLibraryQueryValidator() { - RuleFor(x => x.Id) - .NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description); + RuleFor(query => query.Id) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQuery.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQuery.cs index 4349aa2e..234090e1 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQuery.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.MediaLibrary.Management; -using Mediator; +using Lumina.Application.Common.CQRS; using System; #endregion @@ -15,4 +13,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScan public record GetLibraryScanProgressQuery( Guid LibraryId, Guid ScanId -) : IRequest>; +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs index 55803489..dbbd4a1e 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs @@ -1,17 +1,19 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Mediator; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -23,12 +25,13 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScan /// /// Handler for the query to get the progress of a library scan. /// -public class GetLibraryScanProgressQueryHandler : IRequestHandler> +public class GetLibraryScanProgressQueryHandler : IQueryHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. @@ -37,31 +40,38 @@ public class GetLibraryScanProgressQueryHandler : IRequestHandlerInjected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. public GetLibraryScanProgressQueryHandler( IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker, IAuthorizationService authorizationService, ICurrentUserService currentUserService, - IUnitOfWork unitOfWork) + IUnitOfWork unitOfWork, + IValidator validator) { _mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker; _authorizationService = authorizationService; _currentUserService = currentUserService; _unitOfWork = unitOfWork; + _validator = validator; } /// /// Handles the query to get the progress of a library scan. /// - /// The request to be handled. + /// The query to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a , or an error message. /// - public async ValueTask> Handle(GetLibraryScanProgressQuery request, CancellationToken cancellationToken) + public async Task> HandleAsync(GetLibraryScanProgressQuery query, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + // get the library with the specified id from the repository ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false); + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsError) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) @@ -73,7 +83,7 @@ public class GetLibraryScanProgressQueryHandler : IRequestHandler getProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress( - MediaLibraryScanCompositeId.Create(ScanId.Create(request.ScanId), UserId.Create(_currentUserService.UserId!.Value))); + MediaLibraryScanCompositeId.Create(ScanId.Create(query.ScanId), UserId.Create(_currentUserService.UserId!.Value))); if (getProgressResult.IsError) return getProgressResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryValidator.cs index 1077627a..648b17a4 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; using System; #endregion @@ -16,11 +17,16 @@ public class GetLibraryScanProgressQueryValidator : AbstractValidator public GetLibraryScanProgressQueryValidator() { - RuleFor(x => x.ScanId) - .NotEmpty().WithMessage(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty.Description); - RuleFor(x => x.LibraryId) - .NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description); + RuleFor(query => query.ScanId) + .NotEmpty() + .WithError(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQuery.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQuery.cs index 7cb2d613..3b366ad0 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQuery.cs @@ -1,8 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.MediaLibrary.Management; -using Mediator; -using System.Collections.Generic; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans; @@ -10,4 +7,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibr /// /// Query for getting the list of ongoing media library scans. /// -public record GetRunningLibraryScansQuery : IRequest>>; +public record GetRunningLibraryScansQuery : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs index da62ae66..bea6d4f2 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; @@ -10,7 +11,6 @@ using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Mediator; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -22,7 +22,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibr /// /// Handler for the query to get the ongoing media library scans. /// -public class GetRunningLibraryScansQueryHandler : IRequestHandler>> +public class GetRunningLibraryScansQueryHandler : IQueryHandler>> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -51,12 +51,12 @@ public class GetRunningLibraryScansQueryHandler : IRequestHandler /// Handles the query to get the ongoing media library scans. /// - /// The request to be handled. + /// The query to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a successfully created , or an error message. /// - public async ValueTask>> Handle(GetRunningLibraryScansQuery request, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetRunningLibraryScansQuery query, CancellationToken cancellationToken) { // get the ongoing library scans from the repository ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs index 9b04da3d..f75de677 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Mediator; using System; using System.Collections.Generic; using System.Diagnostics; @@ -56,4 +54,4 @@ public record AddBookCommand( List? ISBNs, List? Contributors, List? Ratings -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs index e7bb8234..9d8d4434 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs @@ -1,9 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Primitives; @@ -13,7 +15,6 @@ using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.Boo using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; -using Mediator; using System; using System.Collections.Generic; using System.Linq; @@ -27,42 +28,49 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar /// /// Handler for the command to add a book. /// -public class AddBookCommandHandler : IRequestHandler> +public class AddBookCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. - public AddBookCommandHandler(IUnitOfWork unitOfWork) + /// Injected validator for application validation rules. + public AddBookCommandHandler(IUnitOfWork unitOfWork, IValidator validator) { _unitOfWork = unitOfWork; + _validator = validator; } /// /// Handles the command to add a book. /// - /// The request to be handled. + /// The command to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a successfully created , or an error message. /// - public async ValueTask> Handle(AddBookCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(AddBookCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + // TODO: update Api.Book.md documentation when the functionality is fully implemented List contributorIds = []; - foreach (MediaContributorDto mediaContributor in request.Contributors!) + foreach (MediaContributorDto mediaContributor in command.Contributors!) { // TODO: add logic to search the media contributors repository for existing contributors, based on the provided names } BookSeries? bookSeries = null; - if (request.Series != null) + if (command.Series != null) { // TODO: add logic to search the book series repository for existing book series, based on the provided title // TODO: uncomment integration and unit tests about series } - List> domainRatingsResult = request.Ratings!.ConvertAll(rating => BookRating.Create( + List> domainRatingsResult = command.Ratings!.ConvertAll(rating => BookRating.Create( rating.Value ?? default, rating.MaxValue ?? default, Optional.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : (BookRatingSource?)null), @@ -74,88 +82,88 @@ public class AddBookCommandHandler : IRequestHandler domainRatings = [.. domainRatingsResult.Select(rating => rating.Value)]; - List> domainGenresResult = request.Metadata!.Genres!.ConvertAll(genre => Genre.Create(genre.Name!)); + List> domainGenresResult = command.Metadata!.Genres!.ConvertAll(genre => Genre.Create(genre.Name!)); errors = [.. domainGenresResult.Where(genreResult => genreResult.IsError).SelectMany(genreResult => genreResult.Errors)]; if (errors.Count != 0) return errors; List domainGenres = [.. domainGenresResult.Select(genre => genre.Value)]; - List> domainTagsResult = request.Metadata.Tags!.ConvertAll(tag => Tag.Create(tag.Name!)); + List> domainTagsResult = command.Metadata.Tags!.ConvertAll(tag => Tag.Create(tag.Name!)); errors = [.. domainTagsResult.Where(tagResult => tagResult.IsError).SelectMany(tagResult => tagResult.Errors)]; if (errors.Count != 0) return errors; List domainTags = [.. domainTagsResult.Select(tag => tag.Value)]; - List> domainIsbnsResult = request.ISBNs!.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!)); + List> domainIsbnsResult = command.ISBNs!.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!)); errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsError).SelectMany(isbnResult => isbnResult.Errors)]; if (errors.Count != 0) return errors; List domainIsbns = [.. domainIsbnsResult.Select(isbn => isbn.Value)]; ErrorOr releaseInfoResult = ReleaseInfo.Create( - Optional.FromNullable(request.Metadata.ReleaseInfo!.OriginalReleaseDate), - Optional.FromNullable(request.Metadata.ReleaseInfo.OriginalReleaseYear), - Optional.FromNullable(request.Metadata.ReleaseInfo.ReReleaseDate), - Optional.FromNullable(request.Metadata.ReleaseInfo.ReReleaseYear), - Optional.FromNullable(request.Metadata.ReleaseInfo.ReleaseCountry), - Optional.FromNullable(request.Metadata.ReleaseInfo.ReleaseVersion) + Optional.FromNullable(command.Metadata.ReleaseInfo!.OriginalReleaseDate), + Optional.FromNullable(command.Metadata.ReleaseInfo.OriginalReleaseYear), + Optional.FromNullable(command.Metadata.ReleaseInfo.ReReleaseDate), + Optional.FromNullable(command.Metadata.ReleaseInfo.ReReleaseYear), + Optional.FromNullable(command.Metadata.ReleaseInfo.ReleaseCountry), + Optional.FromNullable(command.Metadata.ReleaseInfo.ReleaseVersion) ); if (releaseInfoResult.IsError) return releaseInfoResult.Errors; ReleaseInfo releaseInfo = releaseInfoResult.Value; LanguageInfo? languageInfo = null; - if (request.Metadata.Language is not null) + if (command.Metadata.Language is not null) { ErrorOr languageInfoResult = LanguageInfo.Create( - request.Metadata.Language.LanguageCode!, - request.Metadata.Language.LanguageName!, - Optional.FromNullable(request.Metadata.Language.NativeName)); + command.Metadata.Language.LanguageCode!, + command.Metadata.Language.LanguageName!, + Optional.FromNullable(command.Metadata.Language.NativeName)); if (languageInfoResult.IsError) return languageInfoResult.Errors; languageInfo = languageInfoResult.Value; } LanguageInfo? originalLanguageInfo = null; - if (request.Metadata.OriginalLanguage is not null) + if (command.Metadata.OriginalLanguage is not null) { ErrorOr originalLanguageInfoResult = LanguageInfo.Create( - request.Metadata.OriginalLanguage.LanguageCode!, - request.Metadata.OriginalLanguage.LanguageName!, - Optional.FromNullable(request.Metadata.OriginalLanguage.NativeName)); + command.Metadata.OriginalLanguage.LanguageCode!, + command.Metadata.OriginalLanguage.LanguageName!, + Optional.FromNullable(command.Metadata.OriginalLanguage.NativeName)); if (originalLanguageInfoResult.IsError) return originalLanguageInfoResult.Errors; originalLanguageInfo = originalLanguageInfoResult.Value; } ErrorOr metadataResult = WrittenContentMetadata.Create( - request.Metadata.Title!, - Optional.FromNullable(request.Metadata.OriginalTitle), - Optional.FromNullable(request.Metadata.Description), + command.Metadata.Title!, + Optional.FromNullable(command.Metadata.OriginalTitle), + Optional.FromNullable(command.Metadata.Description), releaseInfo, domainGenres, domainTags, Optional.FromNullable(languageInfo), Optional.FromNullable(originalLanguageInfo), - Optional.FromNullable(request.Metadata.Publisher), - Optional.FromNullable(request.Metadata.PageCount) + Optional.FromNullable(command.Metadata.Publisher), + Optional.FromNullable(command.Metadata.PageCount) ); if (metadataResult.IsError) return metadataResult.Errors; ErrorOr createBookResult = Book.Create( - LibraryId.Create(request.LibraryId), - request.Path, + LibraryId.Create(command.LibraryId), + command.Path, metadataResult.Value, - Optional.FromNullable(request.Format), - Optional.FromNullable(request.Edition), - request.VolumeNumber ?? default, + Optional.FromNullable(command.Format), + Optional.FromNullable(command.Edition), + command.VolumeNumber ?? default, Optional.FromNullable(bookSeries), - Optional.FromNullable(request.ASIN), - Optional.FromNullable(request.GoodreadsId), - Optional.FromNullable(request.LCCN), - Optional.FromNullable(request.OCLCNumber), - Optional.FromNullable(request.OpenLibraryId), - Optional.FromNullable(request.LibraryThingId), - Optional.FromNullable(request.GoogleBooksId), - Optional.FromNullable(request.BarnesAndNobleId), - Optional.FromNullable(request.AppleBooksId), + Optional.FromNullable(command.ASIN), + Optional.FromNullable(command.GoodreadsId), + Optional.FromNullable(command.LCCN), + Optional.FromNullable(command.OCLCNumber), + Optional.FromNullable(command.OpenLibraryId), + Optional.FromNullable(command.LibraryThingId), + Optional.FromNullable(command.GoogleBooksId), + Optional.FromNullable(command.BarnesAndNobleId), + Optional.FromNullable(command.AppleBooksId), domainIsbns, contributorIds, ratings: domainRatings diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs index 169a8424..54147686 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Errors; #endregion @@ -16,235 +17,339 @@ public class AddBookCommandValidator : AbstractValidator /// public AddBookCommandValidator() { - RuleFor(x => x.LibraryId) - .NotEmpty().WithMessage(Errors.WrittenContent.BookLibraryCannotBeNull.Description); - RuleFor(x => x.Path) - .NotEmpty().WithMessage(Errors.WrittenContent.BookPathCannotBeEmpty.Description); - RuleFor(x => x.Metadata) - .NotNull().WithMessage(Errors.Metadata.MetadataCannotBeNull.Description) + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.WrittenContent.BookLibraryCannotBeNull); + + RuleFor(command => command.Path) + .NotEmpty() + .WithError(Errors.WrittenContent.BookPathCannotBeEmpty); + + RuleFor(command => command.Metadata) + .NotNull() + .WithError(Errors.Metadata.MetadataCannotBeNull) .ChildRules(metadata => { metadata.RuleFor(m => m!.Title) - .NotEmpty().WithMessage(Errors.Metadata.TitleCannotBeEmpty.Description) - .MaximumLength(255).WithMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description); + .NotEmpty() + .WithError(Errors.Metadata.TitleCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + metadata.RuleFor(m => m!.OriginalTitle) - .MaximumLength(255).When(m => m!.OriginalTitle is not null) - .WithMessage(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong.Description); + .MaximumLength(255) + .When(m => m!.OriginalTitle is not null) + .WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + metadata.RuleFor(m => m!.Description) - .MaximumLength(2000).When(m => m!.Description is not null) - .WithMessage(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong.Description); + .MaximumLength(2000) + .When(m => m!.Description is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + metadata.RuleFor(m => m!.ReleaseInfo) - .NotNull().WithMessage(Errors.Metadata.ReleaseInfoCannotBeNull.Description) - .ChildRules(ri => + .NotNull() + .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) + .ChildRules(releaseInfo => { - ri.RuleFor(r => r!.OriginalReleaseYear) - .InclusiveBetween(1, 9999).When(r => r!.OriginalReleaseYear.HasValue) - .WithMessage(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Description); - ri.RuleFor(r => r!.ReReleaseYear) - .InclusiveBetween(1, 9999).When(r => r!.ReReleaseYear.HasValue) - .WithMessage(Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Description); - ri.RuleFor(r => r!.ReleaseCountry) - .Matches("^[A-Za-z]{2}$").When(r => r!.ReleaseCountry is not null) - .WithMessage(Errors.Metadata.CountryCodeMustBe2CharactersLong.Description); - ri.RuleFor(r => r!.ReleaseVersion) - .MaximumLength(50).When(r => r!.ReleaseVersion is not null) - .WithMessage(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong.Description); - ri.RuleFor(r => r!.OriginalReleaseYear) - .Must((releaseInfo, originalReleaseYear) => - !releaseInfo!.OriginalReleaseDate.HasValue || - !releaseInfo.OriginalReleaseYear.HasValue || - originalReleaseYear == releaseInfo.OriginalReleaseDate.Value.Year) + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReleaseCountry) + .Matches("^[A-Za-z]{2}$") + .When(r => r!.ReleaseCountry is not null) + .WithError(Errors.Metadata.CountryCodeMustBe2CharactersLong); + + releaseInfo.RuleFor(r => r!.ReleaseVersion) + .MaximumLength(50) + .When(r => r!.ReleaseVersion is not null) + .WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .Must((releaseInfoInstance, originalReleaseYear) => + !releaseInfoInstance!.OriginalReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year) .When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue) - .WithMessage(Errors.Metadata.OriginalReleaseDateAndYearMustMatch.Description); - ri.RuleFor(r => r!.ReReleaseYear) - .Must((releaseInfo, reReleaseYear) => - !releaseInfo!.ReReleaseDate.HasValue || - !releaseInfo.ReReleaseYear.HasValue || - reReleaseYear == releaseInfo.ReReleaseDate.Value.Year) + .WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.ReReleaseYear.HasValue || + reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year) .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue) - .WithMessage(Errors.Metadata.ReReleaseDateAndYearMustMatch.Description); - ri.RuleFor(r => r!.ReReleaseYear) - .Must((releaseInfo, reReleaseYear) => - !releaseInfo!.ReReleaseYear.HasValue || - !releaseInfo.OriginalReleaseYear.HasValue || - reReleaseYear >= releaseInfo.OriginalReleaseYear) - .When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue) - .WithMessage(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear.Description); - ri.RuleFor(r => r!.ReReleaseDate) - .Must((releaseInfo, reReleaseDate) => - !releaseInfo!.ReReleaseDate.HasValue || - !releaseInfo.OriginalReleaseDate.HasValue || - reReleaseDate >= releaseInfo.OriginalReleaseDate) + .WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseYear.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + reReleaseYear >= releaseInfoInstance.OriginalReleaseYear) + .When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + + releaseInfo.RuleFor(r => r!.ReReleaseDate) + .Must((releaseInfoInstance, reReleaseDate) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseDate.HasValue || + reReleaseDate >= releaseInfoInstance.OriginalReleaseDate) .When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue) - .WithMessage(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description); - ri.RuleFor(r => r!.ReReleaseYear) - .Must((releaseInfo, reReleaseYear) => - !releaseInfo!.ReReleaseDate.HasValue || - !releaseInfo.ReReleaseYear.HasValue || - reReleaseYear == releaseInfo.ReReleaseDate.Value.Year) + .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.ReReleaseYear.HasValue || + reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year) .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue) - .WithMessage(Errors.Metadata.ReReleaseDateAndYearMustMatch.Description); + .WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch); }); + metadata.RuleFor(m => m!.Genres) - .NotNull().WithMessage(Errors.Metadata.GenresListCannotBeNull.Description); + .NotNull() + .WithError(Errors.Metadata.GenresListCannotBeNull); + metadata.RuleForEach(m => m!.Genres) - .ChildRules(g => - g.RuleFor(genre => genre.Name) - .NotEmpty().WithMessage(Errors.Metadata.GenreNameCannotBeEmpty.Description) - .MaximumLength(50).WithMessage(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong.Description)); + .ChildRules(genre => + genre.RuleFor(g => g.Name) + .NotEmpty() + .WithError(Errors.Metadata.GenreNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong)); + metadata.RuleFor(m => m!.Tags) - .NotNull().WithMessage(Errors.Metadata.TagsListCannotBeNull.Description); + .NotNull() + .WithError(Errors.Metadata.TagsListCannotBeNull); + + metadata.RuleForEach(m => m!.Tags) - .ChildRules(t => - t.RuleFor(tag => tag.Name) - .NotEmpty().WithMessage(Errors.Metadata.TagNameCannotBeEmpty.Description) - .MaximumLength(50).WithMessage(Errors.Metadata.TagNameMustBeMaximum50CharactersLong.Description)); - metadata.RuleFor(m => m!.Language) - .Custom((language, context) => - { - if (language is null) - return; - - if (string.IsNullOrEmpty(language.LanguageCode)) - context.AddFailure("Language.LanguageCode", Errors.Metadata.LanguageCodeCannotBeEmpty.Description); - else if (language.LanguageCode.Length > 2) - context.AddFailure("Language.LanguageCode", Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description); - - if (string.IsNullOrEmpty(language.LanguageName)) - context.AddFailure("Language.LanguageName", Errors.Metadata.LanguageNameCannotBeEmpty.Description); - else if (language.LanguageName.Length > 50) - context.AddFailure("Language.LanguageName", Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description); - - if (language.NativeName != null && language.NativeName.Length > 50) - context.AddFailure("Language.NativeName", Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description); - }); - metadata.RuleFor(m => m!.OriginalLanguage) - .Custom((language, context) => - { - if (language is null) - return; - - if (string.IsNullOrEmpty(language.LanguageCode)) - context.AddFailure("OriginalLanguage.LanguageCode", Errors.Metadata.LanguageCodeCannotBeEmpty.Description); - else if (language.LanguageCode.Length > 2) - context.AddFailure("OriginalLanguage.LanguageCode", Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description); - - if (string.IsNullOrEmpty(language.LanguageName)) - context.AddFailure("OriginalLanguage.LanguageName", Errors.Metadata.LanguageNameCannotBeEmpty.Description); - else if (language.LanguageName.Length > 50) - context.AddFailure("OriginalLanguage.LanguageName", Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description); - - if (language.NativeName != null && language.NativeName.Length > 50) - context.AddFailure("OriginalLanguage.NativeName", Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description); - }); + .ChildRules(tag => + tag.RuleFor(t => t.Name) + .NotEmpty() + .WithError(Errors.Metadata.TagNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong)); + + metadata.RuleFor(m => m!.Language!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .MaximumLength(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.Language!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.Language!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode) + .NotEmpty().WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .MaximumLength(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + metadata.RuleFor(m => m!.Publisher) - .MaximumLength(100).When(m => m!.Publisher is not null) - .WithMessage(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong.Description); + .MaximumLength(100) + .When(m => m!.Publisher is not null) + .WithError(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong); + metadata.RuleFor(m => m!.PageCount) - .GreaterThan(0).When(m => m!.PageCount.HasValue) - .WithMessage(Errors.WrittenContent.PageCountMustBeGreaterThanZero.Description); + .GreaterThan(0) + .When(m => m!.PageCount.HasValue) + .WithError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); }); - RuleFor(x => x.Format) - .IsInEnum().When(f => f.Format is not null).WithMessage(Errors.WrittenContent.UnknownBookFormat.Description); - RuleFor(x => x.Edition) - .MaximumLength(50).When(x => x.Edition is not null) - .WithMessage(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong.Description); - RuleFor(x => x.VolumeNumber) - .GreaterThan(0).When(x => x.VolumeNumber.HasValue) - .WithMessage(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Description); - RuleFor(x => x.Series) - .ChildRules(s => - s.RuleFor(series => series!.Title) - .NotEmpty().WithMessage(Errors.Metadata.TitleCannotBeEmpty.Description) - .MaximumLength(255)).WithMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description) - .When(x => x.Series is not null); - RuleFor(x => x.ASIN) - .Length(10).When(x => x.ASIN is not null) - .WithMessage(Errors.WrittenContent.AsinMustBe10CharactersLong.Description); - RuleFor(x => x.GoodreadsId) - .Matches(@"^\d+$").When(x => x.GoodreadsId is not null) - .WithMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Description); - RuleFor(x => x.LCCN) - .Matches(@"^[a-z]{0,3}\d{8,10}$").WithMessage(Errors.WrittenContent.InvalidLccnFormat.Description) - .When(x => x.LCCN is not null); - RuleFor(x => x.OCLCNumber) - .Matches(@"^(ocm\d{8}|ocn\d{9,}|on\d{10,}|\(OCoLC\)\d{8,}|\d{8,})$").When(x => x.OCLCNumber is not null) - .WithMessage(Errors.WrittenContent.InvalidOclcFormat.Description); - RuleFor(x => x.OpenLibraryId) - .Matches(@"^OL[1-9]\d*[AMW]$").When(x => x.OpenLibraryId is not null) - .WithMessage(Errors.WrittenContent.InvalidOpenLibraryId.Description); - RuleFor(x => x.LibraryThingId) - .MaximumLength(50).When(x => x.LibraryThingId is not null) - .WithMessage(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong.Description); - RuleFor(x => x.GoogleBooksId) - .Length(12).WithMessage(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong.Description) - .Matches(@"^[A-Za-z0-9_-]{12}$").WithMessage(Errors.WrittenContent.InvalidGoogleBooksIdFormat.Description) - .When(x => x.GoogleBooksId is not null); - RuleFor(x => x.BarnesAndNobleId) - .Length(10).WithMessage(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong.Description) - .Matches(@"^\d{10}$").WithMessage(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat.Description) - .When(x => x.BarnesAndNobleId is not null); - RuleFor(x => x.AppleBooksId) - .Matches(@"^id\d+$").When(x => x.AppleBooksId is not null) - .WithMessage(Errors.WrittenContent.InvalidAppleBooksIdFormat.Description); - RuleFor(x => x.ISBNs) - .NotNull().WithMessage(Errors.WrittenContent.IsbnListCannotBeNull.Description); - RuleForEach(x => x.ISBNs) + + RuleFor(command => command.Format) + .IsInEnum() + .When(command => command.Format is not null) + .WithError(Errors.WrittenContent.UnknownBookFormat); + + RuleFor(command => command.Edition) + .MaximumLength(50) + .When(command => command.Edition is not null) + .WithError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong); + + RuleFor(command => command.VolumeNumber) + .GreaterThan(0) + .When(command => command.VolumeNumber.HasValue) + .WithError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); + + RuleFor(command => command.Series) + .ChildRules(series => + series.RuleFor(s => s!.Title) + .NotEmpty() + .WithError(Errors.Metadata.TitleCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong)) + .When(command => command.Series is not null); + + RuleFor(command => command.ASIN) + .Length(10) + .When(command => command.ASIN is not null) + .WithError(Errors.WrittenContent.AsinMustBe10CharactersLong); + + RuleFor(command => command.GoodreadsId) + .Matches(@"^\d+$") + .When(command => command.GoodreadsId is not null) + .WithError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); + + RuleFor(command => command.LCCN) + .Matches(@"^[a-z]{0,3}\d{8,10}$") + .When(command => command.LCCN is not null) + .WithError(Errors.WrittenContent.InvalidLccnFormat); + + RuleFor(command => command.OCLCNumber) + .Matches(@"^(ocm\d{8}|ocn\d{9,}|on\d{10,}|\(OCoLC\)\d{8,}|\d{8,})$").When(command => command.OCLCNumber is not null) + .WithError(Errors.WrittenContent.InvalidOclcFormat); + + RuleFor(command => command.OpenLibraryId) + .Matches(@"^OL[1-9]\d*[AMW]$") + .When(command => command.OpenLibraryId is not null) + .WithError(Errors.WrittenContent.InvalidOpenLibraryId); + + RuleFor(command => command.LibraryThingId) + .MaximumLength(50) + .When(command => command.LibraryThingId is not null) + .WithError(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong); + + RuleFor(command => command.GoogleBooksId) + .Length(12) + .When(command => command.GoogleBooksId is not null) + .WithError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong) + .Matches(@"^[A-Za-z0-9_-]{12}$") + .When(command => command.GoogleBooksId is not null) + .WithError(Errors.WrittenContent.InvalidGoogleBooksIdFormat); + + RuleFor(command => command.BarnesAndNobleId) + .Length(10) + .When(command => command.BarnesAndNobleId is not null) + .WithError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong) + .Matches(@"^\d{10}$") + .When(command => command.BarnesAndNobleId is not null) + .WithError(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat); + + RuleFor(command => command.AppleBooksId) + .Matches(@"^id\d+$") + .When(command => command.AppleBooksId is not null) + .WithError(Errors.WrittenContent.InvalidAppleBooksIdFormat); + + RuleFor(command => command.ISBNs) + .NotNull() + .WithError(Errors.WrittenContent.IsbnListCannotBeNull); + + RuleForEach(command => command.ISBNs) .ChildRules(isbn => { isbn.RuleFor(i => i.Value) - .NotEmpty().WithMessage(Errors.WrittenContent.IsbnValueCannotBeEmpty.Description) - .Matches(i => i.Format == IsbnFormat.Isbn13 - ? @"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$" - : @"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$") - .WithMessage(i => i.Format == IsbnFormat.Isbn13 - ? Errors.WrittenContent.InvalidIsbn13Format.Description - : Errors.WrittenContent.InvalidIsbn10Format.Description); + .NotEmpty() + .WithError(Errors.WrittenContent.IsbnValueCannotBeEmpty); + + isbn.RuleFor(i => i.Value) + .Matches(@"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$") + .When(i => i.Format == IsbnFormat.Isbn13) + .WithError(Errors.WrittenContent.InvalidIsbn13Format); + + isbn.RuleFor(i => i.Value) + .Matches(@"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$") + .When(i => i.Format == IsbnFormat.Isbn10) + .WithError(Errors.WrittenContent.InvalidIsbn10Format); + isbn.RuleFor(i => i.Format) - .IsInEnum().WithMessage(Errors.WrittenContent.UnknownIsbnFormat.Description); + .IsInEnum() + .WithError(Errors.WrittenContent.UnknownIsbnFormat); }); - RuleFor(x => x.Contributors) - .NotNull().WithMessage(Errors.MediaContributor.ContributorsListCannotBeNull.Description); - RuleForEach(x => x.Contributors) + + RuleFor(command => command.Contributors) + .NotNull() + .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); + + RuleForEach(command => command.Contributors) .ChildRules(contributor => { contributor.RuleFor(c => c.Name) - .NotNull().WithMessage(Errors.MediaContributor.ContributorNameCannotBeEmpty.Description) + .NotNull() + .WithError(Errors.MediaContributor.ContributorNameCannotBeEmpty) .ChildRules(name => { name.RuleFor(n => n!.DisplayName) - .NotNull().WithMessage(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description) - .NotEmpty().WithMessage(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description) - .MaximumLength(100).WithMessage(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong.Description); + .NotNull() + .WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty) + .NotEmpty() + .WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty) + .MaximumLength(100) + .WithError(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong); + name.RuleFor(n => n!.LegalName) - .MaximumLength(100).When(n => n!.LegalName is not null) - .WithMessage(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong.Description); + .MaximumLength(100) + .When(n => n!.LegalName is not null) + .WithError(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong); }); + contributor.RuleFor(c => c.Role) - .NotNull().WithMessage(Errors.MediaContributor.ContributorRoleCannotBeNull.Description) + .NotNull() + .WithError(Errors.MediaContributor.ContributorRoleCannotBeNull) .ChildRules(role => { role.RuleFor(r => r!.Name) - .NotEmpty().WithMessage(Errors.MediaContributor.RoleNameCannotBeEmpty.Description) - .MaximumLength(50).WithMessage(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong.Description); + .NotEmpty() + .WithError(Errors.MediaContributor.RoleNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong); role.RuleFor(r => r!.Category) - .NotEmpty().WithMessage(Errors.MediaContributor.RoleCategoryCannotBeEmpty.Description) - .MaximumLength(50).WithMessage(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong.Description); + .NotEmpty() + .WithError(Errors.MediaContributor.RoleCategoryCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong); }); }); - RuleFor(x => x.Ratings) - .NotNull().WithMessage(Errors.Metadata.RatingsListCannotBeNull.Description); - RuleForEach(x => x.Ratings) + + RuleFor(command => command.Ratings) + .NotNull() + .WithError(Errors.Metadata.RatingsListCannotBeNull); + + RuleForEach(command => command.Ratings) .ChildRules(rating => { rating.RuleFor(r => r.Value) - .GreaterThan(0).WithMessage(Errors.Metadata.RatingValueMustBePositive.Description) - .Must((r, value) => value <= r.MaxValue).WithMessage(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Description); + .GreaterThan(0) + .WithError(Errors.Metadata.RatingValueMustBePositive) + .Must((ratingInstance, value) => value <= ratingInstance.MaxValue) + .WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + rating.RuleFor(r => r.MaxValue) - .GreaterThan(0).WithMessage(Errors.Metadata.RatingMaxValueMustBePositive.Description); + .GreaterThan(0) + .WithError(Errors.Metadata.RatingMaxValueMustBePositive); + rating.RuleFor(r => r.VoteCount) - .GreaterThanOrEqualTo(0).When(r => r.VoteCount.HasValue) - .WithMessage(Errors.Metadata.RatingVoteCountMustBePositive.Description); + .GreaterThanOrEqualTo(0) + .When(r => r.VoteCount.HasValue) + .WithError(Errors.Metadata.RatingVoteCountMustBePositive); }); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs index a70060c9..6147d3de 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs @@ -1,9 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Mediator; +using Lumina.Application.Common.CQRS; using System; -using System.Collections.Generic; #endregion namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; @@ -14,4 +11,4 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar /// The Id of the media library whose books are retrieved. public record GetBooksQuery( Guid LibraryId -) : IRequest>>; +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs index 6f1af200..078a3d42 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -16,7 +16,7 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar /// /// Handler for the query to get all books. /// -public class GetBooksQueryHandler : IRequestHandler>> +public class GetBooksQueryHandler : IQueryHandler>> { private readonly IUnitOfWork _unitOfWork; @@ -32,17 +32,17 @@ public class GetBooksQueryHandler : IRequestHandler /// Handles the query to get all books. /// - /// The request to be handled. + /// The query to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a collection of , or an error message. /// - public async ValueTask>> Handle(GetBooksQuery request, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetBooksQuery query, CancellationToken cancellationToken) { // get a books repository IBookRepository bookRepository = _unitOfWork.GetRepository(); // get all books of the media library from the book repository - ErrorOr> getBooksResult = await bookRepository.GetByLibraryIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false); + ErrorOr> getBooksResult = await bookRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); return getBooksResult.Match(result => ErrorOrFactory.From(getBooksResult.Value.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommand.cs index 1a695d7e..a1ab58c2 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommand.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommand.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Mediator; +using Lumina.Application.Common.CQRS; using System; using System.Collections.Generic; #endregion @@ -15,4 +14,4 @@ namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProvide public record ReorderLibraryMetadataProvidersCommand( Guid LibraryId, IReadOnlyList PluginIds -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs index 1c1a2034..d1fb76bd 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs @@ -1,9 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; -using Mediator; +using Lumina.Application.Common.Infrastructure.Validation; using System; using System.Collections.Generic; using System.Linq; @@ -16,38 +17,45 @@ namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProvide /// /// Handler for the command to reorder the metadata providers of a media library. /// -public class ReorderLibraryMetadataProvidersCommandHandler : IRequestHandler> +public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. - public ReorderLibraryMetadataProvidersCommandHandler(IUnitOfWork unitOfWork) + /// Injected validator for application validation rules. + public ReorderLibraryMetadataProvidersCommandHandler(IUnitOfWork unitOfWork, IValidator validator) { _unitOfWork = unitOfWork; + _validator = validator; } /// /// Handles the command to reorder the metadata providers of a media library. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An representing either a successful operation, or an error. /// - public async ValueTask> Handle(ReorderLibraryMetadataProvidersCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(ReorderLibraryMetadataProvidersCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository(); - ErrorOr> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false); + ErrorOr> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsError) return getConfigurationsResult.Errors; Dictionary configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId); - for (int rank = 0; rank < request.PluginIds.Count; rank++) + for (int rank = 0; rank < command.PluginIds.Count; rank++) { - Guid pluginId = request.PluginIds[rank]; + Guid pluginId = command.PluginIds[rank]; if (configurationsByPluginId.TryGetValue(pluginId, out LibraryMetadataProviderConfigurationEntity? configuration)) { configuration.Rank = rank + 1; diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs index aff5200e..73e9e473 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; #endregion @@ -15,10 +16,14 @@ public class ReorderLibraryMetadataProvidersCommandValidator : AbstractValidator /// public ReorderLibraryMetadataProvidersCommandValidator() { - RuleFor(x => x.LibraryId) - .NotEmpty().WithMessage(Errors.Plugins.LibraryIdCannotBeEmpty.Description); - RuleFor(x => x.PluginIds) - .NotNull().WithMessage(Errors.Plugins.PluginIdsListCannotBeNull.Description) - .NotEmpty().WithMessage(Errors.Plugins.PluginIdsListCannotBeEmpty.Description); + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); + + RuleFor(command => command.PluginIds) + .NotNull() + .WithError(Errors.Plugins.PluginIdsListCannotBeNull) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdsListCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommand.cs index b0e98e20..c81174c5 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommand.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommand.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Mediator; +using Lumina.Application.Common.CQRS; using System; #endregion @@ -16,4 +15,4 @@ public record SetLibraryMetadataProviderEnabledCommand( Guid LibraryId, Guid PluginId, bool IsEnabled -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs index 3d4be916..28ba686c 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs @@ -1,9 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; -using Mediator; +using Lumina.Application.Common.Infrastructure.Validation; using System; using System.Collections.Generic; using System.Linq; @@ -16,31 +17,38 @@ namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEna /// /// Handler for the command to enable or disable a metadata provider for a media library. /// -public class SetLibraryMetadataProviderEnabledCommandHandler : IRequestHandler> +public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. - public SetLibraryMetadataProviderEnabledCommandHandler(IUnitOfWork unitOfWork) + /// Injected validator for application validation rules. + public SetLibraryMetadataProviderEnabledCommandHandler(IUnitOfWork unitOfWork, IValidator validator) { _unitOfWork = unitOfWork; + _validator = validator; } /// /// Handles the command to enable or disable a metadata provider for a media library. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An representing either a successful operation, or an error. /// - public async ValueTask> Handle(SetLibraryMetadataProviderEnabledCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(SetLibraryMetadataProviderEnabledCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository(); - ErrorOr getConfigurationResult = await configurationRepository.GetByLibraryAndPluginIdAsync(request.LibraryId, request.PluginId, cancellationToken).ConfigureAwait(false); + ErrorOr getConfigurationResult = await configurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); if (getConfigurationResult.IsError) return getConfigurationResult.Errors; @@ -48,21 +56,21 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : IRequestHandler> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false); + ErrorOr> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsError) return getConfigurationsResult.Errors; int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1; configuration = new LibraryMetadataProviderConfigurationEntity { Id = Guid.NewGuid(), - LibraryId = request.LibraryId, - PluginId = request.PluginId, - IsEnabled = request.IsEnabled, + LibraryId = command.LibraryId, + PluginId = command.PluginId, + IsEnabled = command.IsEnabled, Rank = nextRank, CreatedOnUtc = default, CreatedBy = default, diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs index fc27be68..f9faf160 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; #endregion @@ -15,9 +16,12 @@ public class SetLibraryMetadataProviderEnabledCommandValidator : AbstractValidat /// public SetLibraryMetadataProviderEnabledCommandValidator() { - RuleFor(x => x.LibraryId) - .NotEmpty().WithMessage(Errors.Plugins.LibraryIdCannotBeEmpty.Description); - RuleFor(x => x.PluginId) - .NotEmpty().WithMessage(Errors.Plugins.PluginIdCannotBeEmpty.Description); + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); + + RuleFor(command => command.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommand.cs index e160d675..94d98136 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommand.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommand.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Mediator; +using Lumina.Application.Common.CQRS; using System; using System.Collections.Generic; #endregion @@ -15,4 +14,4 @@ namespace Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; public record UpdatePluginSettingsCommand( Guid PluginId, IReadOnlyDictionary? Settings -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs index e97a118b..47d0e63b 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; -using Mediator; +using Lumina.Application.Common.Infrastructure.Validation; +using System.Collections.Generic; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -13,32 +15,39 @@ namespace Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; /// /// Handler for the command to update the settings of a plugin. /// -public class UpdatePluginSettingsCommandHandler : IRequestHandler> +public class UpdatePluginSettingsCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. - public UpdatePluginSettingsCommandHandler(IUnitOfWork unitOfWork) + /// Injected validator for application validation rules. + public UpdatePluginSettingsCommandHandler(IUnitOfWork unitOfWork, IValidator validator) { _unitOfWork = unitOfWork; + _validator = validator; } /// /// Handles the command to update the settings of a plugin. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An representing either a successful operation, or an error. /// - public async ValueTask> Handle(UpdatePluginSettingsCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(UpdatePluginSettingsCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + IPluginRepository pluginRepository = _unitOfWork.GetRepository(); - string? settingsJson = request.Settings is not null ? JsonSerializer.Serialize(request.Settings) : null; - ErrorOr updateResult = await pluginRepository.UpdateSettingsAsync(request.PluginId, settingsJson, cancellationToken).ConfigureAwait(false); + string? settingsJson = command.Settings is not null ? JsonSerializer.Serialize(command.Settings) : null; + ErrorOr updateResult = await pluginRepository.UpdateSettingsAsync(command.PluginId, settingsJson, cancellationToken).ConfigureAwait(false); if (updateResult.IsError) return updateResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs index 454fcfec..aca3fa33 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; #endregion @@ -15,7 +16,8 @@ public class UpdatePluginSettingsCommandValidator : AbstractValidator public UpdatePluginSettingsCommandValidator() { - RuleFor(x => x.PluginId) - .NotEmpty().WithMessage(Errors.Plugins.PluginIdCannotBeEmpty.Description); + RuleFor(command => command.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQuery.cs index e73ecb00..6b0e6f9f 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQuery.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQuery.cs @@ -1,9 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Plugins; -using Mediator; +using Lumina.Application.Common.CQRS; using System; -using System.Collections.Generic; #endregion namespace Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; @@ -14,4 +11,4 @@ namespace Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; /// The Id of the media library whose metadata providers are retrieved. public record GetLibraryMetadataProvidersQuery( Guid LibraryId -) : IRequest>>; +) : IQuery; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs index 46e89a7a..367fabef 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.Plugins; using Lumina.Contracts.Responses.Plugins; -using Mediator; using System; using System.Collections.Generic; using System.Linq; @@ -18,7 +18,7 @@ namespace Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; /// /// Handler for the query to get the metadata providers configured for a media library. /// -public class GetLibraryMetadataProvidersQueryHandler : IRequestHandler>> +public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler>> { private readonly IUnitOfWork _unitOfWork; @@ -34,15 +34,15 @@ public class GetLibraryMetadataProvidersQueryHandler : IRequestHandler /// Handles the query to get the metadata providers configured for a media library. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a collection of , or an error. /// - public async ValueTask>> Handle(GetLibraryMetadataProvidersQuery request, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetLibraryMetadataProvidersQuery query, CancellationToken cancellationToken) { ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository(); - ErrorOr> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false); + ErrorOr> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsError) return getConfigurationsResult.Errors; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQuery.cs index a7daf05b..19da1e05 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQuery.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQuery.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Plugins; -using Mediator; +using Lumina.Application.Common.CQRS; using System; #endregion @@ -13,4 +11,4 @@ namespace Lumina.Application.Core.Plugins.Queries.GetPluginSettings; /// The unique identifier of the plugin. public record GetPluginSettingsQuery( Guid PluginId -) : IRequest>; +) : IQuery; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs index ce66191a..50a85128 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; @@ -8,7 +9,6 @@ using Lumina.Application.Common.Mapping.Plugins; using Lumina.Contracts.Responses.Plugins; using Lumina.Domain.SharedKernel.Common.Errors; using Lumina.Plugins.Contracts.Core.Plugins; -using Mediator; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -20,7 +20,7 @@ namespace Lumina.Application.Core.Plugins.Queries.GetPluginSettings; /// /// Handler for the query to get the settings of a plugin and their schema. /// -public class GetPluginSettingsQueryHandler : IRequestHandler> +public class GetPluginSettingsQueryHandler : IQueryHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IPluginManager _pluginManager; @@ -39,15 +39,15 @@ public class GetPluginSettingsQueryHandler : IRequestHandler /// Handles the query to get the settings of a plugin and their schema. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a , or an error. /// - public async ValueTask> Handle(GetPluginSettingsQuery request, CancellationToken cancellationToken) + public async Task> HandleAsync(GetPluginSettingsQuery query, CancellationToken cancellationToken) { IPluginRepository pluginRepository = _unitOfWork.GetRepository(); - ErrorOr getPluginResult = await pluginRepository.GetByIdAsync(request.PluginId, cancellationToken).ConfigureAwait(false); + ErrorOr getPluginResult = await pluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false); if (getPluginResult.IsError) return getPluginResult.Errors; PluginEntity? pluginEntity = getPluginResult.Value; @@ -55,10 +55,10 @@ public class GetPluginSettingsQueryHandler : IRequestHandler schema = loadedPlugin is not null ? loadedPlugin.GetSettingsSchema().Select(setting => setting.ToResponse()).ToList() : []; - return new PluginSettingsResponse(request.PluginId, schema, pluginEntity.ToSettings()); + return new PluginSettingsResponse(query.PluginId, schema, pluginEntity.ToSettings()); } } diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQuery.cs index 2a840280..80590846 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQuery.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQuery.cs @@ -1,8 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Plugins; -using Mediator; -using System.Collections.Generic; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.Plugins.Queries.GetPlugins; @@ -10,4 +7,4 @@ namespace Lumina.Application.Core.Plugins.Queries.GetPlugins; /// /// Query for getting all the detected plugins. /// -public record GetPluginsQuery() : IRequest>>; +public record GetPluginsQuery() : IQuery; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs index fe8a7292..50777d81 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.Plugins; using Lumina.Contracts.Responses.Plugins; -using Mediator; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -17,7 +17,7 @@ namespace Lumina.Application.Core.Plugins.Queries.GetPlugins; /// /// Handler for the query to get all the detected plugins. /// -public class GetPluginsQueryHandler : IRequestHandler>> +public class GetPluginsQueryHandler : IQueryHandler>> { private readonly IUnitOfWork _unitOfWork; @@ -33,12 +33,12 @@ public class GetPluginsQueryHandler : IRequestHandler /// Handles the query to get all the detected plugins. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a collection of , or an error. /// - public async ValueTask>> Handle(GetPluginsQuery request, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetPluginsQuery query, CancellationToken cancellationToken) { IPluginRepository pluginRepository = _unitOfWork.GetRepository(); ErrorOr> getPluginsResult = await pluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommand.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommand.cs index 5bc40ef0..0bd2528d 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommand.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommand.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Authentication; -using Mediator; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; @@ -18,4 +16,4 @@ public record ChangePasswordCommand( string? CurrentPassword, string? NewPassword, string? NewPasswordConfirm -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs index 3cd045b4..2ce0efcc 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs @@ -1,13 +1,15 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.Authentication; -using Mediator; using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -17,44 +19,52 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Change /// /// Handler for the command to change the password of a user account. /// -public class ChangePasswordCommandHandler : IRequestHandler> +public class ChangePasswordCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IPasswordHashService _hashService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. /// Injected service for password hashing functionality. + /// Injected validator for application validation rules. public ChangePasswordCommandHandler( IUnitOfWork unitOfWork, - IPasswordHashService hashService) + IPasswordHashService hashService, + IValidator validator) { _unitOfWork = unitOfWork; _hashService = hashService; + _validator = validator; } /// /// Handles the command to change the password of an account. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a successfully created , or an error message. /// - public async ValueTask> Handle(ChangePasswordCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(ChangePasswordCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + IUserRepository userRepository = _unitOfWork.GetRepository(); - ErrorOr getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false); + ErrorOr getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsError) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.UsernameDoesNotExist; // validate if the current password is correct - if (!_hashService.CheckStringAgainstHash(request.CurrentPassword!, Uri.UnescapeDataString(getUserResult.Value.Password!))) + if (!_hashService.CheckStringAgainstHash(command.CurrentPassword!, Uri.UnescapeDataString(getUserResult.Value.Password!))) return Errors.Authentication.InvalidCurrentPassword; - getUserResult.Value.Password = Uri.EscapeDataString(_hashService.HashString(request.NewPassword!)); + getUserResult.Value.Password = Uri.EscapeDataString(_hashService.HashString(command.NewPassword!)); // if the password change was initiated via a password reset, remote the temporary password that was generated in the process getUserResult.Value.TempPassword = null; getUserResult.Value.TempPasswordCreated = null; diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidator.cs index a1168e39..1c880f1a 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidator.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidator.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; #endregion namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; @@ -15,12 +16,28 @@ public class ChangePasswordCommandValidator : AbstractValidator public ChangePasswordCommandValidator() { - RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); - RuleFor(x => x.CurrentPassword).NotEmpty().WithMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description) - .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description); - RuleFor(x => x.NewPassword).NotEmpty().WithMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description) - .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description); - RuleFor(x => x.NewPasswordConfirm).NotEmpty().WithMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description); - RuleFor(x => x.NewPassword).Equal(x => x.NewPasswordConfirm).WithMessage(Errors.Authentication.PasswordsNotMatch.Description); + RuleFor(command => command.Username) + .NotEmpty() + .WithError(Errors.Authentication.UsernameCannotBeEmpty); + + RuleFor(command => command.CurrentPassword) + .NotEmpty() + .WithError(Errors.Authentication.CurrentPasswordCannotBeEmpty) + .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$") + .WithError(Errors.Authentication.InvalidPassword); + + RuleFor(command => command.NewPassword) + .NotEmpty() + .WithError(Errors.Authentication.NewPasswordCannotBeEmpty) + .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$") + .WithError(Errors.Authentication.InvalidPassword); + + RuleFor(command => command.NewPasswordConfirm) + .NotEmpty() + .WithError(Errors.Authentication.NewPasswordConfirmCannotBeEmpty); + + RuleFor(command => command.NewPassword) + .Equal(command => command.NewPasswordConfirm) + .WithError(Errors.Authentication.PasswordsNotMatch); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommand.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommand.cs index a4854a4e..f171b908 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommand.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommand.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Authentication; -using Mediator; +using Lumina.Application.Common.CQRS; using System.Diagnostics; #endregion @@ -16,4 +14,4 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Recove public record class RecoverPasswordCommand( string? Username, string? TotpCode -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs index a9da263b..dea38d92 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs @@ -1,14 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.Authentication; -using Mediator; using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -18,12 +20,13 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Recove /// /// Handler for the command to recover the password of an account. /// -public class RecoverPasswordCommandHandler : IRequestHandler> +public class RecoverPasswordCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IPasswordHashService _hashService; private readonly ITotpTokenGenerator _totpTokenGenerator; private readonly ICryptographyService _cryptographyService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. @@ -32,31 +35,38 @@ public class RecoverPasswordCommandHandler : IRequestHandlerInjected service for password hashing functionality. /// Injected service for generating and validating TOTP tokens. /// Injected service for cryptographic functionality. + /// Injected validator for application validation rules. public RecoverPasswordCommandHandler( IUnitOfWork unitOfWork, IPasswordHashService hashService, ITotpTokenGenerator totpTokenGenerator, - ICryptographyService cryptographyService) + ICryptographyService cryptographyService, + IValidator validator) { _unitOfWork = unitOfWork; _hashService = hashService; _totpTokenGenerator = totpTokenGenerator; _cryptographyService = cryptographyService; + _validator = validator; } /// /// Handles the command to recover the password of an account. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a successfully created , or an error message. /// - public async ValueTask> Handle(RecoverPasswordCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(RecoverPasswordCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + // check if any users already exists IUserRepository userRepository = _unitOfWork.GetRepository(); - ErrorOr getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false); + ErrorOr getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsError) return getUserResult.Errors; else if (getUserResult.Value is null) @@ -67,10 +77,10 @@ public class RecoverPasswordCommandHandler : IRequestHandler public RecoverPasswordCommandValidator() { - RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); - RuleFor(x => x.TotpCode).NotEmpty().WithMessage(Errors.Authentication.TotpCannotBeEmpty.Description); - RuleFor(x => x.TotpCode).Length(6).WithMessage(Errors.Authentication.InvalidTotpCode.Description); - RuleFor(x => x.TotpCode).Matches(@"^[0-9]{6}$").WithMessage(Errors.Authentication.InvalidTotpCode.Description); + RuleFor(command => command.Username) + .NotEmpty() + .WithError(Errors.Authentication.UsernameCannotBeEmpty); + + RuleFor(command => command.TotpCode) + .NotEmpty() + .WithError(Errors.Authentication.TotpCannotBeEmpty); + + RuleFor(command => command.TotpCode) + .Length(6) + .WithError(Errors.Authentication.InvalidTotpCode); + + RuleFor(command => command.TotpCode) + .Matches(@"^[0-9]{6}$") + .WithError(Errors.Authentication.InvalidTotpCode); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommand.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommand.cs index d9e29c05..aa36ec22 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommand.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommand.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Authentication; -using Mediator; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; @@ -18,4 +16,4 @@ public record RegisterUserCommand( string? Password, string? PasswordConfirm, bool Use2fa -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs index 35abe638..b501be28 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; @@ -7,9 +8,10 @@ using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.Authentication; -using Mediator; using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -19,7 +21,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Regist /// /// Handler for the command to register a new user account. /// -public class RegisterUserCommandHandler : IRequestHandler> +public class RegisterUserCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IPasswordHashService _hashService; @@ -27,6 +29,7 @@ public class RegisterUserCommandHandler : IRequestHandler _validator; /// /// Initializes a new instance of the class. @@ -37,13 +40,15 @@ public class RegisterUserCommandHandler : IRequestHandlerInjected service for generating and validating TOTP tokens. /// Injected service for generating QR codes. /// Injected service for time related concerns. + /// Injected validator for application validation rules. public RegisterUserCommandHandler( IUnitOfWork unitOfWork, IPasswordHashService hashService, ICryptographyService cryptographyService, ITotpTokenGenerator totpTokenGenerator, IQRCodeGenerator qRCodeGenerator, - IDateTimeProvider dateTimeProvider) + IDateTimeProvider dateTimeProvider, + IValidator validator) { _unitOfWork = unitOfWork; _hashService = hashService; @@ -51,21 +56,26 @@ public class RegisterUserCommandHandler : IRequestHandler /// Handles the command to register an account. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a successfully created , or an error message. /// - public async ValueTask> Handle(RegisterUserCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(RegisterUserCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + // check if any users already exists (admin account is only set once!) IUserRepository userRepository = _unitOfWork.GetRepository(); - ErrorOr getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false); + ErrorOr getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsError) return getUserResult.Errors; else if (getUserResult.Value is not null) @@ -75,8 +85,8 @@ public class RegisterUserCommandHandler : IRequestHandler public RegisterUserCommandValidator() { - RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description) - .Length(3, 255).WithMessage(Errors.Authentication.UsernameMustBeBetween3And255CharactersLong.Description) + RuleFor(command => command.Username) + .NotEmpty() + .WithError(Errors.Authentication.UsernameCannotBeEmpty) + .Length(3, 255) + .WithError(Errors.Authentication.UsernameMustBeBetween3And255CharactersLong) .Matches("^[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]$") // only allow letters, numbers, dots, underscores and hyphens, and must start and end with letter or number - .WithMessage(Errors.Authentication.InvalidUsername.Description); - RuleFor(x => x.Password).NotEmpty().WithMessage(Errors.Authentication.PasswordCannotBeEmpty.Description) - .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description); - RuleFor(x => x.PasswordConfirm).NotEmpty().WithMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); - RuleFor(x => x.Password).Equal(x => x.PasswordConfirm).WithMessage(Errors.Authentication.PasswordsNotMatch.Description); + .WithError(Errors.Authentication.InvalidUsername); + + RuleFor(command => command.Password) + .NotEmpty() + .WithError(Errors.Authentication.PasswordCannotBeEmpty) + .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$") + .WithError(Errors.Authentication.InvalidPassword); + + RuleFor(command => command.PasswordConfirm) + .NotEmpty() + .WithError(Errors.Authentication.PasswordConfirmCannotBeEmpty); + + RuleFor(command => command.Password) + .Equal(command => command.PasswordConfirm) + .WithError(Errors.Authentication.PasswordsNotMatch); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQuery.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQuery.cs index 3361cc85..4ec59cab 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQuery.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQuery.cs @@ -1,8 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.UsersManagement.Users; -using Mediator; -using System.Collections.Generic; +using Lumina.Application.Common.CQRS; #endregion namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUsers; @@ -10,4 +7,4 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUser /// /// Query for retrieving the list of users. /// -public record GetUsersQuery() : IRequest>>; +public record GetUsersQuery() : IQuery; diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs index dcd26431..7b20ba85 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; @@ -9,7 +10,6 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Common.Mapping.UsersManagement.Users; using Lumina.Contracts.Responses.UsersManagement.Users; -using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -20,7 +20,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUser /// /// Handler for the query to retrieve the list of users. /// -public class GetUsersQueryHandler : IRequestHandler>> +public class GetUsersQueryHandler : IQueryHandler>> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; @@ -42,12 +42,12 @@ public class GetUsersQueryHandler : IRequestHandler /// Handles the query to retrieve the list of users. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a collection of , or an error message. /// - public async ValueTask>> Handle(GetUsersQuery request, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetUsersQuery query, CancellationToken cancellationToken) { // only admins can see the list of users bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQuery.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQuery.cs index 003e1fa1..eb2621b6 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQuery.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQuery.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Authentication; -using Mediator; +using Lumina.Application.Common.CQRS; using System.Diagnostics; #endregion @@ -18,4 +16,4 @@ public record LoginUserQuery( string? Username, string? Password, string? TotpCode = null -) : IRequest>; +) : IQuery; diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs index 0578c231..3db02cfe 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; @@ -7,9 +8,10 @@ using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.Authentication; -using Mediator; using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -19,7 +21,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUs /// /// Handler for the query to authenticate an account. /// -public class LoginUserQueryHandler : IRequestHandler> +public class LoginUserQueryHandler : IQueryHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IPasswordHashService _hashService; @@ -27,6 +29,7 @@ public class LoginUserQueryHandler : IRequestHandler _validator; /// /// Initializes a new instance of the class. @@ -37,13 +40,15 @@ public class LoginUserQueryHandler : IRequestHandlerInjected service for generating and validating TOTP tokens. /// Injected service for cryptographic functionality. /// Injected service for time related concerns. + /// Injected validator for application validation rules. public LoginUserQueryHandler( IUnitOfWork unitOfWork, IPasswordHashService hashService, IJwtTokenGenerator jwtTokenGenerator, ITotpTokenGenerator totpTokenGenerator, ICryptographyService cryptographyService, - IDateTimeProvider dateTimeProvider) + IDateTimeProvider dateTimeProvider, + IValidator validator) { _unitOfWork = unitOfWork; _hashService = hashService; @@ -51,27 +56,32 @@ public class LoginUserQueryHandler : IRequestHandler /// Handles the query to authenticate an account. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a successfully created , or an error message. /// - public async ValueTask> Handle(LoginUserQuery request, CancellationToken cancellationToken) + public async Task> HandleAsync(LoginUserQuery query, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + // check if any users already exists IUserRepository userRepository = _unitOfWork.GetRepository(); - ErrorOr getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false); + ErrorOr getUserResult = await userRepository.GetByUsernameAsync(query.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsError) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.InvalidUsernameOrPassword; // validate that the password is correct - if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(getUserResult.Value.Password!))) + if (!_hashService.CheckStringAgainstHash(query.Password!, Uri.UnescapeDataString(getUserResult.Value.Password!))) { // if a password reset was requested, a temp password is being used - if the hash check failed against the regular password, try against the temp one too if (getUserResult.Value.TempPassword is not null) @@ -87,7 +97,7 @@ public class LoginUserQueryHandler : IRequestHandler /// public LoginUserQueryValidator() { - RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); - RuleFor(x => x.Password).NotEmpty().WithMessage(Errors.Authentication.PasswordCannotBeEmpty.Description) - .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description); - RuleFor(m => m!.TotpCode) - .Custom((code, context) => - { - if (string.IsNullOrEmpty(code)) - return; - if (code.Length != 6) - context.AddFailure("TotpCode", Errors.Authentication.InvalidTotpCode.Description); - if (!code.All(char.IsDigit)) - context.AddFailure("TotpCode", Errors.Authentication.InvalidTotpCode.Description); - }); + RuleFor(query => query.Username) + .NotEmpty() + .WithError(Errors.Authentication.UsernameCannotBeEmpty); + + RuleFor(query => query.Password) + .NotEmpty() + .WithError(Errors.Authentication.PasswordCannotBeEmpty) + .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$") + .WithError(Errors.Authentication.InvalidPassword); + + RuleFor(query => query.TotpCode) + .Matches("^[0-9]{6}$") + .When(query => !string.IsNullOrEmpty(query.TotpCode)) + .WithError(Errors.Authentication.InvalidTotpCode); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommand.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommand.cs index 13b07c04..8daaf5da 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommand.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommand.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Authorization; -using Mediator; +using Lumina.Application.Common.CQRS; using System; using System.Collections.Generic; using System.Diagnostics; @@ -20,4 +18,4 @@ public record UpdateUserRoleAndPermissionsCommand( Guid UserId, Guid? RoleId, List Permissions -) : IRequest>; +) : ICommand; diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs index 49d328a5..4c7899ef 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Authorization; @@ -7,8 +8,8 @@ using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.Authorization; -using Mediator; using System; using System.Collections.Generic; using System.Linq; @@ -23,11 +24,12 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateU /// /// Handler for the command to update an authorization role. /// -public class UpdateUserRoleAndPermissionsCommandHandler : IRequestHandler> +public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IAuthorizationService _authorizationService; private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. @@ -35,23 +37,29 @@ public class UpdateUserRoleAndPermissionsCommandHandler : IRequestHandlerInjected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected unit of work for interacting with the data access layer repositories. - public UpdateUserRoleAndPermissionsCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + /// Injected validator for application validation rules. + public UpdateUserRoleAndPermissionsCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) { _unitOfWork = unitOfWork; _authorizationService = authorizationService; _currentUserService = currentUserService; + _validator = validator; } /// /// Handles the command to update an authorization role. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a successfully updated , or an error message. /// - public async ValueTask> Handle(UpdateUserRoleAndPermissionsCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(UpdateUserRoleAndPermissionsCommand command, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + // only admins can update user authorizations bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) @@ -63,15 +71,15 @@ public class UpdateUserRoleAndPermissionsCommandHandler : IRequestHandler(); // get the user to update - ErrorOr getUserResult = await userRepository.GetByIdAsync(request.UserId, cancellationToken).ConfigureAwait(false); + ErrorOr getUserResult = await userRepository.GetByIdAsync(command.UserId, cancellationToken).ConfigureAwait(false); if (getUserResult.IsError || getUserResult.Value is null) return DomainErrors.Users.UserDoesNotExist; ErrorOr getRoleResult = default; - if (request.RoleId is not null) + if (command.RoleId is not null) { // get the new role - getRoleResult = await roleRepository.GetByIdAsync(request.RoleId!.Value, cancellationToken).ConfigureAwait(false); + getRoleResult = await roleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken).ConfigureAwait(false); if (getRoleResult.IsError || getRoleResult.Value is null) return ApplicationErrors.Authorization.RoleNotFound; @@ -90,7 +98,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : IRequestHandler> getPermissionsResult = - await permissionRepository.GetByIdsAsync(request.Permissions, cancellationToken).ConfigureAwait(false); + await permissionRepository.GetByIdsAsync(command.Permissions, cancellationToken).ConfigureAwait(false); if (getPermissionsResult.IsError) return getPermissionsResult.Errors; @@ -98,12 +106,12 @@ public class UpdateUserRoleAndPermissionsCommandHandler : IRequestHandler new UserPermissionEntity + UserPermissions = command.Permissions.Select(permissionId => new UserPermissionEntity { UserId = userToUpdate.Id, PermissionId = permissionId, diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidator.cs index ba3f1589..d1d2491d 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidator.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using System; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors; @@ -17,16 +18,17 @@ public class UpdateUserRoleAndPermissionsCommandValidator : AbstractValidator public UpdateUserRoleAndPermissionsCommandValidator() { - RuleFor(x => x.UserId) - .NotEmpty().WithMessage(DomainErrors.Users.UserIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(DomainErrors.Users.UserIdCannotBeEmpty.Description); + RuleFor(command => command.UserId) + .NotEmpty() + .WithError(DomainErrors.Users.UserIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(DomainErrors.Users.UserIdCannotBeEmpty); - // validate Permissions only if provided - When(x => x.Permissions != null && x.Permissions.Count != 0, () => - { - RuleForEach(x => x.Permissions) - .NotEmpty().WithMessage(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty.Description); - }); + // validate each permission Id when the list is provided + RuleForEach(command => command.Permissions) + .NotEmpty() + .WithError(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQuery.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQuery.cs index 24d34c3f..1a55226b 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQuery.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQuery.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Authorization; -using Mediator; +using Lumina.Application.Common.CQRS; using System; using System.Diagnostics; #endregion @@ -15,4 +13,4 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAutho [DebuggerDisplay("UserId: {UserId}")] public record GetAuthorizationQuery( Guid? UserId -) : IRequest>; +) : IQuery; diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs index 5e4f81ba..6e4ea133 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs @@ -1,12 +1,14 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; -using Mediator; +using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -17,34 +19,41 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAutho /// /// Handler for the query to retrieve the authorization roles and permissions of an account. /// -public class GetAuthorizationQueryHandler : IRequestHandler> +public class GetAuthorizationQueryHandler : IQueryHandler> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. - public GetAuthorizationQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService) + /// Injected validator for application validation rules. + public GetAuthorizationQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) { _authorizationService = authorizationService; _currentUserService = currentUserService; + _validator = validator; } /// /// Handles the query to retrieve the authorization roles and permissions of an account. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a , or an error message. /// - public async ValueTask> Handle(GetAuthorizationQuery request, CancellationToken cancellationToken) + public async Task> HandleAsync(GetAuthorizationQuery query, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + // first, check if the Id of the user for whom to get the permission list is different from the Id currently making the request - if (_currentUserService.UserId != request.UserId) + if (_currentUserService.UserId != query.UserId) { // if it is, get the role of the current user, and see if they are Admin ErrorOr getCurrentUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(_currentUserService.UserId!.Value, cancellationToken).ConfigureAwait(false); @@ -54,7 +63,7 @@ public class GetAuthorizationQueryHandler : IRequestHandler getUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false); + ErrorOr getUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); return getUserPermissionResult.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidator.cs index aa988eaf..7633da55 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidator.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; using System; #endregion @@ -16,8 +17,10 @@ public class GetAuthorizationQueryValidator : AbstractValidator public GetAuthorizationQueryValidator() { - RuleFor(x => x.UserId) - .NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description); + RuleFor(query => query.UserId) + .NotEmpty() + .WithError(Errors.Users.UserIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Users.UserIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQuery.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQuery.cs index 5838f920..47217437 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQuery.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQuery.cs @@ -1,9 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Authorization; -using Mediator; +using Lumina.Application.Common.CQRS; using System; -using System.Collections.Generic; using System.Diagnostics; #endregion @@ -16,4 +13,4 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserP [DebuggerDisplay("UserId: {UserId}")] public record GetUserPermissionsQuery( Guid? UserId -) : IRequest>>; +) : IQuery; diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs index 3fcdb9fb..fad8a25c 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs @@ -1,14 +1,15 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; -using Mediator; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -20,11 +21,12 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserP /// /// Handler for the query to retrieve the authorization permissions of a user. /// -public class GetUserPermissionsQueryHandler : IRequestHandler>> +public class GetUserPermissionsQueryHandler : IQueryHandler>> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; private readonly IUserRepository _userRepository; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. @@ -32,29 +34,35 @@ public class GetUserPermissionsQueryHandler : IRequestHandlerInjected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected unit of work for interacting with the data access layer repositories. - public GetUserPermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + /// Injected validator for application validation rules. + public GetUserPermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) { _authorizationService = authorizationService; _currentUserService = currentUserService; _userRepository = unitOfWork.GetRepository(); + _validator = validator; } /// /// Handles the query to retrieve the authorization permissions of a user. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a collection of , or an error message. /// - public async ValueTask>> Handle(GetUserPermissionsQuery request, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetUserPermissionsQuery query, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + // only admins can see the list of authorization permissions bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; // get the user from the repository and return its permissions - ErrorOr getUserResult = await _userRepository.GetByIdAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false); + ErrorOr getUserResult = await _userRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); if (getUserResult.IsError) return getUserResult.Errors; else if (getUserResult.Value is null) diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidator.cs index f4b72b35..83f30db7 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidator.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; using System; #endregion @@ -16,8 +17,10 @@ public class GetUserPermissionsQueryValidator : AbstractValidator public GetUserPermissionsQueryValidator() { - RuleFor(x => x.UserId) - .NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description); + RuleFor(query => query.UserId) + .NotEmpty() + .WithError(Errors.Users.UserIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Users.UserIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQuery.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQuery.cs index ab3a32fd..c3fe088e 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQuery.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQuery.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.Authorization; -using Mediator; +using Lumina.Application.Common.CQRS; using System; using System.Diagnostics; #endregion @@ -15,4 +13,4 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserR [DebuggerDisplay("UserId: {UserId}")] public record GetUserRoleQuery( Guid? UserId -) : IRequest>; +) : IQuery; diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs index 460e0210..197a6c68 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs @@ -1,14 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; -using Mediator; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -18,11 +20,12 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserR /// /// Handler for the query to retrieve the authorization role of a user. /// -public class GetUserRoleQueryHandler : IRequestHandler> +public class GetUserRoleQueryHandler : IQueryHandler> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; private readonly IUserRepository _userRepository; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. @@ -30,29 +33,35 @@ public class GetUserRoleQueryHandler : IRequestHandlerInjected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected unit of work for interacting with the data access layer repositories. - public GetUserRoleQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + /// Injected validator for application validation rules. + public GetUserRoleQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) { _authorizationService = authorizationService; _currentUserService = currentUserService; _userRepository = unitOfWork.GetRepository(); + _validator = validator; } /// /// Handles the query to retrieve the authorization role of a user. /// - /// The request to be handled. + /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// /// An containing either a , or an error message. /// - public async ValueTask> Handle(GetUserRoleQuery request, CancellationToken cancellationToken) + public async Task> HandleAsync(GetUserRoleQuery query, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + // only admins can see the authorization role bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; // get the user from the repository and return its roles - ErrorOr getUserResult = await _userRepository.GetByIdAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false); + ErrorOr getUserResult = await _userRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); if (getUserResult.IsError) return getUserResult.Errors; else if (getUserResult.Value is null) diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidator.cs index b4780804..eaad5f25 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidator.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Errors; using System; #endregion @@ -16,8 +17,10 @@ public class GetUserRoleQueryValidator : AbstractValidator /// public GetUserRoleQueryValidator() { - RuleFor(x => x.UserId) - .NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description); + RuleFor(query => query.UserId) + .NotEmpty() + .WithError(Errors.Users.UserIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Users.UserIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Lumina.Application.csproj b/src/Lumina.Application/Lumina.Application.csproj index 137f8c15..73963c32 100644 --- a/src/Lumina.Application/Lumina.Application.csproj +++ b/src/Lumina.Application/Lumina.Application.csproj @@ -20,16 +20,13 @@ - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - + + + + diff --git a/src/Lumina.Domain/Common/Events/IDomainEvent.cs b/src/Lumina.Domain/Common/Events/IDomainEvent.cs index fbb4ed46..dad42f0a 100644 --- a/src/Lumina.Domain/Common/Events/IDomainEvent.cs +++ b/src/Lumina.Domain/Common/Events/IDomainEvent.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Mediator; using System; #endregion @@ -8,7 +7,7 @@ namespace Lumina.Domain.Common.Events; /// /// Interface defining a domain event. /// -public interface IDomainEvent : INotification +public interface IDomainEvent { /// /// Gets the Id of the domain event. diff --git a/src/Lumina.Domain/Common/Events/IDomainEventHandler.cs b/src/Lumina.Domain/Common/Events/IDomainEventHandler.cs new file mode 100644 index 00000000..9209e99d --- /dev/null +++ b/src/Lumina.Domain/Common/Events/IDomainEventHandler.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Common.Events; + +/// +/// Defines a contract for handling a domain event type in the application layer. +/// +/// The type of domain event to handle. +public interface IDomainEventHandler where TDomainEvent : IDomainEvent +{ + /// + /// Handles the specified . + /// + /// The domain event to handle. + /// Token to monitor for cancellation requests. + /// A task that represents the asynchronous operation. + ValueTask HandleAsync(TDomainEvent domainEvent, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Domain/Common/Events/IDomainEventPublisher.cs b/src/Lumina.Domain/Common/Events/IDomainEventPublisher.cs new file mode 100644 index 00000000..df8b69fa --- /dev/null +++ b/src/Lumina.Domain/Common/Events/IDomainEventPublisher.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Common.Events; + +/// +/// Publishes domain events to all handlers registered for the event type. +/// +public interface IDomainEventPublisher +{ + /// + /// Publishes the specified to all its registered handlers, in registration order. + /// + /// The domain event to publish. + /// Token to monitor for cancellation requests. + /// A task that represents the asynchronous operation. + ValueTask PublishAsync(IDomainEvent domainEvent, CancellationToken cancellationToken = default); +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs index 47cfdd17..2c019b7e 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs @@ -9,7 +9,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Mediator; using System; using System.Collections.Generic; using System.Threading; @@ -27,7 +26,7 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService private readonly IMediaLibraryScannerFactory _mediaLibraryScannerFactory; private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker; private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; - private readonly IPublisher _publisher; + private readonly IDomainEventPublisher _domainEventPublisher; /// /// Initializes a new instance of the class. @@ -36,19 +35,19 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService /// Injected factory for creating media library scanners. /// Injected tracker used for canceling media library scans. /// Injected tracker used for media library scans progress. - /// The domain event publisher used to publish events. + /// The domain event publisher used to publish events. public MediaLibraryScanningService( IMediaLibrariesScanQueue mediaLibrariesScanQueue, IMediaLibraryScannerFactory mediaLibraryScannerFactory, IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker, IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker, - IPublisher publisher) + IDomainEventPublisher domainEventPublisher) { _mediaLibrariesScanQueue = mediaLibrariesScanQueue; _mediaLibraryScannerFactory = mediaLibraryScannerFactory; _mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker; _mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker; - _publisher = publisher; + _domainEventPublisher = domainEventPublisher; } /// @@ -67,7 +66,7 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService return startScanResult.Errors; foreach (IDomainEvent domainEvent in scan.GetDomainEvents()) - await _publisher!.Publish(domainEvent, cancellationToken).ConfigureAwait(false); + await _domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false); // register the scan in the tracker for cancellation tokens _mediaLibrariesScanCancellationTracker.RegisterScan(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId)); diff --git a/src/Lumina.Domain/Lumina.Domain.csproj b/src/Lumina.Domain/Lumina.Domain.csproj index db6970b3..bff52acd 100644 --- a/src/Lumina.Domain/Lumina.Domain.csproj +++ b/src/Lumina.Domain/Lumina.Domain.csproj @@ -18,7 +18,6 @@ - diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 1e6e975e..24080a22 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; @@ -8,7 +7,9 @@ using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.Management.Progress; +using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue; @@ -35,6 +36,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; +using System.Linq; using System.Reflection; #endregion @@ -55,8 +57,15 @@ public static class InfrastructureLayerServices public static IServiceCollection AddInfrastructureLayerServices(this IServiceCollection services, IConfiguration configuration) { // scan the current assembly for validators and add them to the DI container - services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), ServiceLifetime.Singleton); + IEnumerable concreteTypes = Assembly.GetExecutingAssembly() + .GetTypes() + .Where(type => !type.IsInterface && !type.IsAbstract && !type.IsGenericTypeDefinition); + foreach (Type implementation in concreteTypes) + foreach (Type contract in implementation.GetInterfaces()) + if (contract.IsGenericType && contract.GetGenericTypeDefinition() == typeof(IValidator<>)) + services.AddSingleton(contract, implementation); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -67,6 +76,7 @@ public static class InfrastructureLayerServices services.AddSingleton(); services.AddScoped(); + services.AddScoped(); // authorization services.AddScoped(); diff --git a/src/Lumina.Infrastructure/Common/DomainEvents/DomainEventPublisher.cs b/src/Lumina.Infrastructure/Common/DomainEvents/DomainEventPublisher.cs new file mode 100644 index 00000000..3c472e9b --- /dev/null +++ b/src/Lumina.Infrastructure/Common/DomainEvents/DomainEventPublisher.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Concurrent; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Common.DomainEvents; + +/// +/// Publishes domain events to all handlers registered for the event type, by resolving them from the dependency injection container. +/// +public class DomainEventPublisher : IDomainEventPublisher +{ + private static readonly ConcurrentDictionary> s_dispatchers = new(); + + private readonly IServiceProvider _serviceProvider; + + /// + /// Initializes a new instance of the class. + /// + /// Injected provider used to resolve the domain event handlers. + public DomainEventPublisher(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + } + + /// + /// Publishes the specified to all its registered handlers, in registration order. + /// + /// The domain event to publish. + /// Token to monitor for cancellation requests. + /// A task that represents the asynchronous operation. + public ValueTask PublishAsync(IDomainEvent domainEvent, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(domainEvent); + + Func dispatcher = s_dispatchers.GetOrAdd(domainEvent.GetType(), static eventType => + { + MethodInfo dispatchMethod = typeof(DomainEventPublisher).GetMethod(nameof(DispatchAsync), BindingFlags.NonPublic | BindingFlags.Static)! + .MakeGenericMethod(eventType); + return dispatchMethod.CreateDelegate>(); + }); + + return new ValueTask(dispatcher(domainEvent, _serviceProvider, cancellationToken)); + } + + /// + /// Dispatches the specified to all handlers registered for . + /// + /// The type of the domain event being dispatched. + /// The domain event to dispatch. + /// The provider used to resolve the domain event handlers. + /// Token to monitor for cancellation requests. + /// A task that represents the asynchronous operation. + private static async Task DispatchAsync(IDomainEvent domainEvent, IServiceProvider serviceProvider, CancellationToken cancellationToken) + where TDomainEvent : IDomainEvent + { + foreach (IDomainEventHandler handler in serviceProvider.GetServices>()) + await handler.HandleAsync((TDomainEvent)domainEvent, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Infrastructure/Common/Utilities/ExceptionUtilities.cs b/src/Lumina.Infrastructure/Common/Utilities/ExceptionUtilities.cs new file mode 100644 index 00000000..95139811 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Utilities/ExceptionUtilities.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +#endregion + +namespace Lumina.Infrastructure.Common.Utilities; + +/// +/// Exception extension methods. +/// +/// +/// Based on https://stackoverflow.com/a/62283895. +/// +public static class ExceptionUtilities +{ + /// + /// Concatenates all inner exception(s) messages of . + /// + /// The exception for which to get the inner exception(s) message. + /// A string representing the concatenated messages of all inner expcetion(s) of . + public static string AggregateMessages(this Exception ex) + { + return ex.GetInnerExceptions().Aggregate(new StringBuilder(), (stringBuilder, exception) => stringBuilder.AppendLine(exception.Message + " -> "), stringBuilder => stringBuilder.ToString()); + } + + /// + /// Recursively gets the inner exception(s) of , at depth. + /// + /// The exception for which to get the inner exception(s). + /// The depth of the recursivity of getting the inner exception(s) of . + /// A list of exceptions representing the list of inner exception(s) of . + public static IEnumerable GetInnerExceptions(this Exception exception, int maximumDepth = 5) + { + // check if there are any more inner exceptions to return + if (exception == null || maximumDepth <= 0) + yield break; + // yield the current level exception itself + yield return exception; + // if the exception is an AggregateException, treat it differently and get its all exceptions + if (exception is AggregateException aggregateException) + foreach (Exception? innerException in aggregateException.InnerExceptions.SelectMany(innerException => innerException.GetInnerExceptions(maximumDepth - 1))) + yield return innerException; + // if it's a normal exception, recursively get its list of inner exceptions and yield them + foreach (Exception innerException in exception.InnerException?.GetInnerExceptions(maximumDepth - 1) ?? []) + yield return innerException; + } + + /// + /// Concatenates the relevant properties of . + /// + /// The exception for which to get the relevant properties. + /// A string representing the concatenated relevant properties of . + public static string AggregateMessage(this Exception ex) + { + return $"Message: {ex.Message}; CallStack: {ex.StackTrace}"; + } +} diff --git a/src/Lumina.Infrastructure/Common/Utilities/OptionsBuilderFluentValidationUtilities.cs b/src/Lumina.Infrastructure/Common/Utilities/OptionsBuilderValidationUtilities.cs similarity index 74% rename from src/Lumina.Infrastructure/Common/Utilities/OptionsBuilderFluentValidationUtilities.cs rename to src/Lumina.Infrastructure/Common/Utilities/OptionsBuilderValidationUtilities.cs index 80cd3011..1fdf407f 100644 --- a/src/Lumina.Infrastructure/Common/Utilities/OptionsBuilderFluentValidationUtilities.cs +++ b/src/Lumina.Infrastructure/Common/Utilities/OptionsBuilderValidationUtilities.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Infrastructure.Common.Validation; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; @@ -10,22 +10,22 @@ namespace Lumina.Infrastructure.Common.Utilities; /// /// Extension methods for adding configuration related options services to the DI container via . /// -public static class OptionsBuilderFluentValidationUtilities +public static class OptionsBuilderValidationUtilities { /// - /// Extension method to add fluent validation to the options validation pipeline. + /// Extension method to add validation to the options validation pipeline. /// /// The type of options being validated. /// The options builder to add the validation to. /// - /// This method allows validating options of type using a FluentValidation validator registered in the DI container. + /// This method allows validating options of type using a validator registered in the DI container. /// /// The same instance, to allow for chaining. public static OptionsBuilder ValidateFluently(this OptionsBuilder optionsBuilder) where TOptions : class { - // register a singleton instance of IValidateOptions using FluentValidation + // register a singleton instance of IValidateOptions using the validator optionsBuilder.Services.AddSingleton>( - serviceProvider => new FluentValidationOptions(optionsBuilder.Name, serviceProvider.GetRequiredService>())); + serviceProvider => new ValidationOptions(optionsBuilder.Name, serviceProvider.GetRequiredService>())); return optionsBuilder; } -} \ No newline at end of file +} diff --git a/src/Lumina.Infrastructure/Common/Validation/FluentValidationOptions.cs b/src/Lumina.Infrastructure/Common/Validation/ValidationOptions.cs similarity index 71% rename from src/Lumina.Infrastructure/Common/Validation/FluentValidationOptions.cs rename to src/Lumina.Infrastructure/Common/Validation/ValidationOptions.cs index e6c0d696..d7018a30 100644 --- a/src/Lumina.Infrastructure/Common/Validation/FluentValidationOptions.cs +++ b/src/Lumina.Infrastructure/Common/Validation/ValidationOptions.cs @@ -1,17 +1,19 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using ErrorOr; +using Lumina.Application.Common.Infrastructure.Validation; using Microsoft.Extensions.Options; using System; +using System.Collections.Generic; using System.Linq; #endregion namespace Lumina.Infrastructure.Common.Validation; /// -/// Provides options for fluent validation of a specific options type. +/// Provides options validation for a specific options type using the application validation framework. /// /// The type of options being validated. -public class FluentValidationOptions : IValidateOptions where TOptions : class +public class ValidationOptions : IValidateOptions where TOptions : class { private readonly IValidator _validator; @@ -21,11 +23,11 @@ public class FluentValidationOptions : IValidateOptions wher public string? Name { get; } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The name of the options being validated. This can be . /// The validator instance used to validate the options. - public FluentValidationOptions(string? name, IValidator validator) + public ValidationOptions(string? name, IValidator validator) { Name = name; _validator = validator; @@ -45,15 +47,14 @@ public class FluentValidationOptions : IValidateOptions wher ArgumentNullException.ThrowIfNull(options, nameof(options)); // don't go further if the options are null - FluentValidation.Results.ValidationResult validationResult = _validator.Validate(options); // validate the options using the validator + List validationResult = _validator.Validate(options); // validate the options using the validator // return a response based on the validation result - if (validationResult.IsValid) + if (validationResult.Count == 0) return ValidateOptionsResult.Success; // if the validation fails, collect the error messages - string[] errors = validationResult.Errors.Select(x => $"Options validation failed for '{x.PropertyName}' with error: '{x.ErrorMessage}'") - .ToArray(); + string[] errors = [.. validationResult.Select(error => $"Options validation failed for '{error.Code}' with error: '{error.Description}'")]; // and return them with a failure result return ValidateOptionsResult.Fail(errors); diff --git a/src/Lumina.Infrastructure/Common/Validators/CommonSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/CommonSettingsDtoValidator.cs index 03cf0cbd..3d3db812 100644 --- a/src/Lumina.Infrastructure/Common/Validators/CommonSettingsDtoValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/CommonSettingsDtoValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Infrastructure.Common.Models.DTO.Configuration; #endregion @@ -15,6 +16,8 @@ public class CommonSettingsDtoValidator : AbstractValidator /// public CommonSettingsDtoValidator() { - RuleFor(x => x.Theme).NotEmpty().WithMessage(Errors.Errors.Configuration.ApplicationThemeCannotBeEmpty.Description); + RuleFor(settings => settings.Theme) + .NotEmpty() + .WithError(Errors.Errors.Configuration.ApplicationThemeCannotBeEmpty); } } diff --git a/src/Lumina.Infrastructure/Common/Validators/CorsSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/CorsSettingsDtoValidator.cs index d5af8f95..c30a6e07 100644 --- a/src/Lumina.Infrastructure/Common/Validators/CorsSettingsDtoValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/CorsSettingsDtoValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Infrastructure.Common.Models.DTO.Configuration; using System; #endregion @@ -12,29 +13,30 @@ namespace Lumina.Infrastructure.Common.Validators; public class CorsSettingsDtoValidator : AbstractValidator { /// - /// Initializes validation rules for CORS configuration + /// Initializes a new instance of the class. /// public CorsSettingsDtoValidator() { - RuleFor(x => x.AllowedOrigins) + RuleFor(settings => settings.AllowedOrigins) .NotEmpty() - .WithMessage(Errors.Errors.Configuration.CorsOriginsCannotBeEmpty.Description) - .ForEach(originRule => - { - originRule.NotEmpty() - .WithMessage(Errors.Errors.Configuration.CorsOriginsCannotBeEmpty.Description) - .Must(BeValidOrigin) - .WithMessage(Errors.Errors.Configuration.CorsOriginIsInvalid.Description); - }); + .WithError(Errors.Errors.Configuration.CorsOriginsCannotBeEmpty); + + RuleForEach(settings => settings.AllowedOrigins) + .NotEmpty() + .WithError(Errors.Errors.Configuration.CorsOriginsCannotBeEmpty) + .Must(BeValidOrigin) + .WithError(Errors.Errors.Configuration.CorsOriginIsInvalid); } /// - /// Validates individual origin format + /// Validates the format of an individual CORS origin. /// + /// The origin to validate. + /// if the origin is a valid absolute HTTP or HTTPS URL, or the wildcard origin; otherwise, . private bool BeValidOrigin(string origin) { if (origin == "*") - return true; // wildcard allowed without credentials + return true; // wildcard allowed without credentials return Uri.TryCreate(origin, UriKind.Absolute, out Uri? uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) && !origin.EndsWith('/'); } } diff --git a/src/Lumina.Infrastructure/Common/Validators/DatabaseSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/DatabaseSettingsDtoValidator.cs index b48cd407..9f62340c 100644 --- a/src/Lumina.Infrastructure/Common/Validators/DatabaseSettingsDtoValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/DatabaseSettingsDtoValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Infrastructure.Common.Models.DTO.Configuration; #endregion @@ -15,6 +16,8 @@ public class DatabaseSettingsDtoValidator : AbstractValidator public DatabaseSettingsDtoValidator() { - RuleFor(x => x.DefaultConnection).NotEmpty().WithMessage(Errors.Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Description); + RuleFor(settings => settings.DefaultConnection) + .NotEmpty() + .WithError(Errors.Errors.Configuration.DatabaseConnectionStringCannotBeEmpty); } } diff --git a/src/Lumina.Infrastructure/Common/Validators/EncryptionSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/EncryptionSettingsDtoValidator.cs index 9c622f2d..fef934bb 100644 --- a/src/Lumina.Infrastructure/Common/Validators/EncryptionSettingsDtoValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/EncryptionSettingsDtoValidator.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Infrastructure.Common.Models.DTO.Configuration; using System; using System.Buffers.Text; @@ -17,8 +18,10 @@ public class EncryptionSettingsDtoValidator : AbstractValidator public EncryptionSettingsDtoValidator() { - RuleFor(x => x.SecretKey) - .NotEmpty().WithMessage(Errors.Errors.Configuration.EncryptionSecretKeyCannotBeEmpty.Description) - .Must(value => Base64.IsValid(value.AsSpan())).WithMessage(Errors.Errors.Configuration.EncryptionSecretKeyMustBeABase64String.Description); + RuleFor(settings => settings.SecretKey) + .NotEmpty() + .WithError(Errors.Errors.Configuration.EncryptionSecretKeyCannotBeEmpty) + .Must(value => Base64.IsValid(value.AsSpan())) + .WithError(Errors.Errors.Configuration.EncryptionSecretKeyMustBeABase64String); } } diff --git a/src/Lumina.Infrastructure/Common/Validators/JwtSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/JwtSettingsDtoValidator.cs index ad09f7a6..97cd9cad 100644 --- a/src/Lumina.Infrastructure/Common/Validators/JwtSettingsDtoValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/JwtSettingsDtoValidator.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using System; #endregion namespace Lumina.Infrastructure.Common.Validators; @@ -15,22 +17,22 @@ public class JwtSettingsDtoValidator : AbstractValidator /// public JwtSettingsDtoValidator() { - RuleFor(x => x.SecretKey) + RuleFor(settings => settings.SecretKey) .NotEmpty() - .WithMessage(Errors.Errors.Configuration.JwtSecretKeyCannotBeEmpty.Description) + .WithError(Errors.Errors.Configuration.JwtSecretKeyCannotBeEmpty) .MinimumLength(32) - .WithMessage(Errors.Errors.Configuration.JwtSecretKeyTooShort.Description); + .WithError(Errors.Errors.Configuration.JwtSecretKeyTooShort); - RuleFor(x => x.ExpiryMinutes) + RuleFor(settings => settings.ExpiryMinutes) .GreaterThan(0) - .WithMessage(Errors.Errors.Configuration.JwtExpiryMinutesMustBePositive.Description); + .WithError(Errors.Errors.Configuration.JwtExpiryMinutesMustBePositive); - RuleFor(x => x.Issuer) + RuleFor(settings => settings.Issuer) .NotEmpty() - .WithMessage(Errors.Errors.Configuration.JwtIssuerCannotBeEmpty.Description); + .WithError(Errors.Errors.Configuration.JwtIssuerCannotBeEmpty); - RuleFor(x => x.Audience) + RuleFor(settings => settings.Audience) .NotEmpty() - .WithMessage(Errors.Errors.Configuration.JwtAudienceCannotBeEmpty.Description); + .WithError(Errors.Errors.Configuration.JwtAudienceCannotBeEmpty); } } diff --git a/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs index 412a373e..846b2d86 100644 --- a/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Common.Utilities; #endregion namespace Lumina.Infrastructure.Common.Validators; @@ -15,7 +16,12 @@ public class MediaSettingsDtoValidator : AbstractValidator /// public MediaSettingsDtoValidator() { - RuleFor(x => x.RootDirectory).NotEmpty().WithMessage(Errors.Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description); - RuleFor(x => x.LibrariesDirectory).NotEmpty().WithMessage(Errors.Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty.Description); + RuleFor(settings => settings.RootDirectory) + .NotEmpty() + .WithError(Errors.Errors.Configuration.MediaRootDirectoryCannotBeEmpty); + + RuleFor(settings => settings.LibrariesDirectory) + .NotEmpty() + .WithError(Errors.Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty); } } diff --git a/src/Lumina.Infrastructure/Common/Validators/PluginsSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/PluginsSettingsDtoValidator.cs index 45d69804..d1abf0a3 100644 --- a/src/Lumina.Infrastructure/Common/Validators/PluginsSettingsDtoValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/PluginsSettingsDtoValidator.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Common.Utilities; using Lumina.Infrastructure.Common.Errors; #endregion @@ -16,6 +17,8 @@ public class PluginsSettingsDtoValidator : AbstractValidator /// public PluginsSettingsDtoValidator() { - RuleFor(x => x.Directory).NotEmpty().WithMessage(Errors.Errors.Configuration.PluginsDirectoryCannotBeEmpty.Description); + RuleFor(settings => settings.Directory) + .NotEmpty() + .WithError(Errors.Errors.Configuration.PluginsDirectoryCannotBeEmpty); } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs index 8f99dab6..2b4d92cd 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs @@ -3,10 +3,10 @@ using ErrorOr; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Mediator; using Microsoft.Extensions.DependencyInjection; using System; using System.Threading; @@ -58,13 +58,13 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra // see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository(); MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // set the initial progress of the scan job, it's a 1 step job - comparing the discovered files against the media library scan snapshot - ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); + ErrorOr publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsError) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); @@ -74,12 +74,12 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra throw new InvalidOperationException(markChangesResult.FirstError.Description); // increment the number of processed elements progress - publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsError) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); // this job finished, increment the number of processed jobs progress - await publisher.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); Status = LibraryScanJobStatus.Completed; // call each linked child with the obtained payload @@ -103,19 +103,19 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra /// /// Publishes a job progress update. /// - /// The service used to publish the progress update. + /// The service used to publish the progress update. /// The composite unique identifier of a media library scan. /// The current job progress. /// The total job progress. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) { ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ComparingFileHashes"); if (scanJobProgressResult.IsError) return scanJobProgressResult.Errors; - await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( + await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); return Result.Success; diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs index 4bb68c45..418be23c 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs @@ -4,10 +4,10 @@ using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Mediator; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; @@ -62,7 +62,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra // see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository(); IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; @@ -75,7 +75,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra int totalFilesToHash = getFilesToHashCountResult.Value; // set the initial progress of the scan job - ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false); + ErrorOr publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsError) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); @@ -104,7 +104,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) { // increment the number of processed elements progress - publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false); + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsError) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); lastUpdateTime = now; @@ -120,7 +120,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra } // this job finished, increment the number of processed jobs progress - await publisher.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); Status = LibraryScanJobStatus.Completed; // call each linked child with the obtained payload @@ -144,19 +144,19 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra /// /// Publishes a job progress update. /// - /// The service used to publish the progress update. + /// The service used to publish the progress update. /// The composite unique identifier of a media library scan. /// The current job progress. /// The total job progress. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) { ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "HashingFileContents"); if (scanJobProgressResult.IsError) return scanJobProgressResult.Errors; - await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( + await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); return Result.Success; diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs index a134c27d..07fa670c 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs @@ -8,13 +8,13 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Plugins.Contracts.Core.Metadata; -using Mediator; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; @@ -74,7 +74,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo // see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; ILibraryMetadataProviderConfigurationRepository configurationRepository = unitOfWork.GetRepository(); IBookRepository bookRepository = unitOfWork.GetRepository(); @@ -102,7 +102,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo int totalBooksToEnrich = getBooksToEnrichCountResult.Value; // set the initial progress of the scan job - ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + ErrorOr publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsError) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); @@ -134,7 +134,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) { // increment the number of processed elements progress - publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsError) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); lastUpdateTime = now; @@ -148,7 +148,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo // this job finished, and it's the last in the chain, the scan is completed Status = LibraryScanJobStatus.Completed; - await publisher.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); // call each linked child with the obtained payload foreach (IMediaLibraryScanJob child in Children) @@ -242,19 +242,19 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo /// /// Publishes a job progress update. /// - /// The service used to publish the progress update. + /// The service used to publish the progress update. /// The composite unique identifier of a media library scan. /// The current job progress. /// The total job progress. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) { ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "EnrichingMetadata"); if (scanJobProgressResult.IsError) return scanJobProgressResult.Errors; - await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( + await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); return Result.Success; diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs index 2f8cc33a..1053b7ab 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs @@ -6,10 +6,10 @@ using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Mediator; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; @@ -65,13 +65,13 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed // see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; ILibraryScanSnapshotRepository libraryScanSnapshotRepository = unitOfWork.GetRepository(); MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // set the initial progress of the scan job, it's a 1 step job - applying the scan results to the storage medium - ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); + ErrorOr publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsError) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); @@ -89,7 +89,7 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed foreach (string deletedPath in getDeletedPathsResult.Value) { cancellationToken.ThrowIfCancellationRequested(); - await publisher.Publish(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + await domainEventPublisher.PublishAsync(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); } // materialize the books of the media library from the scan snapshot, so that they are browsable even without web metadata @@ -114,14 +114,14 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // increment the number of processed elements progress - publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsError) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); Status = LibraryScanJobStatus.Completed; // when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed if (Children.Count == 0) - await publisher.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); // call each linked child with the obtained payload foreach (IMediaLibraryScanJob child in Children) @@ -144,19 +144,19 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed /// /// Publishes a job progress update. /// - /// The service used to publish the progress update. + /// The service used to publish the progress update. /// The composite unique identifier of a media library scan. /// The current job progress. /// The total job progress. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) { ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "SavingScanData"); if (scanJobProgressResult.IsError) return scanJobProgressResult.Errors; - await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); return Result.Success; } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs index 2ec45bda..cade5637 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Mediator; using Microsoft.Extensions.DependencyInjection; using System; using System.Threading; @@ -30,8 +30,8 @@ internal static class ScanFailurePublisher try { await using AsyncServiceScope asyncServiceScope = serviceScopeFactory.CreateAsyncScope(); - IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; - await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), libraryId, compositeKey, DateTime.UtcNow, exception.Message), cancellationToken).ConfigureAwait(false); + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + await domainEventPublisher.PublishAsync(new LibraryScanFailedDomainEvent(Guid.NewGuid(), libraryId, compositeKey, DateTime.UtcNow, exception.Message), cancellationToken).ConfigureAwait(false); } catch { diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs index afb13d77..cfe925dc 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs @@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; @@ -12,7 +13,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; -using Mediator; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; @@ -78,7 +78,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF // see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; ILibraryRepository libraryRepository = unitOfWork.GetRepository()!; ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository(); IDirectoryScanFingerprintRepository directoryScanFingerprintRepository = unitOfWork.GetRepository(); @@ -106,7 +106,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF } // set the initial progress of the scan job - ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + ErrorOr publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsError) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); @@ -137,8 +137,8 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF DateTime now = DateTime.UtcNow; if (now - lastHeartbeat >= heartbeatInterval) { - publishJobProgressResult = await PublishJobProgress( - publisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + publishJobProgressResult = await PublishJobProgressAsync( + domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsError) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); lastHeartbeat = now; @@ -160,7 +160,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF } // this job finished, increment the number of processed jobs progress - await publisher.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); Status = LibraryScanJobStatus.Completed; // call each linked child with the obtained payload @@ -321,19 +321,19 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF /// /// Publishes a job progress update. /// - /// The service used to publish the progress update. + /// The service used to publish the progress update. /// The composite unique identifier of a media library scan. /// The current job progress. /// The total job progress. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) { ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "DiscoveringFiles"); if (scanJobProgressResult.IsError) return scanJobProgressResult.Errors; - await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( + await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); return Result.Success; diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index 33aec118..13283b24 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -16,7 +16,6 @@ - diff --git a/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs index 6d552c84..7f16b977 100644 --- a/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs +++ b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs @@ -3,7 +3,6 @@ using Lumina.Application.Common.DomainEvents; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Logging; @@ -35,10 +34,10 @@ public class EventualConsistencyMiddleware /// Handles incoming HTTP requests and ensures that domain events are published and the database transaction is committed upon successful request completion. /// /// The current HTTP context. - /// The domain event publisher used to publish events. + /// The domain event publisher used to publish events. /// The database context used to manage the transaction. /// In memory queue containing the queued domain events. - public async Task InvokeAsync(HttpContext context, IPublisher publisher, LuminaDbContext dbContext, IDomainEventsQueue domainEventQueue) + public async Task InvokeAsync(HttpContext context, IDomainEventPublisher domainEventPublisher, LuminaDbContext dbContext, IDomainEventsQueue domainEventQueue) { // begin a new database transaction - this will wrap any database operations performed during this HTTP request in an atomic operation IDbContextTransaction transaction = await dbContext.Database.BeginTransactionAsync(context.RequestAborted).ConfigureAwait(false); @@ -59,7 +58,7 @@ public class EventualConsistencyMiddleware // check if domain events exist in the channel queue and publish them while (domainEventQueue.TryDequeue(out IDomainEvent? nextEvent)) - await publisher.Publish(nextEvent); + await domainEventPublisher.PublishAsync(nextEvent); } } catch (EventualConsistencyException ex) diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpoint.cs index 6d5fb47d..30f5c9e4 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpoint.cs @@ -1,12 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions; -using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; using Lumina.Contracts.Responses.Authorization; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -20,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Permissions /// public class GetPermissionsEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler>> _getPermissionsQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetPermissionsEndpoint(ISender sender) + /// Injected service for handling get permissions queries. + public GetPermissionsEndpoint(IQueryHandler>> getPermissionsQueryHandler) { - _sender = sender; + _getPermissionsQueryHandler = getPermissionsQueryHandler; } /// @@ -36,7 +35,7 @@ public class GetPermissionsEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Permissions.GET_PERMISSIONS); Version(1); DontCatchExceptions(); @@ -48,7 +47,7 @@ public class GetPermissionsEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(new GetPermissionsQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _getPermissionsQueryHandler.HandleAsync(new GetPermissionsQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs index c285c2d8..d8754a30 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.AddRo /// public class AddRoleEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _addRoleCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public AddRoleEndpoint(ISender sender) + /// Injected service for handling add role commands. + public AddRoleEndpoint(ICommandHandler> addRoleCommandHandler) { - _sender = sender; + _addRoleCommandHandler = addRoleCommandHandler; } /// @@ -35,7 +35,7 @@ public class AddRoleEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.POST); + Verbs(FastEndpoints.Http.POST); Routes(ApiRoutes.Roles.CREATE_ROLE); Version(1); DontCatchExceptions(); @@ -48,7 +48,7 @@ public class AddRoleEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(AddRoleRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _addRoleCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs index 8d3febaa..16f7d9b9 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; using Lumina.Contracts.Requests.Authorization; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -18,15 +18,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.Delet /// public class DeleteRoleEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _deleteRoleCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public DeleteRoleEndpoint(ISender sender) + /// Injected service for handling delete role commands. + public DeleteRoleEndpoint(ICommandHandler> deleteRoleCommandHandler) { - _sender = sender; + _deleteRoleCommandHandler = deleteRoleCommandHandler; } /// @@ -34,7 +34,7 @@ public class DeleteRoleEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.DELETE); + Verbs(FastEndpoints.Http.DELETE); Routes(ApiRoutes.Roles.DELETE_ROLE); Version(1); DontCatchExceptions(); @@ -47,7 +47,7 @@ public class DeleteRoleEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(DeleteRoleRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _deleteRoleCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.NoContent(), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs index bfb48d71..bf158a74 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.GetRo /// public class GetRolePermissionsEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler> _addRoleQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetRolePermissionsEndpoint(ISender sender) + /// Injected service for handling add role commands. + public GetRolePermissionsEndpoint(IQueryHandler> addRoleQueryHandler) { - _sender = sender; + _addRoleQueryHandler = addRoleQueryHandler; } /// @@ -35,7 +35,7 @@ public class GetRolePermissionsEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Roles.GET_ROLE_PERMISSIONS_BY_ROLE_ID); Version(1); DontCatchExceptions(); @@ -48,7 +48,7 @@ public class GetRolePermissionsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetRolePermissionsRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _addRoleQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpoint.cs index 8d984d82..836acc82 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpoint.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; using Lumina.Contracts.Responses.Authorization; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.GetRo /// public class GetRolesEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler>> _getRolesQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetRolesEndpoint(ISender sender) + /// Injected service for handling get roles queries. + public GetRolesEndpoint(IQueryHandler>> getRolesQueryHandler) { - _sender = sender; + _getRolesQueryHandler = getRolesQueryHandler; } /// @@ -35,7 +35,7 @@ public class GetRolesEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Roles.GET_ROLES); Version(1); DontCatchExceptions(); @@ -47,7 +47,7 @@ public class GetRolesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(new GetRolesQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _getRolesQueryHandler.HandleAsync(new GetRolesQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpoint.cs index 482c5ebe..375918d8 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.Updat /// public class UpdateRoleEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _updateRoleCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public UpdateRoleEndpoint(ISender sender) + /// Injected service for handling update role commands. + public UpdateRoleEndpoint(ICommandHandler> updateRoleCommandHandler) { - _sender = sender; + _updateRoleCommandHandler = updateRoleCommandHandler; } /// @@ -35,7 +35,7 @@ public class UpdateRoleEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.PUT); + Verbs(FastEndpoints.Http.PUT); Routes(ApiRoutes.Roles.UPDATE_ROLE); Version(1); DontCatchExceptions(); @@ -48,7 +48,7 @@ public class UpdateRoleEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdateRoleRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _updateRoleCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs index 94cc59a9..a029dc4d 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Contracts.Requests.FileSystemManagement.Directories; using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -21,15 +21,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directorie /// public class GetDirectoriesEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler>> _getDirectoriesQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetDirectoriesEndpoint(ISender sender) + /// Injected service for handling get directories queries. + public GetDirectoriesEndpoint(IQueryHandler>> getDirectoriesQueryHandler) { - _sender = sender; + _getDirectoriesQueryHandler = getDirectoriesQueryHandler; } /// @@ -37,7 +37,7 @@ public class GetDirectoriesEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Directories.GET_DIRECTORIES); Version(1); DontCatchExceptions(); @@ -50,7 +50,7 @@ public class GetDirectoriesEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetDirectoriesRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _getDirectoriesQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpoint.cs index 82dffb3e..270c61be 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpoint.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.Get /// public class GetDrivesEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler>> _getDrivesQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetDrivesEndpoint(ISender sender) + /// Injected service for handling get drives queries. + public GetDrivesEndpoint(IQueryHandler>> getDrivesQueryHandler) { - _sender = sender; + _getDrivesQueryHandler = getDrivesQueryHandler; } /// @@ -35,7 +35,7 @@ public class GetDrivesEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Drives.GET_DRIVES); Version(1); DontCatchExceptions(); @@ -47,7 +47,7 @@ public class GetDrivesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(new GetDrivesQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _getDrivesQueryHandler.HandleAsync(new GetDrivesQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpoint.cs index 914df7e0..f82b41f1 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpoint.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Files; using Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; using Lumina.Contracts.Requests.FileSystemManagement.Files; using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -21,15 +21,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem /// public class GetTypeEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler _getFileSystemQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetTypeEndpoint(ISender sender) + /// Injected service for handling get file system queries. + public GetTypeEndpoint(IQueryHandler getFileSystemQueryHandler) { - _sender = sender; + _getFileSystemQueryHandler = getFileSystemQueryHandler; } /// @@ -37,7 +37,7 @@ public class GetTypeEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.FileSystem.GET_TYPES); Version(1); DontCatchExceptions(); @@ -49,7 +49,7 @@ public class GetTypeEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - FileSystemTypeResponse platformType = await _sender.Send(new GetFileSystemQuery(), cancellationToken).ConfigureAwait(false); + FileSystemTypeResponse platformType = await _getFileSystemQueryHandler.HandleAsync(new GetFileSystemQuery(), cancellationToken).ConfigureAwait(false); return TypedResults.Ok(platformType); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs index dd7e09dd..ff65bb6f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Files; +using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; using Lumina.Contracts.Requests.FileSystemManagement.Files; using Lumina.Contracts.Responses.FileSystemManagement.Files; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -20,15 +20,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetF /// public class GetFilesEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler>> _getFilesQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetFilesEndpoint(ISender sender) + /// Injected service for handling get files queries. + public GetFilesEndpoint(IQueryHandler>> getFilesQueryHandler) { - _sender = sender; + _getFilesQueryHandler = getFilesQueryHandler; } /// @@ -36,7 +36,7 @@ public class GetFilesEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Files.GET_FILES); Version(1); DontCatchExceptions(); @@ -49,7 +49,7 @@ public class GetFilesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetFilesRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _getFilesQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs index a17d199c..faf6b0d5 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Files; +using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; using Lumina.Contracts.Requests.FileSystemManagement.Files; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -20,15 +20,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetT /// public class GetTreeFilesEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler>> _getTreeFilesQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetTreeFilesEndpoint(ISender sender) + /// Injected service for handling get tree files queries. + public GetTreeFilesEndpoint(IQueryHandler>> getTreeFilesQueryHandler) { - _sender = sender; + _getTreeFilesQueryHandler = getTreeFilesQueryHandler; } /// @@ -36,7 +36,7 @@ public class GetTreeFilesEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Files.GET_TREE_FILES); Version(1); DontCatchExceptions(); @@ -49,7 +49,7 @@ public class GetTreeFilesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetTreeFilesRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _getTreeFilesQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs index 8f5317d0..f4cc6448 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.Check /// public class CheckPathExistsEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler> _checkPathExistsQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public CheckPathExistsEndpoint(ISender sender) + /// Injected service for handling check path exists queries. + public CheckPathExistsEndpoint(IQueryHandler> checkPathExistsQueryHandler) { - _sender = sender; + _checkPathExistsQueryHandler = checkPathExistsQueryHandler; } /// @@ -35,7 +35,7 @@ public class CheckPathExistsEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Path.CHECK_PATH_EXISTS); Version(1); DontCatchExceptions(); @@ -48,7 +48,7 @@ public class CheckPathExistsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(CheckPathExistsRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _checkPathExistsQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpoint.cs index aabf25b1..885b6664 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.Combi /// public class CombinePathEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _combinePathCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public CombinePathEndpoint(ISender sender) + /// Injected service for handling combine path commands. + public CombinePathEndpoint(ICommandHandler> combinePathCommandHandler) { - _sender = sender; + _combinePathCommandHandler = combinePathCommandHandler; } /// @@ -35,7 +35,7 @@ public class CombinePathEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Path.COMBINE); Version(1); DontCatchExceptions(); @@ -48,7 +48,7 @@ public class CombinePathEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(CombinePathRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _combinePathCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpoint.cs index 4ed03330..33d83018 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -20,15 +20,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPa /// public class GetPathParentEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler>> _getPathParentQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetPathParentEndpoint(ISender sender) + /// Injected service for handling get path parent queries. + public GetPathParentEndpoint(IQueryHandler>> getPathParentQueryHandler) { - _sender = sender; + _getPathParentQueryHandler = getPathParentQueryHandler; } /// @@ -36,7 +36,7 @@ public class GetPathParentEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Path.GET_PATH_PARENT); Version(1); DontCatchExceptions(); @@ -49,7 +49,7 @@ public class GetPathParentEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetPathParentRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _getPathParentQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpoint.cs index 70fd55da..fd31534e 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPa /// public class GetPathRootEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler> _getPathRootQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetPathRootEndpoint(ISender sender) + /// Injected service for handling get path root queries. + public GetPathRootEndpoint(IQueryHandler> getPathRootQueryHandler) { - _sender = sender; + _getPathRootQueryHandler = getPathRootQueryHandler; } /// @@ -35,7 +35,7 @@ public class GetPathRootEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Path.GET_PATH_ROOT); Version(1); DontCatchExceptions(); @@ -48,7 +48,7 @@ public class GetPathRootEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetPathRootRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _getPathRootQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpoint.cs index 2afc6259..928029d5 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpoint.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSeparator; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -16,15 +16,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPa /// public class GetPathSeparatorEndpoint : EndpointWithoutRequest { - private readonly ISender _sender; + private readonly IQueryHandler _getPathSeparatorQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetPathSeparatorEndpoint(ISender sender) + /// Injected service for handling get path separator queries. + public GetPathSeparatorEndpoint(IQueryHandler getPathSeparatorQueryHandler) { - _sender = sender; + _getPathSeparatorQueryHandler = getPathSeparatorQueryHandler; } /// @@ -32,7 +32,7 @@ public class GetPathSeparatorEndpoint : EndpointWithoutRequest /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Path.GET_PATH_SEPARATOR); Version(1); DontCatchExceptions(); @@ -44,7 +44,7 @@ public class GetPathSeparatorEndpoint : EndpointWithoutRequest /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(CancellationToken cancellationToken) { - PathSeparatorResponse result = await _sender.Send(new GetPathSeparatorQuery(), cancellationToken).ConfigureAwait(false); + PathSeparatorResponse result = await _getPathSeparatorQueryHandler.HandleAsync(new GetPathSeparatorQuery(), cancellationToken).ConfigureAwait(false); return TypedResults.Ok(result); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpoint.cs index 7f62f048..0d33f95a 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -20,15 +20,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.Split /// public class SplitPathEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler>> _splitPathCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public SplitPathEndpoint(ISender sender) + /// Injected service for handling split path commands. + public SplitPathEndpoint(ICommandHandler>> splitPathCommandHandler) { - _sender = sender; + _splitPathCommandHandler = splitPathCommandHandler; } /// @@ -36,7 +36,7 @@ public class SplitPathEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Path.SPLIT); Version(1); DontCatchExceptions(); @@ -49,7 +49,7 @@ public class SplitPathEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(SplitPathRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _splitPathCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpoint.cs index e1129c65..eded7fa9 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpoint.cs @@ -1,11 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using FastEndpoints; +using ErrorOr; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -18,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.Valid /// public class ValidatePathEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler> _validatePathQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public ValidatePathEndpoint(ISender sender) + /// Injected service for handling validate path queries. + public ValidatePathEndpoint(IQueryHandler> validatePathQueryHandler) { - _sender = sender; + _validatePathQueryHandler = validatePathQueryHandler; } /// @@ -34,7 +35,7 @@ public class ValidatePathEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Path.VALIDATE); Version(1); DontCatchExceptions(); @@ -47,7 +48,7 @@ public class ValidatePathEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(ValidatePathRequest request, CancellationToken cancellationToken) { - PathValidResponse result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); - return TypedResults.Ok(result); + ErrorOr result = await _validatePathQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs index 78387bdb..68ad8c74 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Files; using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails; +using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Common.Utilities; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -21,15 +21,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails /// public class GetThumbnailEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler> _getThumbnailQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetThumbnailEndpoint(ISender sender) + /// Injected service for handling get thumbnail queries. + public GetThumbnailEndpoint(IQueryHandler> getThumbnailQueryHandler) { - _sender = sender; + _getThumbnailQueryHandler = getThumbnailQueryHandler; } /// @@ -37,7 +37,7 @@ public class GetThumbnailEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Thumbnails.GET_THUMBNAIL); Version(1); DontCatchExceptions(); @@ -50,7 +50,7 @@ public class GetThumbnailEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetThumbnailRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _getThumbnailQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.File(success.Bytes, MimeTypes.GetMimeType(success.Type)), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs index 7db5f519..d9c9a336 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.AddLibrary; /// public class AddLibraryEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _addLibraryCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public AddLibraryEndpoint(ISender sender) + /// Injected service for handling add library commands. + public AddLibraryEndpoint(ICommandHandler> addLibraryCommandHandler) { - _sender = sender; + _addLibraryCommandHandler = addLibraryCommandHandler; } /// @@ -35,7 +35,7 @@ public class AddLibraryEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.POST); + Verbs(FastEndpoints.Http.POST); Routes(ApiRoutes.Libraries.ADD_LIBRARY); Version(1); DontCatchExceptions(); @@ -48,7 +48,7 @@ public class AddLibraryEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(AddLibraryRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _addLibraryCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Libraries.ADD_LIBRARY}/{result.Value.Id}", result.Value), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs index 1290f045..7364d233 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -17,15 +17,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.CancelLibrar /// public class CancelLibrariesScanEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly Lumina.Application.Common.CQRS.ICommandHandler> _cancelLibrariesScanCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public CancelLibrariesScanEndpoint(ISender sender) + /// Injected service for handling cancel libraries scan commands. + public CancelLibrariesScanEndpoint(Lumina.Application.Common.CQRS.ICommandHandler> cancelLibrariesScanCommandHandler) { - _sender = sender; + _cancelLibrariesScanCommandHandler = cancelLibrariesScanCommandHandler; } /// @@ -33,7 +33,7 @@ public class CancelLibrariesScanEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.POST); + Verbs(FastEndpoints.Http.POST); Routes(ApiRoutes.Libraries.CANCEL_LIBRARIES_SCAN); Version(1); DontCatchExceptions(); @@ -45,7 +45,7 @@ public class CancelLibrariesScanEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(new CancelLibrariesScanCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _cancelLibrariesScanCommandHandler.HandleAsync(new CancelLibrariesScanCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.NoContent(), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs index 35d9a70b..8d3c5549 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; using Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibraryScan; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -20,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.CancelLibrar /// public class CancelLibraryScanEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _cancelLibraryScanCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public CancelLibraryScanEndpoint(ISender sender) + /// Injected service for handling cancel library scan commands. + public CancelLibraryScanEndpoint(ICommandHandler> cancelLibraryScanCommandHandler) { - _sender = sender; + _cancelLibraryScanCommandHandler = cancelLibraryScanCommandHandler; } /// @@ -36,7 +35,7 @@ public class CancelLibraryScanEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.POST); + Verbs(FastEndpoints.Http.POST); Routes(ApiRoutes.Libraries.CANCEL_LIBRARY_SCAN); Version(1); DontCatchExceptions(); @@ -48,7 +47,7 @@ public class CancelLibraryScanEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(CancelLibraryScanRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _cancelLibraryScanCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.NoContent(), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs index acdaaccc..96ae891f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary; using System.Threading; using System.Threading.Tasks; #endregion @@ -18,15 +18,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.DeleteLibrar /// public class DeleteLibraryEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _deleteLibraryCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public DeleteLibraryEndpoint(ISender sender) + /// Injected service for handling delete library commands. + public DeleteLibraryEndpoint(ICommandHandler> deleteLibraryCommandHandler) { - _sender = sender; + _deleteLibraryCommandHandler = deleteLibraryCommandHandler; } /// @@ -34,7 +34,7 @@ public class DeleteLibraryEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.DELETE); + Verbs(FastEndpoints.Http.DELETE); Routes(ApiRoutes.Libraries.DELETE_LIBRARY); Version(1); DontCatchExceptions(); @@ -47,7 +47,7 @@ public class DeleteLibraryEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(DeleteLibraryRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _deleteLibraryCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpoint.cs index 87c318a5..e1863623 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpoint.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibraries; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -18,15 +18,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetEnabledLi /// public class GetEnabledLibrariesEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler> _getEnabledLibrariesQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetEnabledLibrariesEndpoint(ISender sender) + /// Injected service for handling get enabled libraries queries. + public GetEnabledLibrariesEndpoint(IQueryHandler> getEnabledLibrariesQueryHandler) { - _sender = sender; + _getEnabledLibrariesQueryHandler = getEnabledLibrariesQueryHandler; } /// @@ -34,7 +34,7 @@ public class GetEnabledLibrariesEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Libraries.GET_ENABLED_LIBRARIES); Version(1); DontCatchExceptions(); @@ -46,7 +46,7 @@ public class GetEnabledLibrariesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(new GetEnabledLibrariesQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _getEnabledLibrariesQueryHandler.HandleAsync(new GetEnabledLibrariesQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpoint.cs index 5a21d3b3..ced03ede 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpoint.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -18,15 +18,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraries /// public class GetLibrariesEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler> _getLibrariesQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetLibrariesEndpoint(ISender sender) + /// Injected service for handling get libraries queries. + public GetLibrariesEndpoint(IQueryHandler> getLibrariesQueryHandler) { - _sender = sender; + _getLibrariesQueryHandler = getLibrariesQueryHandler; } /// @@ -34,7 +34,7 @@ public class GetLibrariesEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Libraries.GET_LIBRARIES); Version(1); DontCatchExceptions(); @@ -46,7 +46,7 @@ public class GetLibrariesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(new GetLibrariesQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _getLibrariesQueryHandler.HandleAsync(new GetLibrariesQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpoint.cs index 9a336d3e..560aa619 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibrary; /// public class GetLibraryEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler> _getLibraryQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetLibraryEndpoint(ISender sender) + /// Injected service for handling get library queries. + public GetLibraryEndpoint(IQueryHandler> getLibraryQueryHandler) { - _sender = sender; + _getLibraryQueryHandler = getLibraryQueryHandler; } /// @@ -35,7 +35,7 @@ public class GetLibraryEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Libraries.GET_LIBRARY_BY_ID); Version(1); DontCatchExceptions(); @@ -48,7 +48,7 @@ public class GetLibraryEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetLibraryRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _getLibraryQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpoint.cs index d0cf1c49..ea5f73c4 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScanProgress; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibrarySc /// public class GetLibraryScanProgressEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler> _getLibraryScanProgressQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetLibraryScanProgressEndpoint(ISender sender) + /// Injected service for handling get library scan progress queries. + public GetLibraryScanProgressEndpoint(IQueryHandler> getLibraryScanProgressQueryHandler) { - _sender = sender; + _getLibraryScanProgressQueryHandler = getLibraryScanProgressQueryHandler; } /// @@ -35,7 +35,7 @@ public class GetLibraryScanProgressEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Libraries.LIBRARY_SCAN_PROGRESS); Version(1); DontCatchExceptions(); @@ -48,7 +48,7 @@ public class GetLibraryScanProgressEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetLibraryScanProgressRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _getLibraryScanProgressQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpoint.cs index a80e820d..fa9e8e2b 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -20,15 +20,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetRunningLi /// public class GetRunningLibraryScansEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler>> _getRunningLibraryScansQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetRunningLibraryScansEndpoint(ISender sender) + /// Injected service for handling get running library scans queries. + public GetRunningLibraryScansEndpoint(IQueryHandler>> getRunningLibraryScansQueryHandler) { - _sender = sender; + _getRunningLibraryScansQueryHandler = getRunningLibraryScansQueryHandler; } /// @@ -36,7 +36,7 @@ public class GetRunningLibraryScansEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Libraries.GET_RUNNING_LIBRARIES_SCAN); Version(1); DontCatchExceptions(); @@ -48,7 +48,7 @@ public class GetRunningLibraryScansEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(new GetRunningLibraryScansQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _getRunningLibraryScansQueryHandler.HandleAsync(new GetRunningLibraryScansQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs index de2019af..34920a12 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs @@ -1,11 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -17,17 +16,17 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibrarie /// /// API endpoint for the /libraries/scans route. /// -public class ScanLibrariesEndpoint : BaseEndpoint +public class ScanLibrariesEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler>> _scanLibrariesCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public ScanLibrariesEndpoint(ISender sender) + /// Injected service for handling scan libraries commands. + public ScanLibrariesEndpoint(ICommandHandler>> scanLibrariesCommandHandler) { - _sender = sender; + _scanLibrariesCommandHandler = scanLibrariesCommandHandler; } /// @@ -35,7 +34,7 @@ public class ScanLibrariesEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.POST); + Verbs(FastEndpoints.Http.POST); Routes(ApiRoutes.Libraries.SCAN_LIBRARIES); Version(1); DontCatchExceptions(); @@ -45,9 +44,9 @@ public class ScanLibrariesEndpoint : BaseEndpoint /// Initiates a scan of all media libraries. /// /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(new ScanLibrariesCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _scanLibrariesCommandHandler.HandleAsync(new ScanLibrariesCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs index ba52a8f6..4904c11d 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibrary; /// public class ScanLibraryEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _scanLibraryCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public ScanLibraryEndpoint(ISender sender) + /// Injected service for handling scan library commands. + public ScanLibraryEndpoint(ICommandHandler> scanLibraryCommandHandler) { - _sender = sender; + _scanLibraryCommandHandler = scanLibraryCommandHandler; } /// @@ -35,7 +35,7 @@ public class ScanLibraryEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.POST); + Verbs(FastEndpoints.Http.POST); Routes(ApiRoutes.Libraries.SCAN_LIBRARY); Version(1); DontCatchExceptions(); @@ -47,7 +47,7 @@ public class ScanLibraryEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(ScanLibraryRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _scanLibraryCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpoint.cs index c9c5a51c..b615725b 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.UpdateLibrar /// public class UpdateLibraryEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _updateLibraryCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public UpdateLibraryEndpoint(ISender sender) + /// Injected service for handling update library commands. + public UpdateLibraryEndpoint(ICommandHandler> updateLibraryCommandHandler) { - _sender = sender; + _updateLibraryCommandHandler = updateLibraryCommandHandler; } /// @@ -35,7 +35,7 @@ public class UpdateLibraryEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.PUT); + Verbs(FastEndpoints.Http.PUT); Routes(ApiRoutes.Libraries.UPDATE_LIBRARY); Version(1); DontCatchExceptions(); @@ -48,7 +48,7 @@ public class UpdateLibraryEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdateLibraryRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _updateLibraryCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs index 16146459..de77dcd6 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B /// public class AddBookEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _addBookCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public AddBookEndpoint(ISender sender) + /// Injected service for handling add book commands. + public AddBookEndpoint(ICommandHandler> addBookCommandHandler) { - _sender = sender; + _addBookCommandHandler = addBookCommandHandler; } /// @@ -35,7 +35,7 @@ public class AddBookEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.POST); + Verbs(FastEndpoints.Http.POST); Routes(ApiRoutes.Books.ADD_BOOK); Version(1); DontCatchExceptions(); @@ -48,7 +48,7 @@ public class AddBookEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(AddBookRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _addBookCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Books.ADD_BOOK}/{result.Value.Id}", result.Value), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpoint.cs index e22f8375..10d2d9b1 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpoint.cs @@ -1,9 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using FastEndpoints; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -16,23 +14,12 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B /// public class GetBookEndpoint : BaseEndpoint { - private readonly ISender _sender; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for mediating commands and queries. - public GetBookEndpoint(ISender sender) - { - _sender = sender; - } - /// /// Configures the API endpoint. /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Books.GET_BOOK_BY_ID); Version(1); AllowAnonymous(); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs index cd6dd0ae..53f86381 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -21,15 +20,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B /// public class GetBooksEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler>> _getBooksQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetBooksEndpoint(ISender sender) + /// Injected service for handling get books queries. + public GetBooksEndpoint(IQueryHandler>> getBooksQueryHandler) { - _sender = sender; + _getBooksQueryHandler = getBooksQueryHandler; } /// @@ -37,7 +36,7 @@ public class GetBooksEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Books.GET_BOOKS); Version(1); DontCatchExceptions(); @@ -50,7 +49,7 @@ public class GetBooksEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetBooksRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _getBooksQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs index d2ce826f..1c74f417 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; using Lumina.Contracts.Responses.UsersManagement; using Lumina.Presentation.Api.Common.Routes.Maintenance; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -17,15 +17,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; /// public class CheckInitializationEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler _checkInitializationQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public CheckInitializationEndpoint(ISender sender) + /// Injected service for handling check initialization queries. + public CheckInitializationEndpoint(IQueryHandler checkInitializationQueryHandler) { - _sender = sender; + _checkInitializationQueryHandler = checkInitializationQueryHandler; } /// @@ -33,7 +33,7 @@ public class CheckInitializationEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Initialization.CHECK_INITIALIZATION); Version(1); AllowAnonymous(); @@ -46,7 +46,7 @@ public class CheckInitializationEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - InitializationResponse result = await _sender.Send(new CheckInitializationQuery(), cancellationToken).ConfigureAwait(false); + InitializationResponse result = await _checkInitializationQueryHandler.HandleAsync(new CheckInitializationQuery(), cancellationToken).ConfigureAwait(false); return TypedResults.Ok(result); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs index c7b79cf6..195ceaff 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; /// public class SetupApplicationEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _setupApplicationCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public SetupApplicationEndpoint(ISender sender) + /// Injected service for handling setup application commands. + public SetupApplicationEndpoint(ICommandHandler> setupApplicationCommandHandler) { - _sender = sender; + _setupApplicationCommandHandler = setupApplicationCommandHandler; } /// @@ -35,7 +35,7 @@ public class SetupApplicationEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.POST); + Verbs(FastEndpoints.Http.POST); Routes(ApiRoutes.Initialization.SETUP_APPLICATION); Version(1); AllowAnonymous(); @@ -49,7 +49,7 @@ public class SetupApplicationEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToSetupCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _setupApplicationCommandHandler.HandleAsync(request.ToSetupCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{Api.Common.Routes.UsersManagement.ApiRoutes.Users.GET_USER_BY_ID.Replace("{id}", success.Id.ToString())}", result.Value), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs index fd622095..873837ad 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs @@ -1,17 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; -using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; -using Lumina.Contracts.Requests.FileSystemManagement.Directories; -using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; -using Lumina.Contracts.Responses.FileSystemManagement; using Lumina.Presentation.Api.Common.Routes.Maintenance; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; -using System.Collections.Generic; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance; @@ -21,23 +14,12 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance; /// public class CheckHealthEndpoint : BaseEndpoint { - private readonly ISender _sender; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for mediating commands and queries. - public CheckHealthEndpoint(ISender sender) - { - _sender = sender; - } - /// /// Configures the API endpoint. /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Health.CHECK_HEALTH); Version(1); AllowAnonymous(); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpoint.cs index 88a9f564..b5260a14 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; using Lumina.Contracts.Requests.Plugins; using Lumina.Contracts.Responses.Plugins; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -20,15 +20,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryMetadataProvi /// public class GetLibraryMetadataProvidersEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler>> _getLibraryMetadataProvidersQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetLibraryMetadataProvidersEndpoint(ISender sender) + /// Injected service for handling get library metadata providers queries. + public GetLibraryMetadataProvidersEndpoint(IQueryHandler>> getLibraryMetadataProvidersQueryHandler) { - _sender = sender; + _getLibraryMetadataProvidersQueryHandler = getLibraryMetadataProvidersQueryHandler; } /// @@ -36,7 +36,7 @@ public class GetLibraryMetadataProvidersEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Libraries.GET_LIBRARY_METADATA_PROVIDERS); Version(1); DontCatchExceptions(); @@ -49,7 +49,7 @@ public class GetLibraryMetadataProvidersEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetLibraryMetadataProvidersRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _getLibraryMetadataProvidersQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs index 5171e4e8..4d256e64 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetPluginSettings; using Lumina.Contracts.Requests.Plugins; using Lumina.Contracts.Responses.Plugins; using Lumina.Presentation.Api.Common.Routes.Plugins; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPluginSettings; /// public class GetPluginSettingsEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler> _getPluginSettingsQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetPluginSettingsEndpoint(ISender sender) + /// Injected service for handling get plugin settings queries. + public GetPluginSettingsEndpoint(IQueryHandler> getPluginSettingsQueryHandler) { - _sender = sender; + _getPluginSettingsQueryHandler = getPluginSettingsQueryHandler; } /// @@ -35,7 +35,7 @@ public class GetPluginSettingsEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Plugins.GET_PLUGIN_SETTINGS); Version(1); DontCatchExceptions(); @@ -48,7 +48,7 @@ public class GetPluginSettingsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetPluginSettingsRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _getPluginSettingsQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs index adb03b12..fb276ae9 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Plugins.Queries.GetPlugins; using Lumina.Contracts.Responses.Plugins; using Lumina.Presentation.Api.Common.Routes.Plugins; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPlugins; /// public class GetPluginsEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler>> _getPluginsQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetPluginsEndpoint(ISender sender) + /// Injected service for handling get plugins queries. + public GetPluginsEndpoint(IQueryHandler>> getPluginsQueryHandler) { - _sender = sender; + _getPluginsQueryHandler = getPluginsQueryHandler; } /// @@ -35,7 +35,7 @@ public class GetPluginsEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Plugins.GET_PLUGINS); Version(1); DontCatchExceptions(); @@ -47,7 +47,7 @@ public class GetPluginsEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(new GetPluginsQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _getPluginsQueryHandler.HandleAsync(new GetPluginsQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs index ce196936..4623c080 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; using Lumina.Contracts.Requests.Plugins; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -18,15 +18,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataP /// public class ReorderLibraryMetadataProvidersEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _reorderLibraryMetadataProvidersCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public ReorderLibraryMetadataProvidersEndpoint(ISender sender) + /// Injected service for handling reorder library metadata providers commands. + public ReorderLibraryMetadataProvidersEndpoint(ICommandHandler> reorderLibraryMetadataProvidersCommandHandler) { - _sender = sender; + _reorderLibraryMetadataProvidersCommandHandler = reorderLibraryMetadataProvidersCommandHandler; } /// @@ -34,7 +34,7 @@ public class ReorderLibraryMetadataProvidersEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.PUT); + Verbs(FastEndpoints.Http.PUT); Routes(ApiRoutes.Libraries.REORDER_LIBRARY_METADATA_PROVIDERS); Version(1); DontCatchExceptions(); @@ -47,7 +47,7 @@ public class ReorderLibraryMetadataProvidersEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(ReorderLibraryMetadataProvidersRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _reorderLibraryMetadataProvidersCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs index 2f4247ad..fc331dd1 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; using Lumina.Contracts.Requests.Plugins; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -18,15 +18,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProvi /// public class SetLibraryMetadataProviderEnabledEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _setLibraryMetadataProviderEnabledCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public SetLibraryMetadataProviderEnabledEndpoint(ISender sender) + /// Injected service for handling set library metadata provider enabled commands. + public SetLibraryMetadataProviderEnabledEndpoint(ICommandHandler> setLibraryMetadataProviderEnabledCommandHandler) { - _sender = sender; + _setLibraryMetadataProviderEnabledCommandHandler = setLibraryMetadataProviderEnabledCommandHandler; } /// @@ -34,7 +34,7 @@ public class SetLibraryMetadataProviderEnabledEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.PUT); + Verbs(FastEndpoints.Http.PUT); Routes(ApiRoutes.Libraries.SET_LIBRARY_METADATA_PROVIDER_ENABLED); Version(1); DontCatchExceptions(); @@ -47,7 +47,7 @@ public class SetLibraryMetadataProviderEnabledEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(SetLibraryMetadataProviderEnabledRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _setLibraryMetadataProviderEnabledCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs index 76cecc8e..9045a879 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; using Lumina.Contracts.Requests.Plugins; using Lumina.Presentation.Api.Common.Routes.Plugins; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -18,15 +18,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.UpdatePluginSettings; /// public class UpdatePluginSettingsEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _updatePluginSettingsCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public UpdatePluginSettingsEndpoint(ISender sender) + /// Injected service for handling update plugin settings commands. + public UpdatePluginSettingsEndpoint(ICommandHandler> updatePluginSettingsCommandHandler) { - _sender = sender; + _updatePluginSettingsCommandHandler = updatePluginSettingsCommandHandler; } /// @@ -34,7 +34,7 @@ public class UpdatePluginSettingsEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.PUT); + Verbs(FastEndpoints.Http.PUT); Routes(ApiRoutes.Plugins.UPDATE_PLUGIN_SETTINGS); Version(1); DontCatchExceptions(); @@ -47,7 +47,7 @@ public class UpdatePluginSettingsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdatePluginSettingsRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _updatePluginSettingsCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs index 72eb7a55..dc3352ca 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication. /// public class ChangePasswordEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _changePasswordCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public ChangePasswordEndpoint(ISender sender) + /// Injected service for handling change password commands. + public ChangePasswordEndpoint(ICommandHandler> changePasswordCommandHandler) { - _sender = sender; + _changePasswordCommandHandler = changePasswordCommandHandler; } /// @@ -35,7 +35,7 @@ public class ChangePasswordEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.POST); + Verbs(FastEndpoints.Http.POST); Routes(ApiRoutes.Authentication.CHANGE_PASSWORD); Version(1); DontCatchExceptions(); @@ -48,7 +48,7 @@ public class ChangePasswordEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(ChangePasswordRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _changePasswordCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpoint.cs index 6a1b24b5..b68fb6ed 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpoint.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUsers; using Lumina.Contracts.Responses.UsersManagement.Users; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication. /// public class GetUsersEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler>> _getUsersQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetUsersEndpoint(ISender sender) + /// Injected service for handling get users queries. + public GetUsersEndpoint(IQueryHandler>> getUsersQueryHandler) { - _sender = sender; + _getUsersQueryHandler = getUsersQueryHandler; } /// @@ -35,7 +35,7 @@ public class GetUsersEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Authentication.USERS); Version(1); DontCatchExceptions(); @@ -47,7 +47,7 @@ public class GetUsersEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(new GetUsersQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _getUsersQueryHandler.HandleAsync(new GetUsersQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs index cad0554d..fde99824 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Caching.Memory; @@ -23,15 +23,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication. /// public class LoginEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler> _loginQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public LoginEndpoint(ISender sender) + /// Injected service for handling login queries. + public LoginEndpoint(IQueryHandler> loginQueryHandler) { - _sender = sender; + _loginQueryHandler = loginQueryHandler; } /// @@ -39,7 +39,7 @@ public class LoginEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.POST); + Verbs(FastEndpoints.Http.POST); Routes(ApiRoutes.Authentication.LOGIN_ACCOUNT); Version(1); AllowAnonymous(); @@ -54,7 +54,7 @@ public class LoginEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(LoginRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _loginQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs index 4686e25e..5a33a86c 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading; @@ -20,15 +20,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication. /// public class RecoverPasswordEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _recoverPasswordCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public RecoverPasswordEndpoint(ISender sender) + /// Injected service for handling recover password commands. + public RecoverPasswordEndpoint(ICommandHandler> recoverPasswordCommandHandler) { - _sender = sender; + _recoverPasswordCommandHandler = recoverPasswordCommandHandler; } /// @@ -36,7 +36,7 @@ public class RecoverPasswordEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.POST); + Verbs(FastEndpoints.Http.POST); Routes(ApiRoutes.Authentication.RECOVER_PASSWORD); Version(1); AllowAnonymous(); @@ -51,7 +51,7 @@ public class RecoverPasswordEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(RecoverPasswordRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _recoverPasswordCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs index 95351ca1..e55ae991 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading; @@ -20,15 +20,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication. /// public class RegisterEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _registerUserCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public RegisterEndpoint(ISender sender) + /// Injected service for handling register user commands. + public RegisterEndpoint(ICommandHandler> registerUserCommandHandler) { - _sender = sender; + _registerUserCommandHandler = registerUserCommandHandler; } /// @@ -36,7 +36,7 @@ public class RegisterEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.POST); + Verbs(FastEndpoints.Http.POST); Routes(ApiRoutes.Authentication.REGISTER_ACCOUNT); Version(1); AllowAnonymous(); @@ -51,7 +51,7 @@ public class RegisterEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _registerUserCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Users.GET_USER_BY_ID.Replace("{id}", success.Id.ToString())}", result.Value), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpoint.cs index ee084521..3f31c974 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpoint.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authentication; using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -20,15 +20,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.G /// public class GetAuthorizationEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler> _getAuthorizationQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetAuthorizationEndpoint(ISender sender) + /// Injected service for handling get authorization queries. + public GetAuthorizationEndpoint(IQueryHandler> getAuthorizationQueryHandler) { - _sender = sender; + _getAuthorizationQueryHandler = getAuthorizationQueryHandler; } /// @@ -36,7 +36,7 @@ public class GetAuthorizationEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Authorization.GET_AUTHORIZATION); Version(1); DontCatchExceptions(); @@ -49,7 +49,7 @@ public class GetAuthorizationEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetAuthorizationRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _getAuthorizationQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpoint.cs index dd9b8f94..1539c716 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpoint.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authentication; using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -21,15 +21,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.G /// public class GetUserPermissionsEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler>> _getUserPermissionsQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetUserPermissionsEndpoint(ISender sender) + /// Injected service for handling get user permissions queries. + public GetUserPermissionsEndpoint(IQueryHandler>> getUserPermissionsQueryHandler) { - _sender = sender; + _getUserPermissionsQueryHandler = getUserPermissionsQueryHandler; } /// @@ -37,7 +37,7 @@ public class GetUserPermissionsEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Authorization.GET_USER_PERMISSIONS_BY_USER_ID); Version(1); DontCatchExceptions(); @@ -50,7 +50,7 @@ public class GetUserPermissionsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetUserPermissionsRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _getUserPermissionsQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpoint.cs index 8c2e8542..072ba2fe 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpoint.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authentication; using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Threading; @@ -21,15 +21,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.G /// public class GetUserRoleEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly IQueryHandler> _getUserRoleQueryHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public GetUserRoleEndpoint(ISender sender) + /// Injected service for handling get user role queries. + public GetUserRoleEndpoint(IQueryHandler> getUserRoleQueryHandler) { - _sender = sender; + _getUserRoleQueryHandler = getUserRoleQueryHandler; } /// @@ -37,7 +37,7 @@ public class GetUserRoleEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Authorization.GET_USER_ROLE_BY_USER_ID); Version(1); DontCatchExceptions(); @@ -50,7 +50,7 @@ public class GetUserRoleEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetUserRoleRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _getUserRoleQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpoint.cs index 7ebd5a3c..5ef4af57 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.U /// public class UpdateUserRoleAndPermissionsEndpoint : BaseEndpoint { - private readonly ISender _sender; + private readonly ICommandHandler> _updateUserRoleAndPermissionsCommandHandler; /// /// Initializes a new instance of the class. /// - /// Injected service for mediating commands and queries. - public UpdateUserRoleAndPermissionsEndpoint(ISender sender) + /// Injected service for handling update user role and permissions commands. + public UpdateUserRoleAndPermissionsEndpoint(ICommandHandler> updateUserRoleAndPermissionsCommandHandler) { - _sender = sender; + _updateUserRoleAndPermissionsCommandHandler = updateUserRoleAndPermissionsCommandHandler; } /// @@ -35,7 +35,7 @@ public class UpdateUserRoleAndPermissionsEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.PUT); + Verbs(FastEndpoints.Http.PUT); Routes(ApiRoutes.Authorization.UPDATE_USER_ROLE_AND_PERMISSIONS_BY_USER_ID); Version(1); DontCatchExceptions(); @@ -48,7 +48,7 @@ public class UpdateUserRoleAndPermissionsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdateUserRoleAndPermissionsRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _updateUserRoleAndPermissionsCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj index 6114a9a6..a1a29f78 100644 --- a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj +++ b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj @@ -1,4 +1,4 @@ - + net10.0 enable @@ -13,7 +13,10 @@ lumina-api ..\docker-compose.dcproj - + + en + + @@ -21,11 +24,6 @@ - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - @@ -59,9 +57,4 @@ - - - - $(NoWarn);CS0436 - diff --git a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj index e6639816..1d093b6a 100644 --- a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj +++ b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj @@ -357,7 +357,6 @@ - $(NoWarn);TS6385 diff --git a/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js b/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js index a3e87f67..566d9279 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js @@ -249,21 +249,26 @@ */ async function checkPathAsync(path) { const pathValidResponse = await callApiGetAsync(`${clientBasePath}path/api-validate?path=${encodeURIComponent(path)}`); - if (pathValidResponse !== undefined) { - if (!pathValidResponse.isValid) { - notificationService.show("Specified path is not valid!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented - addressBarInput.value = _path; - if (addressBarInput.value !== null && !addressBarInput.value.endsWith(pathSeparator)) - addressBarInput.value += pathSeparator; - } else { - const pathExistsResponse = await callApiGetAsync(`${clientBasePath}path/api-check-path-exists?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`); - if (pathExistsResponse !== undefined && !pathExistsResponse.exists) { - notificationService.show("Specified path does not exist!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented - return false; - } - } - return pathValidResponse.isValid; + if (pathValidResponse === undefined) { + // the API rejected the path with a validation error (e.g. it is empty), treat it as invalid and restore the address bar + addressBarInput.value = _path; + if (addressBarInput.value !== null && !addressBarInput.value.endsWith(pathSeparator)) + addressBarInput.value += pathSeparator; + return false; } + if (!pathValidResponse.isValid) { + notificationService.show("Specified path is not valid!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented + addressBarInput.value = _path; + if (addressBarInput.value !== null && !addressBarInput.value.endsWith(pathSeparator)) + addressBarInput.value += pathSeparator; + } else { + const pathExistsResponse = await callApiGetAsync(`${clientBasePath}path/api-check-path-exists?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`); + if (pathExistsResponse !== undefined && !pathExistsResponse.exists) { + notificationService.show("Specified path does not exist!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented + return false; + } + } + return pathValidResponse.isValid; } /** diff --git a/src/Lumina.sln b/src/Lumina.sln index d29d523a..705b4779 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -191,6 +191,15 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-decision-log", ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0001.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0001.md ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0002.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0002.md ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0003.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0003.md + ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0004.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0004.md + ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0005.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0005.md + ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0006.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0006.md + ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0007.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0007.md + ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0008.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0008.md + ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0009.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0009.md + ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0010.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0010.md + ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0011.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0011.md + ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0012.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0012.md EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Contracts", "Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj", "{8CF6FEA4-624C-4EC9-93D6-EB7626059D7C}" diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs index 86a0d98b..219e0c99 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs @@ -1,7 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http; @@ -82,7 +84,7 @@ public class ValidatePathEndpointTests : IClassFixture(content, _jsonOptions); - Assert.NotNull(result); - Assert.False(result!.IsValid); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("/api/v1/path/validate", problemDetails["instance"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/Fixtures/ValidationBehaviorFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/Fixtures/ValidationBehaviorFixture.cs deleted file mode 100644 index 3fc074bd..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/Fixtures/ValidationBehaviorFixture.cs +++ /dev/null @@ -1,16 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Mediator; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Behaviors.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class ValidationBehaviorFixture : IRequest> -{ - -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/Fixtures/ValidationBehaviorTestResponse.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/Fixtures/ValidationBehaviorTestResponse.cs deleted file mode 100644 index bd3f7b13..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/Fixtures/ValidationBehaviorTestResponse.cs +++ /dev/null @@ -1,13 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Behaviors.Fixtures; - -/// -/// Fixture test class for validation behavior responses. -/// -[ExcludeFromCodeCoverage] -public class ValidationBehaviorTestResponse -{ -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/ValidationBehaviorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/ValidationBehaviorTests.cs deleted file mode 100644 index 88e817fd..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/ValidationBehaviorTests.cs +++ /dev/null @@ -1,99 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using FluentValidation; -using FluentValidation.Results; -using Lumina.Application.Common.Behaviors; -using Lumina.Application.UnitTests.Common.Behaviors.Fixtures; -using Mediator; -using NSubstitute; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Application.UnitTests.Common.Behaviors; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ValidationBehaviorTests -{ - private readonly IValidator _mockValidator; - private readonly MessageHandlerDelegate> _nextDelegate; - - /// - /// Initializes a new instance of the class. - /// - public ValidationBehaviorTests() - { - _mockValidator = Substitute.For>(); - _nextDelegate = Substitute.For>>(); - } - - [Fact] - public async Task Handle_WhenValidatorIsNull_ShouldInvokeNextDelegate() - { - // Arrange - ValidationBehavior> behavior = new(); - ValidationBehaviorFixture request = new(); - ValidationBehaviorTestResponse expectedResponse = new(); - _nextDelegate.Invoke(request, Arg.Any()).Returns(new ValueTask>(ErrorOrFactory.From(expectedResponse))); - - // Act - ErrorOr result = await behavior.Handle(request, _nextDelegate, CancellationToken.None); - - // Assert - Assert.False(result.IsError); - Assert.Equal(expectedResponse, result.Value); - await _nextDelegate.Received(1).Invoke(request, Arg.Any()); - } - - [Fact] - public async Task Handle_WhenValidationSucceeds_ShouldInvokeNextDelegate() - { - // Arrange - ValidationBehavior> behavior = new(_mockValidator); - ValidationBehaviorFixture request = new(); - ValidationBehaviorTestResponse expectedResponse = new(); - _mockValidator.ValidateAsync(request, Arg.Any()).Returns(new ValidationResult()); - _nextDelegate.Invoke(request, Arg.Any()).Returns(new ValueTask>(ErrorOrFactory.From(expectedResponse))); - - // Act - ErrorOr result = await behavior.Handle(request, _nextDelegate, CancellationToken.None); - - // Assert - Assert.False(result.IsError); - Assert.Equal(expectedResponse, result.Value); - await _mockValidator.Received(1).ValidateAsync(request, Arg.Any()); - await _nextDelegate.Received(1).Invoke(request, Arg.Any()); - } - - [Fact] - public async Task Handle_WhenValidationFails_ShouldReturnErrors() - { - // Arrange - ValidationBehavior> behavior = new(_mockValidator); - ValidationBehaviorFixture request = new(); - List validationFailures = - [ - new ValidationFailure("Property1", "Error message 1"), - new ValidationFailure("Property2", "Error message 2") - ]; - _mockValidator.ValidateAsync(request, Arg.Any()).Returns(new ValidationResult(validationFailures)); - - // Act - ErrorOr result = await behavior.Handle(request, _nextDelegate, CancellationToken.None); - - // Assert - Assert.True(result.IsError); - Assert.Equal(2, result.Errors.Count); - Assert.Equal(ErrorType.Validation, result.Errors[0].Type); - Assert.Equal("Error message 1", result.Errors[0].Description); - Assert.Equal(ErrorType.Validation, result.Errors[1].Type); - Assert.Equal("Error message 2", result.Errors[1].Description); - await _mockValidator.Received(1).ValidateAsync(request, Arg.Any()); - await _nextDelegate.DidNotReceive().Invoke(request, Arg.Any()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/CQRS/HandlersCallTheirValidatorsTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/CQRS/HandlersCallTheirValidatorsTests.cs new file mode 100644 index 00000000..0672be4a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/CQRS/HandlersCallTheirValidatorsTests.cs @@ -0,0 +1,229 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Infrastructure.Validation; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +#endregion + +namespace Lumina.Application.UnitTests.Common.CQRS; + +/// +/// Contains tests that enforce the convention that command and query handlers always call the validator defined for their command or query. +/// +[ExcludeFromCodeCoverage] +public class HandlersCallTheirValidatorsTests +{ + private static readonly Assembly s_applicationAssembly = typeof(ICommand).Assembly; + private static readonly Dictionary s_opCodes = BuildOpCodeLookup(); + + /// + /// Ensures every command or query that has a validator has a handler that calls that validator. + /// + [Fact] + public void AllCommandAndQueryHandlers_WhenTheirRequestHasAValidator_ShouldCallIt() + { + // Arrange + List violations = []; + + // Act + foreach (Type type in s_applicationAssembly.GetTypes().Where(IsConcreteClass)) + { + foreach (Type implementedInterface in type.GetInterfaces().Where(IsValidatorInterface)) + { + Type requestType = implementedInterface.GetGenericArguments()[0]; + if (!IsCommandOrQuery(requestType)) + continue; + + Type? handlerType = FindHandlerFor(requestType); + if (handlerType is null) + { + violations.Add($"Validator '{type.FullName}' targets '{requestType.FullName}', which has no command or query handler."); + continue; + } + + if (!CallsValidator(handlerType, requestType)) + violations.Add($"Handler '{handlerType.FullName}' does not call 'IValidator<{requestType.Name}>.Validate'."); + } + } + + // Assert + Assert.True(violations.Count == 0, string.Join(Environment.NewLine, violations)); + } + + private static bool IsConcreteClass(Type type) + { + return !type.IsInterface && !type.IsAbstract && !type.IsGenericTypeDefinition; + } + + private static bool IsValidatorInterface(Type type) + { + return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IValidator<>); + } + + private static bool IsCommandOrQueryHandlerInterface(Type type) + { + if (!type.IsGenericType) + return false; + Type genericTypeDefinition = type.GetGenericTypeDefinition(); + return genericTypeDefinition == typeof(ICommandHandler<,>) || genericTypeDefinition == typeof(IQueryHandler<,>); + } + + private static bool IsCommandOrQuery(Type type) + { + return typeof(ICommand).IsAssignableFrom(type) || typeof(IQuery).IsAssignableFrom(type); + } + + private static Type? FindHandlerFor(Type requestType) + { + return s_applicationAssembly.GetTypes() + .Where(IsConcreteClass) + .FirstOrDefault(type => type.GetInterfaces().Any(@interface => + IsCommandOrQueryHandlerInterface(@interface) && @interface.GetGenericArguments()[0].Equals(requestType))); + } + + private static bool CallsValidator(Type handlerType, Type requestType) + { + Type validatorInterface = typeof(IValidator<>).MakeGenericType(requestType); + foreach (Type type in EnumerateTypeHierarchy(handlerType)) + foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly)) + if (CallsValidatorMethod(method, validatorInterface)) + return true; + return false; + } + + private static IEnumerable EnumerateTypeHierarchy(Type type) + { + yield return type; + foreach (Type nestedType in type.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic)) + foreach (Type nestedDescendant in EnumerateTypeHierarchy(nestedType)) + yield return nestedDescendant; + } + + /// + /// Checks whether the IL of the specified contains a call to . + /// + /// The method whose IL is inspected. + /// The closed validator interface whose Validate method is being looked for. + /// if the method calls the validator, otherwise. + private static bool CallsValidatorMethod(MethodInfo method, Type validatorInterface) + { + MethodBody? body = method.GetMethodBody(); + if (body is null) + return false; + + byte[]? il = body.GetILAsByteArray(); + if (il is null) + return false; + + Module module = method.Module; + int offset = 0; + while (offset < il.Length) + { + // read the opcode, handling the 0xFE prefix used by two-byte opcodes + short opCodeValue = il[offset]; + int opCodeSize = 1; + if (opCodeValue == 0xFE && offset + 1 < il.Length) + { + opCodeValue = (short)((0xFE << 8) | il[offset + 1]); + opCodeSize = 2; + } + + if (!s_opCodes.TryGetValue(opCodeValue, out OpCode opCode)) + return false; + + offset += opCodeSize; + if (offset >= il.Length) + break; + + if (opCode == OpCodes.Call || opCode == OpCodes.Callvirt) + { + int token = ReadInt32(il, offset); + try + { + if (module.ResolveMethod(token) is MethodInfo resolvedMethod && + resolvedMethod.Name == nameof(IValidator.Validate) && + resolvedMethod.DeclaringType != null && + resolvedMethod.DeclaringType.Equals(validatorInterface)) + return true; + } + catch (ArgumentException) + { + // the token is not a valid method token, skip it + } + catch (BadImageFormatException) + { + // the token references corrupt metadata, skip it + } + catch (InvalidOperationException) + { + // the token cannot be resolved as a method, skip it + } + } + + if (opCode.OperandType == OperandType.InlineSwitch) + { + int switchCases = ReadInt32(il, offset); + offset += 4 + (switchCases * 4); + } + else + offset += GetOperandSize(opCode); + } + return false; + } + + /// + /// Builds a lookup table of all opcodes, keyed by their numeric value. + /// + /// The built lookup table. + private static Dictionary BuildOpCodeLookup() + { + Dictionary opCodes = []; + foreach (FieldInfo field in typeof(OpCodes).GetFields(BindingFlags.Public | BindingFlags.Static)) + if (field.GetValue(null) is OpCode opCode) + opCodes[opCode.Value] = opCode; + return opCodes; + } + + /// + /// Gets the size in bytes of the operand of the specified . + /// + /// The opcode whose operand size is returned. + /// The size of the operand in bytes. + private static int GetOperandSize(OpCode opCode) + { + return opCode.OperandType switch + { + OperandType.InlineNone => 0, + OperandType.ShortInlineI => 1, + OperandType.ShortInlineVar => 1, + OperandType.ShortInlineBrTarget => 1, + OperandType.InlineVar => 2, + OperandType.InlineBrTarget => 4, + OperandType.InlineField => 4, + OperandType.InlineMethod => 4, + OperandType.InlineType => 4, + OperandType.InlineString => 4, + OperandType.InlineSig => 4, + OperandType.ShortInlineR => 4, + OperandType.InlineI => 4, + OperandType.InlineR => 8, + OperandType.InlineI8 => 8, + _ => 0, + }; + } + + /// + /// Reads a 4-byte little-endian integer from the specified offset in the IL stream. + /// + /// The IL byte stream. + /// The offset at which to read the integer. + /// The read integer. + private static int ReadInt32(byte[] il, int offset) + { + return il[offset] | (il[offset + 1] << 8) | (il[offset + 2] << 16) | (il[offset + 3] << 24); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs new file mode 100644 index 00000000..bc7b3506 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.Infrastructure.Validation; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.UnitTests.Common.Setup; + +/// +/// Validator extension methods for for unit tests. +/// +public static class ValidatorTestExtensions +{ + /// + /// Executes the validator against the specified request instance and returns the resulting errors. + /// + /// The type of the request being validated. + /// The validator instance to execute. + /// The request instance to validate. + /// A list of produced by the validator. If the request is valid, the list will be empty. + public static List TestValidate(this IValidator validator, TRequest request) + { + return validator.Validate(request); + } + + /// + /// Asserts that the validation results do not contain the specified error. + /// + /// The list of errors returned by the validator. + /// The error that should not be present in the validation results. + public static void ShouldNotHaveValidationError(this List errors, Error expectedError) + { + Assert.DoesNotContain(errors, error => error.Description == expectedError.Description); + } + + /// + /// Asserts that the validation results contain the specified error. + /// + /// The list of errors returned by the validator. + /// The error that should be present in the validation results. + public static void ShouldHaveValidationError(this List errors, Error expectedError) + { + Assert.Contains(errors, error => error.Description == expectedError.Description); + } + + /// + /// Asserts that the validation results are completely empty, indicating the request is valid. + /// + /// The list of errors returned by the validator. + public static void ShouldNotHaveAnyValidationErrors(this List errors) + { + Assert.Empty(errors); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs index 75dbf4f6..bd6fe545 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs @@ -54,7 +54,7 @@ public class GetPermissionsQueryHandlerTests } [Fact] - public async Task Handle_WhenUserIsAdmin_ShouldReturnPermissions() + public async Task HandleAsync_WhenUserIsAdmin_ShouldReturnPermissions() { // Arrange GetPermissionsQuery query = new(); @@ -70,7 +70,7 @@ public class GetPermissionsQueryHandlerTests .Returns(ErrorOrFactory.From(permissions)); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -80,7 +80,7 @@ public class GetPermissionsQueryHandlerTests } [Fact] - public async Task Handle_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange GetPermissionsQuery query = new(); @@ -89,7 +89,7 @@ public class GetPermissionsQueryHandlerTests .Returns(false); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -99,7 +99,7 @@ public class GetPermissionsQueryHandlerTests } [Fact] - public async Task Handle_WhenGetAllPermissionsReturnsError_ShouldReturnError() + public async Task HandleAsync_WhenGetAllPermissionsReturnsError_ShouldReturnError() { // Arrange GetPermissionsQuery query = new(); @@ -111,7 +111,7 @@ public class GetPermissionsQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -121,7 +121,7 @@ public class GetPermissionsQueryHandlerTests } [Fact] - public async Task Handle_WhenCancellationRequested_ShouldStillCompleteOperation() + public async Task HandleAsync_WhenCancellationRequested_ShouldStillCompleteOperation() { // Arrange GetPermissionsQuery query = new(); @@ -137,7 +137,7 @@ public class GetPermissionsQueryHandlerTests .Returns(ErrorOrFactory.From(permissions)); // Act - ErrorOr> result = await _sut.Handle(query, cancellationToken); + ErrorOr> result = await _sut.HandleAsync(query, cancellationToken); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs index 66799e0f..9360cef3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.AddRole.Fixtures; using Lumina.Contracts.Responses.Authorization; @@ -39,6 +40,9 @@ public class AddRoleCommandHandlerTests /// public AddRoleCommandHandlerTests() { + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); _mockUnitOfWork = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); @@ -52,11 +56,12 @@ public class AddRoleCommandHandlerTests _sut = new AddRoleCommandHandler( _mockAuthorizationService, _mockCurrentUserService, - _mockUnitOfWork); + _mockUnitOfWork, + mockValidator); } [Fact] - public async Task Handle_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange AddRoleCommand command = _addRoleCommandFixture.CreateCommand(); @@ -64,7 +69,7 @@ public class AddRoleCommandHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -73,7 +78,7 @@ public class AddRoleCommandHandlerTests } [Fact] - public async Task Handle_WhenInsertRoleFails_ShouldReturnError() + public async Task HandleAsync_WhenInsertRoleFails_ShouldReturnError() { // Arrange AddRoleCommand command = _addRoleCommandFixture.CreateCommand(); @@ -85,7 +90,7 @@ public class AddRoleCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -94,7 +99,7 @@ public class AddRoleCommandHandlerTests } [Fact] - public async Task Handle_WhenGetRoleByNameFails_ShouldReturnError() + public async Task HandleAsync_WhenGetRoleByNameFails_ShouldReturnError() { // Arrange AddRoleCommand command = _addRoleCommandFixture.CreateCommand(); @@ -108,7 +113,7 @@ public class AddRoleCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -116,7 +121,7 @@ public class AddRoleCommandHandlerTests } [Fact] - public async Task Handle_WhenGetRoleByNameReturnsNull_ShouldReturnError() + public async Task HandleAsync_WhenGetRoleByNameReturnsNull_ShouldReturnError() { // Arrange AddRoleCommand command = _addRoleCommandFixture.CreateCommand(); @@ -129,7 +134,7 @@ public class AddRoleCommandHandlerTests .Returns((RoleEntity?)null); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -137,7 +142,7 @@ public class AddRoleCommandHandlerTests } [Fact] - public async Task Handle_WhenAllOperationsSucceed_ShouldReturnSuccessResponse() + public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccessResponse() { // Arrange AddRoleCommand command = _addRoleCommandFixture.CreateCommand(); @@ -146,7 +151,7 @@ public class AddRoleCommandHandlerTests { Id = roleId, RoleName = command.RoleName, - RolePermissions = command.Permissions.Select(p => new RolePermissionEntity + RolePermissions = [.. command.Permissions.Select(p => new RolePermissionEntity { RoleId = roleId, PermissionId = p, @@ -156,7 +161,7 @@ public class AddRoleCommandHandlerTests Id = p, PermissionName = AuthorizationPermission.CanViewUsers } - }).ToList() + })] }; _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -167,7 +172,7 @@ public class AddRoleCommandHandlerTests .Returns(role); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs index 9e4c4f24..818773ac 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs @@ -1,9 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.AddRole.Fixtures; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -35,11 +37,10 @@ public class AddRoleCommandValidatorTests command = command with { RoleName = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.RoleName) - .WithErrorMessage(Errors.Authorization.RoleNameCannotBeNull.Description); + result.ShouldHaveValidationError(Errors.Authorization.RoleNameCannotBeNull); } [Fact] @@ -50,11 +51,10 @@ public class AddRoleCommandValidatorTests command = command with { RoleName = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.RoleName) - .WithErrorMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authorization.RoleNameCannotBeEmpty); } [Fact] @@ -65,11 +65,10 @@ public class AddRoleCommandValidatorTests command = command with { RoleName = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.RoleName) - .WithErrorMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authorization.RoleNameCannotBeEmpty); } [Fact] @@ -80,11 +79,10 @@ public class AddRoleCommandValidatorTests command = command with { Permissions = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Permissions) - .WithErrorMessage(Errors.Authorization.PermissionsListCannotBeNull.Description); + result.ShouldHaveValidationError(Errors.Authorization.PermissionsListCannotBeNull); } [Fact] @@ -95,11 +93,10 @@ public class AddRoleCommandValidatorTests command = command with { Permissions = [] }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Permissions) - .WithErrorMessage(Errors.Authorization.PermissionsListCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authorization.PermissionsListCannotBeEmpty); } [Fact] @@ -110,11 +107,10 @@ public class AddRoleCommandValidatorTests command = command with { Permissions = [Guid.Empty, Guid.NewGuid()] }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor("Permissions[0]") - .WithErrorMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authorization.PermissionIdCannotBeEmpty); } [Fact] @@ -124,7 +120,7 @@ public class AddRoleCommandValidatorTests AddRoleCommand command = _fixture.CreateCommand(); // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert result.ShouldNotHaveAnyValidationErrors(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs index 2ffe3946..fd583879 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.DeleteRole.Fixtures; using NSubstitute; @@ -36,6 +37,9 @@ public class DeleteRoleCommandHandlerTests /// public DeleteRoleCommandHandlerTests() { + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); _mockUnitOfWork = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); @@ -49,11 +53,12 @@ public class DeleteRoleCommandHandlerTests _sut = new DeleteRoleCommandHandler( _mockAuthorizationService, _mockCurrentUserService, - _mockUnitOfWork); + _mockUnitOfWork, + mockValidator); } [Fact] - public async Task Handle_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand(); @@ -61,7 +66,7 @@ public class DeleteRoleCommandHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -70,7 +75,7 @@ public class DeleteRoleCommandHandlerTests } [Fact] - public async Task Handle_WhenRoleDoesNotExist_ShouldReturnRoleNotFoundError() + public async Task HandleAsync_WhenRoleDoesNotExist_ShouldReturnRoleNotFoundError() { // Arrange DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand(); @@ -81,7 +86,7 @@ public class DeleteRoleCommandHandlerTests .Returns((RoleEntity?)null); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -90,7 +95,7 @@ public class DeleteRoleCommandHandlerTests } [Fact] - public async Task Handle_WhenDeletingAdminRole_ShouldReturnAdminRoleCannotBeDeletedError() + public async Task HandleAsync_WhenDeletingAdminRole_ShouldReturnAdminRoleCannotBeDeletedError() { // Arrange DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand(); @@ -102,7 +107,7 @@ public class DeleteRoleCommandHandlerTests .Returns(adminRole); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -111,7 +116,7 @@ public class DeleteRoleCommandHandlerTests } [Fact] - public async Task Handle_WhenGetRoleByIdFails_ShouldReturnError() + public async Task HandleAsync_WhenGetRoleByIdFails_ShouldReturnError() { // Arrange DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand(); @@ -123,7 +128,7 @@ public class DeleteRoleCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -132,7 +137,7 @@ public class DeleteRoleCommandHandlerTests } [Fact] - public async Task Handle_WhenDeleteRoleFails_ShouldReturnError() + public async Task HandleAsync_WhenDeleteRoleFails_ShouldReturnError() { // Arrange DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand(); @@ -147,7 +152,7 @@ public class DeleteRoleCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -156,7 +161,7 @@ public class DeleteRoleCommandHandlerTests } [Fact] - public async Task Handle_WhenAllOperationsSucceed_ShouldReturnSuccess() + public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccess() { // Arrange DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand(); @@ -170,7 +175,7 @@ public class DeleteRoleCommandHandlerTests .Returns(Result.Deleted); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs index e86d0f56..4df71485 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; +using Lumina.Application.UnitTests.Common.Setup; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -31,11 +33,10 @@ public class DeleteRoleCommandValidatorTests DeleteRoleCommand command = new(Guid.Empty); // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.RoleId) - .WithErrorMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authorization.RoleIdCannotBeEmpty); } [Fact] @@ -45,9 +46,9 @@ public class DeleteRoleCommandValidatorTests DeleteRoleCommand command = new(Guid.NewGuid()); // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.RoleId); + result.ShouldNotHaveValidationError(Errors.Authorization.RoleIdCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs index b9708dd4..a9f585d6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.UpdateRole.Fixtures; using Lumina.Contracts.Responses.Authorization; @@ -39,6 +40,9 @@ public class UpdateRoleCommandHandlerTests /// public UpdateRoleCommandHandlerTests() { + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); _mockUnitOfWork = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); @@ -52,11 +56,12 @@ public class UpdateRoleCommandHandlerTests _sut = new UpdateRoleCommandHandler( _mockAuthorizationService, _mockCurrentUserService, - _mockUnitOfWork); + _mockUnitOfWork, + mockValidator); } [Fact] - public async Task Handle_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange UpdateRoleCommand command = _updateRoleCommandFixture.CreateCommand(); @@ -64,7 +69,7 @@ public class UpdateRoleCommandHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -73,7 +78,7 @@ public class UpdateRoleCommandHandlerTests } [Fact] - public async Task Handle_WhenUpdateRoleFails_ShouldReturnError() + public async Task HandleAsync_WhenUpdateRoleFails_ShouldReturnError() { // Arrange UpdateRoleCommand command = _updateRoleCommandFixture.CreateCommand(); @@ -85,7 +90,7 @@ public class UpdateRoleCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -94,7 +99,7 @@ public class UpdateRoleCommandHandlerTests } [Fact] - public async Task Handle_WhenGetRoleByIdFails_ShouldReturnError() + public async Task HandleAsync_WhenGetRoleByIdFails_ShouldReturnError() { // Arrange UpdateRoleCommand command = _updateRoleCommandFixture.CreateCommand(); @@ -108,7 +113,7 @@ public class UpdateRoleCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -116,7 +121,7 @@ public class UpdateRoleCommandHandlerTests } [Fact] - public async Task Handle_WhenGetRoleByIdReturnsNull_ShouldReturnError() + public async Task HandleAsync_WhenGetRoleByIdReturnsNull_ShouldReturnError() { // Arrange UpdateRoleCommand command = _updateRoleCommandFixture.CreateCommand(); @@ -129,7 +134,7 @@ public class UpdateRoleCommandHandlerTests .Returns((RoleEntity?)null); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -137,7 +142,7 @@ public class UpdateRoleCommandHandlerTests } [Fact] - public async Task Handle_WhenAllOperationsSucceed_ShouldReturnSuccessResponse() + public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccessResponse() { // Arrange UpdateRoleCommand command = _updateRoleCommandFixture.CreateCommand(); @@ -145,7 +150,7 @@ public class UpdateRoleCommandHandlerTests { Id = command.RoleId, RoleName = command.RoleName, - RolePermissions = command.Permissions.Select(p => new RolePermissionEntity + RolePermissions = [.. command.Permissions.Select(p => new RolePermissionEntity { RoleId = command.RoleId, PermissionId = p, @@ -155,7 +160,7 @@ public class UpdateRoleCommandHandlerTests Id = p, PermissionName = AuthorizationPermission.CanViewUsers } - }).ToList() + })] }; _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -166,7 +171,7 @@ public class UpdateRoleCommandHandlerTests .Returns(role); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs index f3e7b541..e42d4bfb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs @@ -1,9 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.UpdateRole.Fixtures; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -35,11 +37,10 @@ public class UpdateRoleCommandValidatorTests command = command with { RoleId = Guid.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.RoleId) - .WithErrorMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authorization.RoleIdCannotBeEmpty); } [Fact] @@ -50,11 +51,10 @@ public class UpdateRoleCommandValidatorTests command = command with { RoleName = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.RoleName) - .WithErrorMessage(Errors.Authorization.RoleNameCannotBeNull.Description); + result.ShouldHaveValidationError(Errors.Authorization.RoleNameCannotBeNull); } [Fact] @@ -65,11 +65,10 @@ public class UpdateRoleCommandValidatorTests command = command with { RoleName = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.RoleName) - .WithErrorMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authorization.RoleNameCannotBeEmpty); } [Fact] @@ -80,11 +79,10 @@ public class UpdateRoleCommandValidatorTests command = command with { RoleName = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.RoleName) - .WithErrorMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authorization.RoleNameCannotBeEmpty); } [Fact] @@ -95,11 +93,10 @@ public class UpdateRoleCommandValidatorTests command = command with { Permissions = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Permissions) - .WithErrorMessage(Errors.Authorization.PermissionsListCannotBeNull.Description); + result.ShouldHaveValidationError(Errors.Authorization.PermissionsListCannotBeNull); } [Fact] @@ -110,11 +107,10 @@ public class UpdateRoleCommandValidatorTests command = command with { Permissions = [] }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Permissions) - .WithErrorMessage(Errors.Authorization.PermissionsListCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authorization.PermissionsListCannotBeEmpty); } [Fact] @@ -125,11 +121,10 @@ public class UpdateRoleCommandValidatorTests command = command with { Permissions = [Guid.Empty, Guid.NewGuid()] }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor("Permissions[0]") - .WithErrorMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authorization.PermissionIdCannotBeEmpty); } [Fact] @@ -139,7 +134,7 @@ public class UpdateRoleCommandValidatorTests UpdateRoleCommand command = _fixture.CreateCommand(); // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert result.ShouldNotHaveAnyValidationErrors(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs index 4eb91472..8d0516d8 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.GetRolePermissions.Fixtures; using Lumina.Contracts.Responses.Authorization; @@ -38,6 +39,9 @@ public class GetRolePermissionsQueryHandlerTests /// public GetRolePermissionsQueryHandlerTests() { + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); _mockUnitOfWork = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); @@ -51,11 +55,12 @@ public class GetRolePermissionsQueryHandlerTests _sut = new GetRolePermissionsQueryHandler( _mockAuthorizationService, _mockCurrentUserService, - _mockUnitOfWork); + _mockUnitOfWork, + mockValidator); } [Fact] - public async Task Handle_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.CreateQuery(); @@ -63,7 +68,7 @@ public class GetRolePermissionsQueryHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -72,7 +77,7 @@ public class GetRolePermissionsQueryHandlerTests } [Fact] - public async Task Handle_WhenGetRoleByIdFails_ShouldReturnError() + public async Task HandleAsync_WhenGetRoleByIdFails_ShouldReturnError() { // Arrange GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.CreateQuery(); @@ -84,7 +89,7 @@ public class GetRolePermissionsQueryHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -92,7 +97,7 @@ public class GetRolePermissionsQueryHandlerTests } [Fact] - public async Task Handle_WhenRoleNotFound_ShouldReturnRoleNotFoundError() + public async Task HandleAsync_WhenRoleNotFound_ShouldReturnRoleNotFoundError() { // Arrange GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.CreateQuery(); @@ -103,7 +108,7 @@ public class GetRolePermissionsQueryHandlerTests .Returns((RoleEntity?)null); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -111,7 +116,7 @@ public class GetRolePermissionsQueryHandlerTests } [Fact] - public async Task Handle_WhenAllOperationsSucceed_ShouldReturnRolePermissions() + public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnRolePermissions() { // Arrange GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.CreateQuery(); @@ -141,7 +146,7 @@ public class GetRolePermissionsQueryHandlerTests .Returns(role); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs index 3d1483a7..55015c30 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; +using Lumina.Application.UnitTests.Common.Setup; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -31,11 +33,10 @@ public class GetRolePermissionsQueryValidatorTests GetRolePermissionsQuery query = new(Guid.Empty); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.RoleId) - .WithErrorMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authorization.RoleIdCannotBeEmpty); } [Fact] @@ -45,9 +46,9 @@ public class GetRolePermissionsQueryValidatorTests GetRolePermissionsQuery query = new(Guid.NewGuid()); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.RoleId); + result.ShouldNotHaveValidationError(Errors.Authorization.RoleIdCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs index de9ac33c..31a3da85 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs @@ -55,7 +55,7 @@ public class GetRolesQueryHandlerTests } [Fact] - public async Task Handle_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange GetRolesQuery query = _getRolesQueryFixture.CreateQuery(); @@ -63,7 +63,7 @@ public class GetRolesQueryHandlerTests .Returns(false); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -72,7 +72,7 @@ public class GetRolesQueryHandlerTests } [Fact] - public async Task Handle_WhenGetRolesFails_ShouldReturnError() + public async Task HandleAsync_WhenGetRolesFails_ShouldReturnError() { // Arrange GetRolesQuery query = _getRolesQueryFixture.CreateQuery(); @@ -84,7 +84,7 @@ public class GetRolesQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -92,7 +92,7 @@ public class GetRolesQueryHandlerTests } [Fact] - public async Task Handle_WhenAllOperationsSucceed_ShouldReturnRoles() + public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnRoles() { // Arrange GetRolesQuery query = _getRolesQueryFixture.CreateQuery(); @@ -108,7 +108,7 @@ public class GetRolesQueryHandlerTests .Returns(ErrorOrFactory.From(roles)); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs index 886dcf67..02a7b600 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs @@ -8,6 +8,7 @@ using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries using Lumina.Contracts.Responses.FileSystemManagement.Directories; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System; using System.Collections.Generic; @@ -37,12 +38,15 @@ public class GetDirectoriesQueryHandlerTests { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockDirectoryService = Substitute.For(); - _sut = new GetDirectoriesQueryHandler(_mockDirectoryService); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new GetDirectoriesQueryHandler(_mockDirectoryService, mockValidator); _directoryFixture = new DirectoryFixture(); } [Fact] - public async Task Handle_WhenCalledWithValidQueryWithoutFilesIncluded_ShouldReturnSuccessResult() + public async Task HandleAsync_WhenCalledWithValidQueryWithoutFilesIncluded_ShouldReturnSuccessResult() { // Arrange GetDirectoriesQuery getDirectoriesQuery = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(false); @@ -53,7 +57,7 @@ public class GetDirectoriesQueryHandlerTests .Returns(ErrorOrFactory.From(directories)); // Act - ErrorOr> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(getDirectoriesQuery, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -76,7 +80,7 @@ public class GetDirectoriesQueryHandlerTests } [Fact] - public async Task Handle_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult() + public async Task HandleAsync_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult() { // Arrange GetDirectoriesQuery getDirectoriesQuery = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(true); @@ -87,7 +91,7 @@ public class GetDirectoriesQueryHandlerTests .Returns(ErrorOrFactory.From(directories)); // Act - ErrorOr> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(getDirectoriesQuery, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -110,7 +114,7 @@ public class GetDirectoriesQueryHandlerTests } [Fact] - public async Task Handle_WhenDirectoryServiceReturnsError_ShouldReturnFailureResult() + public async Task HandleAsync_WhenDirectoryServiceReturnsError_ShouldReturnFailureResult() { // Arrange GetDirectoriesQuery query = _fixture.Create(); @@ -119,7 +123,7 @@ public class GetDirectoriesQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -128,7 +132,7 @@ public class GetDirectoriesQueryHandlerTests } [Fact] - public async Task Handle_WhenDirectoryServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() + public async Task HandleAsync_WhenDirectoryServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() { // Arrange GetDirectoriesQuery query = _fixture.Create(); @@ -137,7 +141,7 @@ public class GetDirectoriesQueryHandlerTests .Returns(emptyList); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs index 47e32cb6..78c3fd9f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs @@ -1,7 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Lumina.Domain.SharedKernel.Common.Errors; #endregion @@ -32,11 +34,10 @@ public class GetDirectoriesQueryValidatorTests query = query with { Path = null! }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -47,11 +48,10 @@ public class GetDirectoriesQueryValidatorTests query = query with { Path = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -62,11 +62,10 @@ public class GetDirectoriesQueryValidatorTests query = query with { Path = " " }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -77,10 +76,10 @@ public class GetDirectoriesQueryValidatorTests query = query with { Path = "/valid/path" }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Path); + result.ShouldNotHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -91,10 +90,10 @@ public class GetDirectoriesQueryValidatorTests query = query with { IncludeHiddenElements = true }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + result.ShouldNotHaveAnyValidationErrors(); } [Fact] @@ -105,9 +104,9 @@ public class GetDirectoriesQueryValidatorTests query = query with { IncludeHiddenElements = false }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + result.ShouldNotHaveAnyValidationErrors(); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs index 66c77f18..80b5ce4c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs @@ -39,7 +39,7 @@ public class GetDrivesQueryHandlerTests } [Fact] - public async Task Handle_WhenCalled_ShouldReturnSuccessResult() + public async Task HandleAsync_WhenCalled_ShouldReturnSuccessResult() { // Arrange GetDrivesQuery getDrivesQuery = _fixture.Create(); @@ -54,7 +54,7 @@ public class GetDrivesQueryHandlerTests .Returns(ErrorOrFactory.From(drives)); // Act - ErrorOr> result = await _sut.Handle(getDrivesQuery, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(getDrivesQuery, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -81,7 +81,7 @@ public class GetDrivesQueryHandlerTests } [Fact] - public async Task Handle_WhenDriveServiceReturnsError_ShouldReturnFailureResult() + public async Task HandleAsync_WhenDriveServiceReturnsError_ShouldReturnFailureResult() { // Arrange GetDrivesQuery query = _fixture.Create(); @@ -90,7 +90,7 @@ public class GetDrivesQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -99,7 +99,7 @@ public class GetDrivesQueryHandlerTests } [Fact] - public async Task Handle_WhenDriveServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() + public async Task HandleAsync_WhenDriveServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() { // Arrange GetDrivesQuery query = _fixture.Create(); @@ -108,7 +108,7 @@ public class GetDrivesQueryHandlerTests .Returns(emptyList); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs index c65c507a..a0fa6b16 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs @@ -40,14 +40,14 @@ public class GetFileSystemQueryHandlerTests [Theory] [InlineData(PlatformType.Unix)] [InlineData(PlatformType.Windows)] - public async Task Handle_WhenCalled_ShouldReturnCorrectFileSystemTypeResponse(PlatformType platformType) + public async Task HandleAsync_WhenCalled_ShouldReturnCorrectFileSystemTypeResponse(PlatformType platformType) { // Arrange GetFileSystemQuery query = _fixture.Create(); _mockPlatformContext.Platform.Returns(platformType); // Act - FileSystemTypeResponse result = await _sut.Handle(query, CancellationToken.None); + FileSystemTypeResponse result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.NotNull(result); @@ -56,14 +56,14 @@ public class GetFileSystemQueryHandlerTests } [Fact] - public async Task Handle_WhenCalled_ShouldReturnValueTaskResult() + public async Task HandleAsync_WhenCalled_ShouldReturnValueTaskResult() { // Arrange GetFileSystemQuery query = _fixture.Create(); _mockPlatformContext.Platform.Returns(PlatformType.Unix); // Act - ValueTask resultTask = _sut.Handle(query, CancellationToken.None); + Task resultTask = _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(resultTask.IsCompleted); @@ -73,7 +73,7 @@ public class GetFileSystemQueryHandlerTests } [Fact] - public async Task Handle_WhenCalled_ShouldNotDependOnQueryContent() + public async Task HandleAsync_WhenCalled_ShouldNotDependOnQueryContent() { // Arrange GetFileSystemQuery query1 = _fixture.Create(); @@ -81,8 +81,8 @@ public class GetFileSystemQueryHandlerTests _mockPlatformContext.Platform.Returns(PlatformType.Windows); // Act - FileSystemTypeResponse result1 = await _sut.Handle(query1, CancellationToken.None); - FileSystemTypeResponse result2 = await _sut.Handle(query2, CancellationToken.None); + FileSystemTypeResponse result1 = await _sut.HandleAsync(query1, CancellationToken.None); + FileSystemTypeResponse result2 = await _sut.HandleAsync(query2, CancellationToken.None); // Assert Assert.Equal(result1.PlatformType, result2.PlatformType); @@ -90,7 +90,7 @@ public class GetFileSystemQueryHandlerTests } [Fact] - public async Task Handle_WhenCalled_ShouldIgnoreCancellationToken() + public async Task HandleAsync_WhenCalled_ShouldIgnoreCancellationToken() { // Arrange GetFileSystemQuery query = _fixture.Create(); @@ -99,7 +99,7 @@ public class GetFileSystemQueryHandlerTests // Act & Assert Exception? exception = await Record.ExceptionAsync(async () => - await _sut.Handle(query, cancellationToken)); + await _sut.HandleAsync(query, cancellationToken)); Assert.Null(exception); _mockPlatformContextManager.Received(1).GetCurrentContext(); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs index ff69c2fc..a24e463d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs @@ -8,6 +8,7 @@ using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFi using Lumina.Contracts.Responses.FileSystemManagement.Files; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System; using System.Collections.Generic; @@ -37,12 +38,15 @@ public class GetFilesQueryHandlerTests { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockFileService = Substitute.For(); - _sut = new GetFilesQueryHandler(_mockFileService); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new GetFilesQueryHandler(_mockFileService, mockValidator); _fileFixture = new FileFixture(); } [Fact] - public async Task Handle_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult() + public async Task HandleAsync_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult() { // Arrange GetFilesQuery getFilesQuery = GetFilesQueryFixture.CreateGetFilesQuery(false); @@ -53,7 +57,7 @@ public class GetFilesQueryHandlerTests .Returns(ErrorOrFactory.From(files)); // Act - ErrorOr> result = await _sut.Handle(getFilesQuery, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(getFilesQuery, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -76,7 +80,7 @@ public class GetFilesQueryHandlerTests } [Fact] - public async Task Handle_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult() + public async Task HandleAsync_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult() { // Arrange GetFilesQuery getFilesQuery = GetFilesQueryFixture.CreateGetFilesQuery(true); @@ -87,7 +91,7 @@ public class GetFilesQueryHandlerTests .Returns(ErrorOrFactory.From(files)); // Act - ErrorOr> result = await _sut.Handle(getFilesQuery, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(getFilesQuery, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -110,7 +114,7 @@ public class GetFilesQueryHandlerTests } [Fact] - public async Task Handle_WhenFileServiceReturnsError_ShouldReturnFailureResult() + public async Task HandleAsync_WhenFileServiceReturnsError_ShouldReturnFailureResult() { // Arrange GetFilesQuery query = _fixture.Create(); @@ -119,7 +123,7 @@ public class GetFilesQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -128,7 +132,7 @@ public class GetFilesQueryHandlerTests } [Fact] - public async Task Handle_WhenFileServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() + public async Task HandleAsync_WhenFileServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() { // Arrange GetFilesQuery query = _fixture.Create(); @@ -137,7 +141,7 @@ public class GetFilesQueryHandlerTests .Returns(emptyList); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs index 60ea1b44..94c96481 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures; using Lumina.Domain.SharedKernel.Common.Errors; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -32,11 +34,10 @@ public class GetFilesQueryValidatorTests query = query with { Path = null! }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -47,11 +48,10 @@ public class GetFilesQueryValidatorTests query = query with { Path = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -62,11 +62,10 @@ public class GetFilesQueryValidatorTests query = query with { Path = " " }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -77,10 +76,10 @@ public class GetFilesQueryValidatorTests query = query with { Path = "/valid/path" }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Path); + result.ShouldNotHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -91,10 +90,10 @@ public class GetFilesQueryValidatorTests query = query with { IncludeHiddenElements = true }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + result.ShouldNotHaveAnyValidationErrors(); } [Fact] @@ -105,9 +104,9 @@ public class GetFilesQueryValidatorTests query = query with { IncludeHiddenElements = false }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + result.ShouldNotHaveAnyValidationErrors(); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs index bad1bc4e..7e1bfa0c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs @@ -9,6 +9,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -37,12 +38,15 @@ public class GetTreeFilesQueryHandlerTests { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockFileService = Substitute.For(); - _sut = new GetTreeFilesQueryHandler(_mockFileService); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new GetTreeFilesQueryHandler(_mockFileService, mockValidator); _fileFixture = new FileFixture(); } [Fact] - public async Task Handle_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult() + public async Task HandleAsync_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult() { // Arrange GetTreeFilesQuery getFilesQuery = GetTreeFilesQueryFixture.CreateGetFilesQuery(false); @@ -53,7 +57,7 @@ public class GetTreeFilesQueryHandlerTests .Returns(ErrorOrFactory.From(files)); // Act - ErrorOr> result = await _sut.Handle(getFilesQuery, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(getFilesQuery, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -77,7 +81,7 @@ public class GetTreeFilesQueryHandlerTests } [Fact] - public async Task Handle_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult() + public async Task HandleAsync_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult() { // Arrange GetTreeFilesQuery getFilesQuery = GetTreeFilesQueryFixture.CreateGetFilesQuery(true); @@ -88,7 +92,7 @@ public class GetTreeFilesQueryHandlerTests .Returns(ErrorOrFactory.From(files)); // Act - ErrorOr> result = await _sut.Handle(getFilesQuery, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(getFilesQuery, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -112,7 +116,7 @@ public class GetTreeFilesQueryHandlerTests } [Fact] - public async Task Handle_WhenFileServiceReturnsError_ShouldReturnFailureResult() + public async Task HandleAsync_WhenFileServiceReturnsError_ShouldReturnFailureResult() { // Arrange GetTreeFilesQuery query = _fixture.Create(); @@ -121,7 +125,7 @@ public class GetTreeFilesQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -130,7 +134,7 @@ public class GetTreeFilesQueryHandlerTests } [Fact] - public async Task Handle_WhenFileServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() + public async Task HandleAsync_WhenFileServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() { // Arrange GetTreeFilesQuery query = _fixture.Create(); @@ -139,7 +143,7 @@ public class GetTreeFilesQueryHandlerTests .Returns(emptyList); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs index 14324952..e62ae42d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures; using Lumina.Domain.SharedKernel.Common.Errors; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -32,11 +34,10 @@ public class GetTreeFilesQueryValidatorTests query = query with { Path = null! }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -47,11 +48,10 @@ public class GetTreeFilesQueryValidatorTests query = query with { Path = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -62,11 +62,10 @@ public class GetTreeFilesQueryValidatorTests query = query with { Path = " " }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -77,10 +76,10 @@ public class GetTreeFilesQueryValidatorTests query = query with { Path = "/valid/path" }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Path); + result.ShouldNotHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -91,10 +90,10 @@ public class GetTreeFilesQueryValidatorTests query = query with { IncludeHiddenElements = true }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + result.ShouldNotHaveAnyValidationErrors(); } [Fact] @@ -105,9 +104,9 @@ public class GetTreeFilesQueryValidatorTests query = query with { IncludeHiddenElements = false }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + result.ShouldNotHaveAnyValidationErrors(); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs index 90f00f1a..3f954981 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; @@ -31,11 +32,14 @@ public class CombinePathCommandHandlerTests { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockPathService = Substitute.For(); - _sut = new CombinePathCommandHandler(_mockPathService); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new CombinePathCommandHandler(_mockPathService, mockValidator); } [Fact] - public async Task Handle_WhenCalledWithValidCommand_ShouldReturnSuccessResult() + public async Task HandleAsync_WhenCalledWithValidCommand_ShouldReturnSuccessResult() { // Arrange CombinePathCommand combinePathCommand = CombinePathCommandFixture.CreateCombinePathCommand(); @@ -45,7 +49,7 @@ public class CombinePathCommandHandlerTests .Returns(ErrorOrFactory.From(combinedPath)); // Act - ErrorOr result = await _sut.Handle(combinePathCommand, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(combinePathCommand, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -55,7 +59,7 @@ public class CombinePathCommandHandlerTests } [Fact] - public async Task Handle_WhenPathServiceReturnsError_ShouldReturnFailureResult() + public async Task HandleAsync_WhenPathServiceReturnsError_ShouldReturnFailureResult() { // Arrange CombinePathCommand command = _fixture.Create(); @@ -64,7 +68,7 @@ public class CombinePathCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -73,7 +77,7 @@ public class CombinePathCommandHandlerTests } [Fact] - public async Task Handle_WhenPathServiceReturnsEmptyString_ShouldReturnSuccessResultWithEmptyPath() + public async Task HandleAsync_WhenPathServiceReturnsEmptyString_ShouldReturnSuccessResultWithEmptyPath() { // Arrange CombinePathCommand command = _fixture.Create(); @@ -81,7 +85,7 @@ public class CombinePathCommandHandlerTests .Returns(ErrorOrFactory.From(string.Empty)); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs index b242be5a..856582db 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures; using Lumina.Domain.SharedKernel.Common.Errors; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -32,11 +34,10 @@ public class CombinePathCommandValidatorTests command = command with { OriginalPath = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.OriginalPath) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -47,11 +48,10 @@ public class CombinePathCommandValidatorTests command = command with { OriginalPath = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.OriginalPath) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -62,11 +62,10 @@ public class CombinePathCommandValidatorTests command = command with { OriginalPath = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.OriginalPath) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -77,11 +76,10 @@ public class CombinePathCommandValidatorTests command = command with { NewPath = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.NewPath) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -92,11 +90,10 @@ public class CombinePathCommandValidatorTests command = command with { NewPath = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.NewPath) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -107,11 +104,10 @@ public class CombinePathCommandValidatorTests command = command with { NewPath = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.NewPath) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -122,10 +118,10 @@ public class CombinePathCommandValidatorTests command = command with { OriginalPath = "/valid/path", NewPath = "new/segment" }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.OriginalPath); - result.ShouldNotHaveValidationErrorFor(x => x.NewPath); + result.ShouldNotHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs index 38c810ff..247c5cae 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs @@ -8,6 +8,7 @@ using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System; using System.Collections.Generic; @@ -37,12 +38,15 @@ public class SplitPathCommandHandlerTests { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockPathService = Substitute.For(); - _sut = new SplitPathCommandHandler(_mockPathService); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new SplitPathCommandHandler(_mockPathService, mockValidator); _pathSegmentFixture = new PathSegmentFixture(); } [Fact] - public async Task Handle_WhenCalledWithValidCommand_ShouldReturnSuccessResult() + public async Task HandleAsync_WhenCalledWithValidCommand_ShouldReturnSuccessResult() { // Arrange SplitPathCommand splitPathCommand = SplitPathCommandFixture.CreateSplitPathCommand(); @@ -53,7 +57,7 @@ public class SplitPathCommandHandlerTests .Returns(ErrorOrFactory.From(pathSegments)); // Act - ErrorOr> result = await _sut.Handle(splitPathCommand, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(splitPathCommand, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -69,7 +73,7 @@ public class SplitPathCommandHandlerTests } [Fact] - public async Task Handle_WhenPathServiceReturnsError_ShouldReturnFailureResult() + public async Task HandleAsync_WhenPathServiceReturnsError_ShouldReturnFailureResult() { // Arrange SplitPathCommand command = _fixture.Create(); @@ -78,7 +82,7 @@ public class SplitPathCommandHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.Handle(command, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -87,7 +91,7 @@ public class SplitPathCommandHandlerTests } [Fact] - public async Task Handle_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() + public async Task HandleAsync_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() { // Arrange SplitPathCommand command = _fixture.Create(); @@ -96,7 +100,7 @@ public class SplitPathCommandHandlerTests .Returns(emptyList); // Act - ErrorOr> result = await _sut.Handle(command, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs index 3c773e4f..04e34a2e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures; using Lumina.Domain.SharedKernel.Common.Errors; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -32,11 +34,10 @@ public class SplitPathCommandValidatorTests command = command with { Path = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -47,11 +48,10 @@ public class SplitPathCommandValidatorTests command = command with { Path = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -62,11 +62,10 @@ public class SplitPathCommandValidatorTests command = command with { Path = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -77,9 +76,9 @@ public class SplitPathCommandValidatorTests command = command with { Path = "/valid/path" }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Path); + result.ShouldNotHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs index 122fed20..5c0569a8 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs @@ -4,6 +4,7 @@ using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; @@ -27,18 +28,21 @@ public class CheckPathExistsQueryHandlerTests public CheckPathExistsQueryHandlerTests() { _mockPathService = Substitute.For(); - _sut = new CheckPathExistsQueryHandler(_mockPathService); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new CheckPathExistsQueryHandler(_mockPathService, mockValidator); } [Fact] - public async Task Handle_WhenPathExistsAndIsNotHidden_ShouldReturnTrueResponse() + public async Task HandleAsync_WhenPathExistsAndIsNotHidden_ShouldReturnTrueResponse() { // Arrange CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); _mockPathService.Exists(query.Path!).Returns(true); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -47,14 +51,14 @@ public class CheckPathExistsQueryHandlerTests } [Fact] - public async Task Handle_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsTrue_ShouldReturnTrueResponse() + public async Task HandleAsync_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsTrue_ShouldReturnTrueResponse() { // Arrange CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(true); _mockPathService.Exists(query.Path!).Returns(true); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -63,14 +67,14 @@ public class CheckPathExistsQueryHandlerTests } [Fact] - public async Task Handle_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsFalse_ShouldReturnFalseResponse() + public async Task HandleAsync_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsFalse_ShouldReturnFalseResponse() { // Arrange CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(false); _mockPathService.Exists(query.Path!, false).Returns(false); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -79,14 +83,14 @@ public class CheckPathExistsQueryHandlerTests } [Fact] - public async Task Handle_WhenPathDoesNotExist_ShouldReturnFalseResponse() + public async Task HandleAsync_WhenPathDoesNotExist_ShouldReturnFalseResponse() { // Arrange CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); _mockPathService.Exists(query.Path!).Returns(false); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -95,14 +99,14 @@ public class CheckPathExistsQueryHandlerTests } [Fact] - public async Task Handle_WhenCalledWithNullPath_ShouldStillCallPathService() + public async Task HandleAsync_WhenCalledWithNullPath_ShouldStillCallPathService() { // Arrange CheckPathExistsQuery query = new(null!, false); _mockPathService.Exists(Arg.Any(), Arg.Any()).Returns(false); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -111,7 +115,7 @@ public class CheckPathExistsQueryHandlerTests } [Fact] - public async Task Handle_WhenCancellationRequested_ShouldStillCompleteOperation() + public async Task HandleAsync_WhenCancellationRequested_ShouldStillCompleteOperation() { // Arrange CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); @@ -119,7 +123,7 @@ public class CheckPathExistsQueryHandlerTests CancellationToken cancellationToken = new(true); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs index 84bcbbae..950bc114 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures; using Lumina.Domain.SharedKernel.Common.Errors; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -32,11 +34,10 @@ public class CheckPathExistsQueryValidatorTests query = query with { Path = null! }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -47,11 +48,10 @@ public class CheckPathExistsQueryValidatorTests query = query with { Path = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -62,11 +62,10 @@ public class CheckPathExistsQueryValidatorTests query = query with { Path = " " }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -77,9 +76,9 @@ public class CheckPathExistsQueryValidatorTests query = query with { Path = "/valid/path" }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Path); + result.ShouldNotHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs index 4479503b..cf4e7044 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs @@ -8,6 +8,7 @@ using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPat using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -33,12 +34,15 @@ public class GetPathParentQueryHandlerTests { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockPathService = Substitute.For(); - _sut = new GetPathParentQueryHandler(_mockPathService); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new GetPathParentQueryHandler(_mockPathService, mockValidator); _pathSegmentFixture = new PathSegmentFixture(); } [Fact] - public async Task Handle_WhenCalledWithValidQuery_ShouldReturnSuccessResult() + public async Task HandleAsync_WhenCalledWithValidQuery_ShouldReturnSuccessResult() { // Arrange GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery(); @@ -52,7 +56,7 @@ public class GetPathParentQueryHandlerTests .Returns(ErrorOrFactory.From(pathSegments)); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -62,7 +66,7 @@ public class GetPathParentQueryHandlerTests } [Fact] - public async Task Handle_WhenPathServiceReturnsError_ShouldReturnFailureResult() + public async Task HandleAsync_WhenPathServiceReturnsError_ShouldReturnFailureResult() { // Arrange GetPathParentQuery query = _fixture.Create(); @@ -71,7 +75,7 @@ public class GetPathParentQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -80,7 +84,7 @@ public class GetPathParentQueryHandlerTests } [Fact] - public async Task Handle_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() + public async Task HandleAsync_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() { // Arrange GetPathParentQuery query = _fixture.Create(); @@ -89,7 +93,7 @@ public class GetPathParentQueryHandlerTests .Returns(emptyList); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs index 0a636c0a..10685253 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent.Fixtures; using Lumina.Domain.SharedKernel.Common.Errors; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -32,11 +34,10 @@ public class GetPathParentQueryValidatorTests query = query with { Path = null! }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -47,11 +48,10 @@ public class GetPathParentQueryValidatorTests query = query with { Path = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -62,11 +62,10 @@ public class GetPathParentQueryValidatorTests query = query with { Path = " " }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -77,9 +76,9 @@ public class GetPathParentQueryValidatorTests query = query with { Path = "/valid/path" }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Path); + result.ShouldNotHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs index 2ab560bb..1fb38b59 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPat using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; @@ -30,12 +31,15 @@ public class GetPathRootQueryHandlerTests public GetPathRootQueryHandlerTests() { _mockPathService = Substitute.For(); - _sut = new GetPathRootQueryHandler(_mockPathService); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new GetPathRootQueryHandler(_mockPathService, mockValidator); _pathSegmentFixture = new PathSegmentFixture(); } [Fact] - public async Task Handle_WhenCalledWithValidQuery_ShouldReturnSuccessResult() + public async Task HandleAsync_WhenCalledWithValidQuery_ShouldReturnSuccessResult() { // Arrange GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); @@ -45,7 +49,7 @@ public class GetPathRootQueryHandlerTests .Returns(ErrorOrFactory.From(pathSegment)); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -55,7 +59,7 @@ public class GetPathRootQueryHandlerTests } [Fact] - public async Task Handle_WhenPathServiceReturnsError_ShouldReturnFailureResult() + public async Task HandleAsync_WhenPathServiceReturnsError_ShouldReturnFailureResult() { // Arrange GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); @@ -64,7 +68,7 @@ public class GetPathRootQueryHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -73,7 +77,7 @@ public class GetPathRootQueryHandlerTests } [Fact] - public async Task Handle_WhenPathServiceReturnsRootPathSegment_ShouldReturnRootSuccessResult() + public async Task HandleAsync_WhenPathServiceReturnsRootPathSegment_ShouldReturnRootSuccessResult() { // Arrange GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); @@ -83,7 +87,7 @@ public class GetPathRootQueryHandlerTests .Returns(ErrorOrFactory.From(rootPathSegment)); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs index 8971c254..96db357c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot.Fixtures; using Lumina.Domain.SharedKernel.Common.Errors; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -32,11 +34,10 @@ public class GetPathRootQueryValidatorTests query = query with { Path = null! }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -47,11 +48,10 @@ public class GetPathRootQueryValidatorTests query = query with { Path = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -62,11 +62,10 @@ public class GetPathRootQueryValidatorTests query = query with { Path = " " }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -77,9 +76,9 @@ public class GetPathRootQueryValidatorTests query = query with { Path = "/valid/path" }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Path); + result.ShouldNotHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs index 53e1bbf9..e7cfaf36 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs @@ -30,7 +30,7 @@ public class GetPathSeparatorQueryHandlerTests } [Fact] - public async Task Handle_WhenCalled_ShouldReturnPathSeparatorResponse() + public async Task HandleAsync_WhenCalled_ShouldReturnPathSeparatorResponse() { // Arrange GetPathSeparatorQuery query = new(); @@ -38,7 +38,7 @@ public class GetPathSeparatorQueryHandlerTests _mockPathService.PathSeparator.Returns(expectedSeparator); // Act - PathSeparatorResponse result = await _sut.Handle(query, CancellationToken.None); + PathSeparatorResponse result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.NotNull(result); @@ -57,7 +57,7 @@ public class GetPathSeparatorQueryHandlerTests _mockPathService.PathSeparator.Returns(separator); // Act - PathSeparatorResponse result = await _sut.Handle(query, CancellationToken.None); + PathSeparatorResponse result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.NotNull(result); @@ -66,7 +66,7 @@ public class GetPathSeparatorQueryHandlerTests } [Fact] - public async Task Handle_WhenCalledMultipleTimes_ShouldReturnSameResult() + public async Task HandleAsync_WhenCalledMultipleTimes_ShouldReturnSameResult() { // Arrange GetPathSeparatorQuery query = new(); @@ -74,8 +74,8 @@ public class GetPathSeparatorQueryHandlerTests _mockPathService.PathSeparator.Returns(expectedSeparator); // Act - PathSeparatorResponse result1 = await _sut.Handle(query, CancellationToken.None); - PathSeparatorResponse result2 = await _sut.Handle(query, CancellationToken.None); + PathSeparatorResponse result1 = await _sut.HandleAsync(query, CancellationToken.None); + PathSeparatorResponse result2 = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.Equal(result1, result2); @@ -91,7 +91,7 @@ public class GetPathSeparatorQueryHandlerTests // Act Exception? exception = await Record.ExceptionAsync( - async () => await _sut.Handle(query, cts.Token) + async () => await _sut.HandleAsync(query, cts.Token) ); // Assert diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs index e7178926..dd62b385 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs @@ -1,9 +1,13 @@ #region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.SharedKernel.Common.Errors; using NSubstitute; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -18,6 +22,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.Va public class ValidatePathQueryHandlerTests { private readonly IPathService _mockPathService; + private readonly IValidator _mockValidator; private readonly ValidatePathQueryHandler _sut; /// @@ -26,66 +31,90 @@ public class ValidatePathQueryHandlerTests public ValidatePathQueryHandlerTests() { _mockPathService = Substitute.For(); - _sut = new ValidatePathQueryHandler(_mockPathService); + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new ValidatePathQueryHandler(_mockPathService, _mockValidator); } [Fact] - public async Task Handle_WhenCalledWithValidPath_ShouldReturnTrueResponse() + public async Task HandleAsync_WhenCalledWithValidPath_ShouldReturnTrueResponse() { // Arrange ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); _mockPathService.IsValidPath(query.Path!).Returns(true); // Act - PathValidResponse result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsValid); + Assert.False(result.IsError); + Assert.True(result.Value.IsValid); _mockPathService.Received(1).IsValidPath(query.Path!); } [Fact] - public async Task Handle_WhenCalledWithInvalidPath_ShouldReturnFalseResponse() + public async Task HandleAsync_WhenCalledWithInvalidPath_ShouldReturnFalseResponse() { // Arrange ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); _mockPathService.IsValidPath(query.Path!).Returns(false); // Act - PathValidResponse result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsValid); + Assert.False(result.IsError); + Assert.False(result.Value.IsValid); _mockPathService.Received(1).IsValidPath(query.Path!); } [Fact] - public async Task Handle_WhenCalledWithNullPath_ShouldReturnFalseResponse() + public async Task HandleAsync_WhenCalledWithNullPath_ShouldReturnFalseResponse() { // Arrange ValidatePathQuery query = new(null!); _mockPathService.IsValidPath(Arg.Any()).Returns(false); // Act - PathValidResponse result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsValid); + Assert.False(result.IsError); + Assert.False(result.Value.IsValid); _mockPathService.Received(1).IsValidPath(Arg.Any()); } [Fact] - public async Task Handle_WhenCalledWithEmptyPath_ShouldReturnFalseResponse() + public async Task HandleAsync_WhenCalledWithEmptyPath_ShouldReturnFalseResponse() { // Arrange ValidatePathQuery query = new(string.Empty); _mockPathService.IsValidPath(Arg.Any()).Returns(false); // Act - PathValidResponse result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsValid); + Assert.False(result.IsError); + Assert.False(result.Value.IsValid); _mockPathService.Received(1).IsValidPath(Arg.Any()); } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnValidationErrorsWithoutCallingPathService() + { + // Arrange + ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); + _mockValidator.Validate(query) + .Returns([Errors.FileSystemManagement.PathCannotBeEmpty]); + + // Act + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsError); + Assert.Equal(Errors.FileSystemManagement.PathCannotBeEmpty, result.FirstError); + _mockPathService.DidNotReceive().IsValidPath(Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs index cadbb61e..72cce88c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures; using Lumina.Domain.SharedKernel.Common.Errors; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -32,11 +34,10 @@ public class ValidatePathQueryValidatorTests query = query with { Path = null! }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -47,11 +48,10 @@ public class ValidatePathQueryValidatorTests query = query with { Path = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -62,11 +62,10 @@ public class ValidatePathQueryValidatorTests query = query with { Path = " " }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -77,9 +76,9 @@ public class ValidatePathQueryValidatorTests query = query with { Path = "/valid/path" }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Path); + result.ShouldNotHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs index 3de8062b..b0015000 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbna using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; @@ -28,11 +29,14 @@ public class GetThumbnailQueryHandlerTests { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockThumbnailService = Substitute.For(); - _sut = new GetThumbnailQueryHandler(_mockThumbnailService); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new GetThumbnailQueryHandler(_mockThumbnailService, mockValidator); } [Fact] - public async Task Handle_WhenCalledWithValidQuery_ShouldReturnSuccessResult() + public async Task HandleAsync_WhenCalledWithValidQuery_ShouldReturnSuccessResult() { // Arrange GetThumbnailQuery query = _fixture.Create(); @@ -42,7 +46,7 @@ public class GetThumbnailQueryHandlerTests .Returns(ErrorOrFactory.From(thumbnail)); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -53,7 +57,7 @@ public class GetThumbnailQueryHandlerTests } [Fact] - public async Task Handle_WhenThumbnailServiceReturnsError_ShouldReturnFailureResult() + public async Task HandleAsync_WhenThumbnailServiceReturnsError_ShouldReturnFailureResult() { // Arrange GetThumbnailQuery query = _fixture.Create(); @@ -62,7 +66,7 @@ public class GetThumbnailQueryHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -71,7 +75,7 @@ public class GetThumbnailQueryHandlerTests } [Fact] - public async Task Handle_WhenCancellationRequested_ShouldCancelOperation() + public async Task HandleAsync_WhenCancellationRequested_ShouldCancelOperation() { // Arrange GetThumbnailQuery query = _fixture.Create(); @@ -82,7 +86,7 @@ public class GetThumbnailQueryHandlerTests .Returns(Task.FromCanceled>(cts.Token)); // Act & Assert - await Assert.ThrowsAsync(() => _sut.Handle(query, cts.Token).AsTask()); + await Assert.ThrowsAsync(() => _sut.HandleAsync(query, cts.Token)); await _mockThumbnailService.Received(1).GetThumbnailAsync(query.Path!, query.Quality, cts.Token); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs index b71ddf03..87668442 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs @@ -1,7 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.SharedKernel.Common.Errors; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -30,10 +32,10 @@ public class GetThumbnailQueryValidatorTests GetThumbnailQuery query = new(null!, 1); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path).WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -43,10 +45,10 @@ public class GetThumbnailQueryValidatorTests GetThumbnailQuery query = new(string.Empty, 1); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path).WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -56,10 +58,10 @@ public class GetThumbnailQueryValidatorTests GetThumbnailQuery query = new("test", 1); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Path); + result.ShouldNotHaveValidationError(Errors.FileSystemManagement.PathCannotBeEmpty); } [Fact] @@ -69,10 +71,10 @@ public class GetThumbnailQueryValidatorTests GetThumbnailQuery query = new("test", -1); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Quality).WithErrorMessage(Errors.Thumbnails.ImageQualityMustBeBetweenZeroAndOneHundred.Description); + result.ShouldHaveValidationError(Errors.Thumbnails.ImageQualityMustBeBetweenZeroAndOneHundred); } [Fact] @@ -82,10 +84,10 @@ public class GetThumbnailQueryValidatorTests GetThumbnailQuery query = new("test", 101); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Quality).WithErrorMessage(Errors.Thumbnails.ImageQualityMustBeBetweenZeroAndOneHundred.Description); + result.ShouldHaveValidationError(Errors.Thumbnails.ImageQualityMustBeBetweenZeroAndOneHundred); } [Fact] @@ -95,10 +97,10 @@ public class GetThumbnailQueryValidatorTests GetThumbnailQuery query = new("test", 1); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Quality); + result.ShouldNotHaveValidationError(Errors.Thumbnails.ImageQualityMustBeBetweenZeroAndOneHundred); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs index d1961244..62bf4ee3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs @@ -8,6 +8,7 @@ using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures; @@ -53,6 +54,9 @@ public class SetupApplicationCommandHandlerTests _mockDateTimeProvider = Substitute.For(); _mockDataSeedService = Substitute.For(); _setupApplicationCommandFixture = new SetupApplicationCommandFixture(); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); _mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow); @@ -64,11 +68,12 @@ public class SetupApplicationCommandHandlerTests _mockTotpTokenGenerator, _mockQRCodeGenerator, _mockDateTimeProvider, - _mockDataSeedService); + _mockDataSeedService, + mockValidator); } [Fact] - public async Task Handle_WhenNoExistingUsers_ShouldCreateAdminUserWithout2FA() + public async Task HandleAsync_WhenNoExistingUsers_ShouldCreateAdminUserWithout2FA() { // Arrange SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand() with { Use2fa = false }; @@ -82,7 +87,7 @@ public class SetupApplicationCommandHandlerTests .Returns(Result.Created); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -96,7 +101,7 @@ public class SetupApplicationCommandHandlerTests } [Fact] - public async Task Handle_WhenNoExistingUsersAndWith2FA_ShouldCreateAdminUserWithTOTP() + public async Task HandleAsync_WhenNoExistingUsersAndWith2FA_ShouldCreateAdminUserWithTOTP() { // Arrange SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand() with { Use2fa = true }; @@ -119,7 +124,7 @@ public class SetupApplicationCommandHandlerTests .Returns(Result.Created); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -133,7 +138,7 @@ public class SetupApplicationCommandHandlerTests } [Fact] - public async Task Handle_WhenUserAlreadyExists_ShouldReturnError() + public async Task HandleAsync_WhenUserAlreadyExists_ShouldReturnError() { // Arrange SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); @@ -143,7 +148,7 @@ public class SetupApplicationCommandHandlerTests .Returns(new[] { existingUser }); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -155,7 +160,7 @@ public class SetupApplicationCommandHandlerTests } [Fact] - public async Task Handle_WhenGetAllUsersReturnsError_ShouldReturnError() + public async Task HandleAsync_WhenGetAllUsersReturnsError_ShouldReturnError() { // Arrange SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); @@ -165,7 +170,7 @@ public class SetupApplicationCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -177,7 +182,7 @@ public class SetupApplicationCommandHandlerTests } [Fact] - public async Task Handle_WhenInsertUserReturnsError_ShouldReturnError() + public async Task HandleAsync_WhenInsertUserReturnsError_ShouldReturnError() { // Arrange SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); @@ -189,7 +194,7 @@ public class SetupApplicationCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -201,7 +206,7 @@ public class SetupApplicationCommandHandlerTests } [Fact] - public async Task Handle_WhenSetDefaultAuthorizationPermissionsFails_ShouldReturnError() + public async Task HandleAsync_WhenSetDefaultAuthorizationPermissionsFails_ShouldReturnError() { // Arrange SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); @@ -215,7 +220,7 @@ public class SetupApplicationCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -226,7 +231,7 @@ public class SetupApplicationCommandHandlerTests } [Fact] - public async Task Handle_WhenSetDefaultAuthorizationRolesFails_ShouldReturnError() + public async Task HandleAsync_WhenSetDefaultAuthorizationRolesFails_ShouldReturnError() { // Arrange SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); @@ -242,7 +247,7 @@ public class SetupApplicationCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -254,7 +259,7 @@ public class SetupApplicationCommandHandlerTests } [Fact] - public async Task Handle_WhenSetAdminRolePermissionsFails_ShouldReturnError() + public async Task HandleAsync_WhenSetAdminRolePermissionsFails_ShouldReturnError() { // Arrange SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); @@ -272,7 +277,7 @@ public class SetupApplicationCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -285,7 +290,7 @@ public class SetupApplicationCommandHandlerTests } [Fact] - public async Task Handle_WhenSetAdminRoleToAdministratorAccountFails_ShouldReturnError() + public async Task HandleAsync_WhenSetAdminRoleToAdministratorAccountFails_ShouldReturnError() { // Arrange SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); @@ -305,7 +310,7 @@ public class SetupApplicationCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -318,7 +323,7 @@ public class SetupApplicationCommandHandlerTests } [Fact] - public async Task Handle_WhenAllOperationsSucceed_ShouldReturnSuccessResponse() + public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccessResponse() { // Arrange SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); @@ -337,7 +342,7 @@ public class SetupApplicationCommandHandlerTests .Returns(Result.Created); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs index d0752370..362ed891 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -34,11 +36,10 @@ public class SetupApplicationCommandValidatorTests command = command with { Username = null }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); } [Fact] @@ -49,11 +50,10 @@ public class SetupApplicationCommandValidatorTests command = command with { Username = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); } [Fact] @@ -64,11 +64,10 @@ public class SetupApplicationCommandValidatorTests command = command with { Username = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); } [Fact] @@ -79,11 +78,10 @@ public class SetupApplicationCommandValidatorTests command = command with { Password = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Password) - .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordCannotBeEmpty); } [Fact] @@ -94,11 +92,10 @@ public class SetupApplicationCommandValidatorTests command = command with { Password = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Password) - .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordCannotBeEmpty); } [Fact] @@ -109,11 +106,10 @@ public class SetupApplicationCommandValidatorTests command = command with { Password = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Password) - .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordCannotBeEmpty); } [Fact] @@ -124,11 +120,10 @@ public class SetupApplicationCommandValidatorTests command = command with { PasswordConfirm = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm) - .WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordConfirmCannotBeEmpty); } [Fact] @@ -139,11 +134,10 @@ public class SetupApplicationCommandValidatorTests command = command with { PasswordConfirm = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm) - .WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordConfirmCannotBeEmpty); } [Fact] @@ -154,11 +148,10 @@ public class SetupApplicationCommandValidatorTests command = command with { PasswordConfirm = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm) - .WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordConfirmCannotBeEmpty); } [Fact] @@ -169,11 +162,10 @@ public class SetupApplicationCommandValidatorTests command = command with { PasswordConfirm = "$321Bcda" }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Password) - .WithErrorMessage(Errors.Authentication.PasswordsNotMatch.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordsNotMatch); } [Theory] @@ -190,11 +182,10 @@ public class SetupApplicationCommandValidatorTests command = command with { Password = password, PasswordConfirm = password }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Password) - .WithErrorMessage(Errors.Authentication.InvalidPassword.Description); + result.ShouldHaveValidationError(Errors.Authentication.InvalidPassword); } [Theory] @@ -209,10 +200,10 @@ public class SetupApplicationCommandValidatorTests command = command with { Password = password, PasswordConfirm = password }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Password); + result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword); } [Fact] @@ -223,11 +214,11 @@ public class SetupApplicationCommandValidatorTests command = command with { Password = "$321Bcda", PasswordConfirm = "$321Bcda" }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Username); - result.ShouldNotHaveValidationErrorFor(x => x.Password); - result.ShouldNotHaveValidationErrorFor(x => x.PasswordConfirm); + result.ShouldNotHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword); + result.ShouldNotHaveValidationError(Errors.Authentication.PasswordConfirmCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs index 3f5bac9e..3dde8b07 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs @@ -40,7 +40,7 @@ public class CheckInitializationQueryHandlerTests } [Fact] - public async Task Handle_WhenUsersExist_ShouldReturnInitialized() + public async Task HandleAsync_WhenUsersExist_ShouldReturnInitialized() { // Arrange List users = UserEntityFixture.CreateMany(); @@ -48,7 +48,7 @@ public class CheckInitializationQueryHandlerTests .Returns(ErrorOrFactory.From(users.AsEnumerable())); // Act - InitializationResponse result = await _sut.Handle(new CheckInitializationQuery(), CancellationToken.None); + InitializationResponse result = await _sut.HandleAsync(new CheckInitializationQuery(), CancellationToken.None); // Assert Assert.True(result.IsInitialized); @@ -56,14 +56,14 @@ public class CheckInitializationQueryHandlerTests } [Fact] - public async Task Handle_WhenNoUsersExist_ShouldReturnNotInitialized() + public async Task HandleAsync_WhenNoUsersExist_ShouldReturnNotInitialized() { // Arrange _mockUserRepository.GetAllAsync(Arg.Any()) .Returns(ErrorOrFactory.From(Enumerable.Empty())); // Act - InitializationResponse result = await _sut.Handle(new CheckInitializationQuery(), CancellationToken.None); + InitializationResponse result = await _sut.HandleAsync(new CheckInitializationQuery(), CancellationToken.None); // Assert Assert.False(result.IsInitialized); @@ -71,7 +71,7 @@ public class CheckInitializationQueryHandlerTests } [Fact] - public async Task Handle_WhenRepositoryReturnsError_ShouldReturnNotInitialized() + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnNotInitialized() { // Arrange Error error = Error.Failure("Database.Error", "Failed to retrieve users"); @@ -79,7 +79,7 @@ public class CheckInitializationQueryHandlerTests .Returns(error); // Act - InitializationResponse result = await _sut.Handle(new CheckInitializationQuery(), CancellationToken.None); + InitializationResponse result = await _sut.HandleAsync(new CheckInitializationQuery(), CancellationToken.None); // Assert Assert.False(result.IsInitialized); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs index 7b2cbdb4..d667c227 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs @@ -5,6 +5,7 @@ using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; @@ -48,12 +49,15 @@ public class AddBookCommandHandlerTests _mockUnitOfWork.GetRepository().Returns(_mockBookRepository); - _sut = new AddBookCommandHandler(_mockUnitOfWork); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new AddBookCommandHandler(_mockUnitOfWork, mockValidator); _commandBookFixture = new AddBookCommandFixture(); } [Fact] - public async Task Handle_WhenCalledWithValidCommand_ShouldReturnSuccessResult() + public async Task HandleAsync_WhenCalledWithValidCommand_ShouldReturnSuccessResult() { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); @@ -62,7 +66,7 @@ public class AddBookCommandHandlerTests .Returns(Result.Created); // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -72,7 +76,7 @@ public class AddBookCommandHandlerTests } [Fact] - public async Task Handle_WhenRepositoryInsertFails_ShouldReturnFailureResult() + public async Task HandleAsync_WhenRepositoryInsertFails_ShouldReturnFailureResult() { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); @@ -81,7 +85,7 @@ public class AddBookCommandHandlerTests .Returns(Errors.WrittenContent.BookAlreadyExists); // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -91,14 +95,14 @@ public class AddBookCommandHandlerTests } [Fact] - public async Task Handle_WhenCalledWithInvalidISBN_ShouldReturnFailureResult() + public async Task HandleAsync_WhenCalledWithInvalidISBN_ShouldReturnFailureResult() { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { ISBNs = [new IsbnDto("invalid", IsbnFormat.Isbn13)] }; // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -108,14 +112,14 @@ public class AddBookCommandHandlerTests } [Fact] - public async Task Handle_WhenCalledWithInvalidRating_ShouldReturnFailureResult() + public async Task HandleAsync_WhenCalledWithInvalidRating_ShouldReturnFailureResult() { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Ratings = [new BookRatingDto(-1, 5, null, null)] }; // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -125,7 +129,7 @@ public class AddBookCommandHandlerTests } [Fact] - public async Task Handle_WhenGenreCreationFails_ShouldReturnFailureResult() + public async Task HandleAsync_WhenGenreCreationFails_ShouldReturnFailureResult() { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); @@ -138,7 +142,7 @@ public class AddBookCommandHandlerTests }; // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -148,7 +152,7 @@ public class AddBookCommandHandlerTests } [Fact] - public async Task Handle_WhenTagCreationFails_ShouldReturnFailureResult() + public async Task HandleAsync_WhenTagCreationFails_ShouldReturnFailureResult() { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); @@ -161,7 +165,7 @@ public class AddBookCommandHandlerTests }; // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -171,7 +175,7 @@ public class AddBookCommandHandlerTests } [Fact] - public async Task Handle_WhenReleaseInfoCreationFails_ShouldReturnFailureResult() + public async Task HandleAsync_WhenReleaseInfoCreationFails_ShouldReturnFailureResult() { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); @@ -191,7 +195,7 @@ public class AddBookCommandHandlerTests }; // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -201,7 +205,7 @@ public class AddBookCommandHandlerTests } [Fact] - public async Task Handle_WhenLanguageInfoCreationFails_ShouldReturnFailureResult() + public async Task HandleAsync_WhenLanguageInfoCreationFails_ShouldReturnFailureResult() { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); @@ -214,7 +218,7 @@ public class AddBookCommandHandlerTests }; // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -224,7 +228,7 @@ public class AddBookCommandHandlerTests } [Fact] - public async Task Handle_WhenOriginalLanguageInfoCreationFails_ShouldReturnFailureResult() + public async Task HandleAsync_WhenOriginalLanguageInfoCreationFails_ShouldReturnFailureResult() { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); @@ -237,7 +241,7 @@ public class AddBookCommandHandlerTests }; // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert Assert.True(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs index 98c78110..c08354e8 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs @@ -1,11 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Errors; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion @@ -38,10 +40,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Title = null! } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.Title).WithErrorMessage(Errors.Metadata.TitleCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); } [Fact] @@ -52,10 +54,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Title = new Faker().Random.String2(300) } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.Title).WithErrorMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description); + result.ShouldHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); } [Fact] @@ -66,10 +68,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Title = new Faker().Random.String2(200) } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Title); + result.ShouldNotHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); } [Fact] @@ -80,10 +82,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalTitle = new Faker().Random.String2(300) } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.OriginalTitle).WithErrorMessage(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong.Description); + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); } [Fact] @@ -94,10 +96,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalTitle = new Faker().Random.String2(200) } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.OriginalTitle); + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); } [Fact] @@ -108,10 +110,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalTitle = null! } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.OriginalTitle); + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); } [Fact] @@ -122,10 +124,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = new Faker().Random.String2(2001) } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.Description).WithErrorMessage(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong.Description); + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); } [Fact] @@ -136,10 +138,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = new Faker().Random.String2(1500) } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Description); + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); } [Fact] @@ -150,10 +152,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = null! } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Description); + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); } [Fact] @@ -164,10 +166,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = string.Empty } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Description); + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); } [Fact] @@ -178,10 +180,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = null! } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo).WithErrorMessage(Errors.Metadata.ReleaseInfoCannotBeNull.Description); + result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); } [Fact] @@ -192,10 +194,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseDate = null!, OriginalReleaseYear = new Faker().Random.Int(2000, 2005), ReReleaseYear = new Faker().Random.Int(2005, 2010), ReReleaseDate = null! } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.OriginalReleaseYear); + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); } [Fact] @@ -206,10 +208,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 0 } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.OriginalReleaseYear).WithErrorMessage(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Description); + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); } [Fact] @@ -220,10 +222,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 10000 } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.OriginalReleaseYear).WithErrorMessage(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Description); + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); } [Fact] @@ -242,10 +244,10 @@ public class AddBookCommandValidatorTests }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReReleaseYear); + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); } [Fact] @@ -256,10 +258,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReReleaseYear = 0 } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReReleaseYear).WithErrorMessage(Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Description); + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); } [Fact] @@ -270,10 +272,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReReleaseYear = 10000 } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReReleaseYear).WithErrorMessage(Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Description); + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); } [Fact] @@ -284,10 +286,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseCountry = new Faker().Random.String2(2).ToUpper() } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReleaseCountry); + result.ShouldNotHaveValidationError(Errors.Metadata.CountryCodeMustBe2CharactersLong); } [Fact] @@ -298,10 +300,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseCountry = new Faker().Random.String2(3) } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReleaseCountry).WithErrorMessage(Errors.Metadata.CountryCodeMustBe2CharactersLong.Description); + result.ShouldHaveValidationError(Errors.Metadata.CountryCodeMustBe2CharactersLong); } [Fact] @@ -312,10 +314,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseVersion = new Faker().Random.String2(50) } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReleaseVersion); + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); } [Fact] @@ -326,10 +328,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseVersion = new Faker().Random.String2(51) } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReleaseVersion).WithErrorMessage(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong.Description); + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); } [Fact] @@ -340,10 +342,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 2000, ReReleaseYear = 2001, ReReleaseDate = null! } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReReleaseYear); + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); } [Fact] @@ -354,10 +356,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 2001, ReReleaseYear = 2000, ReReleaseDate = null! } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReReleaseYear).WithErrorMessage(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear.Description); + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); } [Fact] @@ -368,10 +370,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseDate = new DateOnly(2000, 1, 1), ReReleaseDate = new DateOnly(2001, 1, 1) } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReReleaseDate); + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); } [Fact] @@ -382,10 +384,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseDate = new DateOnly(2001, 1, 1), ReReleaseDate = new DateOnly(2000, 1, 1) } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReReleaseDate).WithErrorMessage(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description); + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); } [Fact] @@ -396,10 +398,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = null! } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.Genres).WithErrorMessage(Errors.Metadata.GenresListCannotBeNull.Description); + result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); } [Fact] @@ -410,10 +412,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = bookCommand.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = string.Empty } : genre).ToList() } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Metadata.Genres[0].Name").WithErrorMessage(Errors.Metadata.GenreNameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); } [Fact] @@ -424,10 +426,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = bookCommand.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = new Faker().Random.String2(51) } : genre).ToList() } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Metadata.Genres[0].Name").WithErrorMessage(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong.Description); + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); } [Fact] @@ -444,10 +446,10 @@ public class AddBookCommandValidatorTests }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Genres); + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); } [Fact] @@ -458,10 +460,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = null! } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.Tags).WithErrorMessage(Errors.Metadata.TagsListCannotBeNull.Description); + result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); } [Fact] @@ -472,10 +474,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = bookCommand.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = string.Empty } : tag).ToList() } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Metadata.Tags[0].Name").WithErrorMessage(Errors.Metadata.TagNameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); } [Fact] @@ -486,10 +488,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = bookCommand.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = new Faker().Random.String2(51) } : tag).ToList() } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Metadata.Tags[0].Name").WithErrorMessage(Errors.Metadata.TagNameMustBeMaximum50CharactersLong.Description); + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); } [Fact] @@ -506,10 +508,10 @@ public class AddBookCommandValidatorTests }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Tags); + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); } [Fact] @@ -520,10 +522,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = null! } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Language); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); } [Fact] @@ -534,10 +536,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageCode = string.Empty } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.Language!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); } [Fact] @@ -548,10 +550,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageCode = new Faker().Random.String2(3) } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.Language!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description); + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); } [Fact] @@ -562,10 +564,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageName = string.Empty } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.Language!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); } [Fact] @@ -576,10 +578,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageName = new Faker().Random.String2(51) } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.Language!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description); + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); } [Fact] @@ -590,10 +592,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { NativeName = null! } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Language!.NativeName); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); } [Fact] @@ -604,10 +606,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { NativeName = new Faker().Random.String2(51) } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.Language!.NativeName).WithErrorMessage(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description); + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); } [Fact] @@ -618,10 +620,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = null! } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.OriginalLanguage); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); } [Fact] @@ -632,10 +634,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageCode = string.Empty } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.OriginalLanguage!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); } [Fact] @@ -646,10 +648,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageCode = new Faker().Random.String2(3) } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.OriginalLanguage!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description); + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); } [Fact] @@ -660,10 +662,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageName = string.Empty } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.OriginalLanguage!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); } [Fact] @@ -674,10 +676,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageName = new Faker().Random.String2(51) } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.OriginalLanguage!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description); + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); } [Fact] @@ -688,10 +690,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { NativeName = null! } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.OriginalLanguage!.NativeName); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); } [Fact] @@ -702,10 +704,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { NativeName = new Faker().Random.String2(51) } } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.OriginalLanguage!.NativeName).WithErrorMessage(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description); + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); } [Fact] @@ -716,10 +718,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Publisher = null! } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Publisher); + result.ShouldNotHaveValidationError(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong); } [Fact] @@ -730,10 +732,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Publisher = new Faker().Random.String2(100) } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Publisher); + result.ShouldNotHaveValidationError(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong); } [Fact] @@ -744,10 +746,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Publisher = new Faker().Random.String2(101) } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.Publisher).WithErrorMessage(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong); } [Fact] @@ -758,10 +760,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = null } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.PageCount); + result.ShouldNotHaveValidationError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); } [Fact] @@ -772,10 +774,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = 0 } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.PageCount).WithErrorMessage(Errors.WrittenContent.PageCountMustBeGreaterThanZero.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); } [Fact] @@ -786,10 +788,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = -1 } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata!.PageCount).WithErrorMessage(Errors.WrittenContent.PageCountMustBeGreaterThanZero.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); } [Fact] @@ -800,10 +802,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = 100 } }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.PageCount); + result.ShouldNotHaveValidationError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); } [Fact] @@ -814,10 +816,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Format = null }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Format); + result.ShouldNotHaveValidationError(Errors.WrittenContent.UnknownBookFormat); } [Fact] @@ -828,10 +830,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Format = BookFormat.Hardcover }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Format); + result.ShouldNotHaveValidationError(Errors.WrittenContent.UnknownBookFormat); } [Fact] @@ -842,10 +844,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Format = (BookFormat)99 }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Format).WithErrorMessage(Errors.WrittenContent.UnknownBookFormat.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.UnknownBookFormat); } [Fact] @@ -856,10 +858,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Edition = null }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Edition); + result.ShouldNotHaveValidationError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong); } [Fact] @@ -870,10 +872,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Edition = new Faker().Random.String2(50) }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Edition); + result.ShouldNotHaveValidationError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong); } [Fact] @@ -884,10 +886,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Edition = new Faker().Random.String2(51) }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Edition).WithErrorMessage(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong); } [Fact] @@ -898,10 +900,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { VolumeNumber = null }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.VolumeNumber); + result.ShouldNotHaveValidationError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); } [Fact] @@ -912,10 +914,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { VolumeNumber = 0 }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.VolumeNumber).WithErrorMessage(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); } [Fact] @@ -926,10 +928,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { VolumeNumber = -1 }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.VolumeNumber).WithErrorMessage(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); } [Fact] @@ -940,10 +942,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { VolumeNumber = 1 }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.VolumeNumber); + result.ShouldNotHaveValidationError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); } [Fact] @@ -954,10 +956,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Series = null }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Series); + result.ShouldNotHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); } //[Fact] @@ -1010,10 +1012,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { ASIN = new Faker().Random.String2(10) }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.ASIN); + result.ShouldNotHaveValidationError(Errors.WrittenContent.AsinMustBe10CharactersLong); } [Fact] @@ -1024,10 +1026,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { ASIN = null }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.ASIN); + result.ShouldNotHaveValidationError(Errors.WrittenContent.AsinMustBe10CharactersLong); } [Fact] @@ -1038,10 +1040,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { ASIN = new Faker().Random.String2(9) }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.ASIN).WithErrorMessage(Errors.WrittenContent.AsinMustBe10CharactersLong.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.AsinMustBe10CharactersLong); } [Fact] @@ -1052,10 +1054,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { GoodreadsId = null }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.GoodreadsId); + result.ShouldNotHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); } [Fact] @@ -1066,10 +1068,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { GoodreadsId = "123456789" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.GoodreadsId); + result.ShouldNotHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); } [Fact] @@ -1080,10 +1082,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { GoodreadsId = "abc123" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.GoodreadsId).WithErrorMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); } [Fact] @@ -1094,10 +1096,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { GoodreadsId = "123 456" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.GoodreadsId).WithErrorMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); } [Fact] @@ -1108,10 +1110,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { GoodreadsId = "123-456" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.GoodreadsId).WithErrorMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); } [Fact] @@ -1122,10 +1124,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { LCCN = null }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.LCCN); + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidLccnFormat); } [Fact] @@ -1136,10 +1138,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { LCCN = "n78890351" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.LCCN); + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidLccnFormat); } [Fact] @@ -1150,10 +1152,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { LCCN = "invalid123" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.LCCN).WithErrorMessage(Errors.WrittenContent.InvalidLccnFormat.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidLccnFormat); } [Fact] @@ -1164,10 +1166,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { LCCN = new Faker().Random.String2(15) }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.LCCN).WithErrorMessage(Errors.WrittenContent.InvalidLccnFormat.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidLccnFormat); } [Fact] @@ -1178,10 +1180,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { LCCN = "n12" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.LCCN).WithErrorMessage(Errors.WrittenContent.InvalidLccnFormat.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidLccnFormat); } [Fact] @@ -1192,10 +1194,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { OCLCNumber = null }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.OCLCNumber); + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); } [Fact] @@ -1206,10 +1208,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { OCLCNumber = "ocm12345678" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.OCLCNumber); + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); } [Fact] @@ -1220,10 +1222,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { OCLCNumber = "ocn123456789" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.OCLCNumber); + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); } [Fact] @@ -1234,10 +1236,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { OCLCNumber = "on1234567890" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.OCLCNumber); + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); } [Fact] @@ -1248,10 +1250,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { OCLCNumber = "(OCoLC)1234567890" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.OCLCNumber); + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); } [Fact] @@ -1262,10 +1264,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { OCLCNumber = "12345678" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.OCLCNumber); + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); } [Fact] @@ -1276,10 +1278,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { OCLCNumber = "invalid_oclc_number" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.OCLCNumber).WithErrorMessage(Errors.WrittenContent.InvalidOclcFormat.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); } [Fact] @@ -1290,10 +1292,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { OpenLibraryId = null! }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.OpenLibraryId); + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOpenLibraryId); } [Fact] @@ -1304,10 +1306,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { OpenLibraryId = "OL123456M" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.OpenLibraryId); + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOpenLibraryId); } [Fact] @@ -1318,10 +1320,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { OpenLibraryId = "InvalidID" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.OpenLibraryId).WithErrorMessage(Errors.WrittenContent.InvalidOpenLibraryId.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidOpenLibraryId); } [Fact] @@ -1332,10 +1334,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { OpenLibraryId = "OL123ABC" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.OpenLibraryId).WithErrorMessage(Errors.WrittenContent.InvalidOpenLibraryId.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidOpenLibraryId); } [Fact] @@ -1346,10 +1348,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { OpenLibraryId = "OL123456X" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.OpenLibraryId).WithErrorMessage(Errors.WrittenContent.InvalidOpenLibraryId.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidOpenLibraryId); } [Fact] @@ -1360,10 +1362,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { LibraryThingId = null }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.LibraryThingId); + result.ShouldNotHaveValidationError(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong); } [Fact] @@ -1374,10 +1376,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { LibraryThingId = new Faker().Random.String2(50) }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.LibraryThingId); + result.ShouldNotHaveValidationError(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong); } [Fact] @@ -1388,10 +1390,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { LibraryThingId = new Faker().Random.String2(51) }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.LibraryThingId).WithErrorMessage(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong); } [Fact] @@ -1402,10 +1404,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { GoogleBooksId = null! }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.GoogleBooksId); + result.ShouldNotHaveValidationError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong); } [Fact] @@ -1416,10 +1418,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { GoogleBooksId = new Faker().Random.String2(11) }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.GoogleBooksId).WithErrorMessage(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong); } [Fact] @@ -1430,10 +1432,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { GoogleBooksId = new Faker().Random.String2(11) + " " }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.GoogleBooksId).WithErrorMessage(Errors.WrittenContent.InvalidGoogleBooksIdFormat.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidGoogleBooksIdFormat); } [Fact] @@ -1444,10 +1446,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { GoogleBooksId = new Faker().Random.String2(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-") }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.GoogleBooksId); + result.ShouldNotHaveValidationError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong); } [Fact] @@ -1458,10 +1460,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { BarnesAndNobleId = null! }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.BarnesAndNobleId); + result.ShouldNotHaveValidationError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong); } [Fact] @@ -1472,10 +1474,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { BarnesAndNobleId = new Faker().Random.String2(11) }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.BarnesAndNobleId).WithErrorMessage(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong); } [Fact] @@ -1486,10 +1488,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { BarnesAndNobleId = new Faker().Random.AlphaNumeric(10) }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.BarnesAndNobleId).WithErrorMessage(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat); } [Fact] @@ -1500,10 +1502,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { BarnesAndNobleId = new Faker().Random.Number(1000000000, 999999999).ToString() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.BarnesAndNobleId); + result.ShouldNotHaveValidationError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong); } [Fact] @@ -1514,10 +1516,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { AppleBooksId = null }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.AppleBooksId); + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidAppleBooksIdFormat); } [Fact] @@ -1528,10 +1530,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { AppleBooksId = "id123456" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.AppleBooksId); + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidAppleBooksIdFormat); } [Fact] @@ -1542,10 +1544,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { AppleBooksId = "invalid_id" }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.AppleBooksId).WithErrorMessage(Errors.WrittenContent.InvalidAppleBooksIdFormat.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidAppleBooksIdFormat); } [Fact] @@ -1556,10 +1558,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { ISBNs = null! }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.ISBNs).WithErrorMessage(Errors.WrittenContent.IsbnListCannotBeNull.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.IsbnListCannotBeNull); } [Fact] @@ -1570,10 +1572,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = null! } : isbn).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("ISBNs[0].Value").WithErrorMessage(Errors.WrittenContent.IsbnValueCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.IsbnValueCannotBeEmpty); } [Fact] @@ -1584,10 +1586,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn10 } : isbn).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("ISBNs[0].Value").WithErrorMessage(Errors.WrittenContent.InvalidIsbn10Format.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidIsbn10Format); } [Fact] @@ -1598,10 +1600,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn13 } : isbn).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("ISBNs[0].Value").WithErrorMessage(Errors.WrittenContent.InvalidIsbn13Format.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidIsbn13Format); } [Fact] @@ -1612,10 +1614,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Format = (IsbnFormat)99 } : isbn).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("ISBNs[0].Format").WithErrorMessage(Errors.WrittenContent.UnknownIsbnFormat.Description); + result.ShouldHaveValidationError(Errors.WrittenContent.UnknownIsbnFormat); } [Fact] @@ -1626,10 +1628,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = "0-306-40615-2", Format = IsbnFormat.Isbn10 } : isbn).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.ISBNs![0].Value); + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidIsbn10Format); } [Fact] @@ -1640,10 +1642,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = "978-3-16-148410-0", Format = IsbnFormat.Isbn13 } : isbn).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.ISBNs![0].Value); + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidIsbn13Format); } [Fact] @@ -1654,10 +1656,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Contributors = null! }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Contributors).WithErrorMessage(Errors.MediaContributor.ContributorsListCannotBeNull.Description); + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); } [Fact] @@ -1668,10 +1670,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = null! } : contributor).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Name").WithErrorMessage(Errors.MediaContributor.ContributorNameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorNameCannotBeEmpty); } [Fact] @@ -1682,10 +1684,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = new Faker().Random.String2(101) } } : contributor).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Name.DisplayName").WithErrorMessage(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong.Description); + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong); } [Fact] @@ -1696,10 +1698,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = null! } } : contributor).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Name.DisplayName").WithErrorMessage(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty); } [Fact] @@ -1710,10 +1712,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { LegalName = new Faker().Random.String2(101) } } : contributor).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Name.LegalName").WithErrorMessage(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong.Description); + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong); } [Fact] @@ -1724,10 +1726,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = null! } : contributor).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Role").WithErrorMessage(Errors.MediaContributor.ContributorRoleCannotBeNull.Description); + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorRoleCannotBeNull); } [Fact] @@ -1738,10 +1740,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Name = null! } } : contributor).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Role.Name").WithErrorMessage(Errors.MediaContributor.RoleNameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.MediaContributor.RoleNameCannotBeEmpty); } [Fact] @@ -1752,10 +1754,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Name = new Faker().Random.String2(51) } } : contributor).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Role.Name").WithErrorMessage(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong.Description); + result.ShouldHaveValidationError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong); } [Fact] @@ -1766,10 +1768,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Category = null! } } : contributor).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Role.Category").WithErrorMessage(Errors.MediaContributor.RoleCategoryCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.MediaContributor.RoleCategoryCannotBeEmpty); } [Fact] @@ -1780,10 +1782,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Category = new Faker().Random.String2(51) } } : contributor).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Role.Category").WithErrorMessage(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong.Description); + result.ShouldHaveValidationError(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong); } [Fact] @@ -1794,10 +1796,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Ratings = null! }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Ratings).WithErrorMessage(Errors.Metadata.RatingsListCannotBeNull.Description); + result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); } [Fact] @@ -1808,10 +1810,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = -1 } : rating).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Ratings[0].Value").WithErrorMessage(Errors.Metadata.RatingValueMustBePositive.Description); + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); } [Fact] @@ -1822,10 +1824,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = 6, MaxValue = 5 } : rating).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Ratings[0].Value").WithErrorMessage(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Description); + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); } [Fact] @@ -1836,10 +1838,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { MaxValue = -1 } : rating).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Ratings[0].MaxValue").WithErrorMessage(Errors.Metadata.RatingMaxValueMustBePositive.Description); + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); } [Fact] @@ -1850,10 +1852,10 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = -1 } : rating).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Ratings[0].VoteCount").WithErrorMessage(Errors.Metadata.RatingVoteCountMustBePositive.Description); + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); } [Fact] @@ -1869,10 +1871,10 @@ public class AddBookCommandValidatorTests }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Ratings); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); } [Fact] @@ -1883,9 +1885,9 @@ public class AddBookCommandValidatorTests bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = null } : rating).ToList() }; // Act - TestValidationResult result = _validator.TestValidate(bookCommand); + List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Ratings![0].VoteCount); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs index a974333b..90558a6b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs @@ -3,6 +3,7 @@ using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; using Lumina.DataAccess.UnitTests.Core.Repositories.Plugins.Fixtures; using NSubstitute; @@ -31,11 +32,14 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests _mockUnitOfWork = Substitute.For(); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.GetRepository().Returns(_mockConfigurationRepository); - _sut = new ReorderLibraryMetadataProvidersCommandHandler(_mockUnitOfWork); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new ReorderLibraryMetadataProvidersCommandHandler(_mockUnitOfWork, mockValidator); } [Fact] - public async Task Handle_WhenCalled_ShouldAssignRanksInTheProvidedOrder() + public async Task HandleAsync_WhenCalled_ShouldAssignRanksInTheProvidedOrder() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -48,7 +52,7 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests .Returns(Result.Updated); // Act - ErrorOr result = await _sut.Handle(new ReorderLibraryMetadataProvidersCommand(libraryId, [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(new ReorderLibraryMetadataProvidersCommand(libraryId, [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs index 5d5d333c..3fcc7f80 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs @@ -3,6 +3,7 @@ using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; using NSubstitute; using System; @@ -30,11 +31,14 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests _mockUnitOfWork = Substitute.For(); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.GetRepository().Returns(_mockConfigurationRepository); - _sut = new SetLibraryMetadataProviderEnabledCommandHandler(_mockUnitOfWork); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new SetLibraryMetadataProviderEnabledCommandHandler(_mockUnitOfWork, mockValidator); } [Fact] - public async Task Handle_WhenConfigurationDoesNotExist_ShouldCreateEnabledConfigurationWithNextRank() + public async Task HandleAsync_WhenConfigurationDoesNotExist_ShouldCreateEnabledConfigurationWithNextRank() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -47,7 +51,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests .Returns(Result.Updated); // Act - ErrorOr result = await _sut.Handle(new SetLibraryMetadataProviderEnabledCommand(libraryId, pluginId, true), CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(libraryId, pluginId, true), CancellationToken.None); // Assert Assert.False(result.IsError); @@ -57,7 +61,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests } [Fact] - public async Task Handle_WhenConfigurationExists_ShouldUpdateItsEnabledState() + public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledState() { // Arrange LibraryMetadataProviderConfigurationEntity existingConfiguration = new() @@ -77,7 +81,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests .Returns(Result.Updated); // Act - ErrorOr result = await _sut.Handle(new SetLibraryMetadataProviderEnabledCommand(existingConfiguration.LibraryId, existingConfiguration.PluginId, true), CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(existingConfiguration.LibraryId, existingConfiguration.PluginId, true), CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs index 9cea88b4..1d83a6f3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs @@ -2,6 +2,7 @@ using ErrorOr; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; using NSubstitute; using System; @@ -29,11 +30,14 @@ public class UpdatePluginSettingsCommandHandlerTests _mockUnitOfWork = Substitute.For(); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.GetRepository().Returns(_mockPluginRepository); - _sut = new UpdatePluginSettingsCommandHandler(_mockUnitOfWork); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new UpdatePluginSettingsCommandHandler(_mockUnitOfWork, mockValidator); } [Fact] - public async Task Handle_WhenCalled_ShouldPersistTheSettings() + public async Task HandleAsync_WhenCalled_ShouldPersistTheSettings() { // Arrange Guid pluginId = Guid.NewGuid(); @@ -42,7 +46,7 @@ public class UpdatePluginSettingsCommandHandlerTests .Returns(Result.Updated); // Act - ErrorOr result = await _sut.Handle(new UpdatePluginSettingsCommand(pluginId, settings), CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(new UpdatePluginSettingsCommand(pluginId, settings), CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs index 04e96ad4..ea3c0498 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs @@ -36,7 +36,7 @@ public class GetPluginsQueryHandlerTests } [Fact] - public async Task Handle_WhenCalled_ShouldReturnAllDetectedPlugins() + public async Task HandleAsync_WhenCalled_ShouldReturnAllDetectedPlugins() { // Arrange PluginEntityFixture pluginFixture = new(); @@ -44,7 +44,7 @@ public class GetPluginsQueryHandlerTests _mockPluginRepository.GetAllAsync(Arg.Any()).Returns(plugins); // Act - ErrorOr> result = await _sut.Handle(new GetPluginsQuery(), CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(new GetPluginsQuery(), CancellationToken.None); // Assert Assert.False(result.IsError); @@ -54,14 +54,14 @@ public class GetPluginsQueryHandlerTests } [Fact] - public async Task Handle_WhenRepositoryReturnsError_ShouldReturnError() + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnError() { // Arrange _mockPluginRepository.GetAllAsync(Arg.Any()) .Returns(Error.Failure(description: "Failed to get plugins")); // Act - ErrorOr> result = await _sut.Handle(new GetPluginsQuery(), CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(new GetPluginsQuery(), CancellationToken.None); // Assert Assert.True(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs index 1c39e3cc..50e07f8d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs @@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Contracts.Responses.Authentication; @@ -39,13 +40,17 @@ public class ChangePasswordCommandHandlerTests _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); _sut = new ChangePasswordCommandHandler( _mockUnitOfWork, - _mockHashService); + _mockHashService, + mockValidator); } [Fact] - public async Task Handle_WhenPasswordChangeIsSuccessful_ShouldUpdateUserAndReturnSuccess() + public async Task HandleAsync_WhenPasswordChangeIsSuccessful_ShouldUpdateUserAndReturnSuccess() { // Arrange string currentPassword = "currentPassword"; @@ -72,7 +77,7 @@ public class ChangePasswordCommandHandlerTests .Returns(Result.Updated); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -86,7 +91,7 @@ public class ChangePasswordCommandHandlerTests } [Fact] - public async Task Handle_WhenUserDoesNotExist_ShouldReturnError() + public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnError() { // Arrange ChangePasswordCommand command = new("nonexistentUser", "oldPass", "newPass", "newPass"); @@ -95,7 +100,7 @@ public class ChangePasswordCommandHandlerTests .Returns(ErrorOrFactory.From(null)); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -107,7 +112,7 @@ public class ChangePasswordCommandHandlerTests } [Fact] - public async Task Handle_WhenCurrentPasswordIsIncorrect_ShouldReturnError() + public async Task HandleAsync_WhenCurrentPasswordIsIncorrect_ShouldReturnError() { // Arrange UserEntity user = UserEntityFixture.CreateUserEntity(); @@ -125,7 +130,7 @@ public class ChangePasswordCommandHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -138,7 +143,7 @@ public class ChangePasswordCommandHandlerTests } [Fact] - public async Task Handle_WhenUpdateFails_ShouldReturnError() + public async Task HandleAsync_WhenUpdateFails_ShouldReturnError() { // Arrange string currentPassword = "currentPassword"; @@ -163,7 +168,7 @@ public class ChangePasswordCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -176,7 +181,7 @@ public class ChangePasswordCommandHandlerTests } [Fact] - public async Task Handle_WhenGetByUsernameReturnsError_ShouldReturnError() + public async Task HandleAsync_WhenGetByUsernameReturnsError_ShouldReturnError() { // Arrange string currentPassword = "currentPassword"; @@ -193,7 +198,7 @@ public class ChangePasswordCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs index 2c272751..2bab25b2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -32,11 +34,10 @@ public class ChangePasswordCommandValidatorTests command = command with { Username = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); } [Fact] @@ -47,11 +48,10 @@ public class ChangePasswordCommandValidatorTests command = command with { Username = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); } [Fact] @@ -62,11 +62,10 @@ public class ChangePasswordCommandValidatorTests command = command with { Username = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); } [Fact] @@ -77,11 +76,10 @@ public class ChangePasswordCommandValidatorTests command = command with { CurrentPassword = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.CurrentPassword) - .WithErrorMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.CurrentPasswordCannotBeEmpty); } [Fact] @@ -92,11 +90,10 @@ public class ChangePasswordCommandValidatorTests command = command with { CurrentPassword = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.CurrentPassword) - .WithErrorMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.CurrentPasswordCannotBeEmpty); } [Fact] @@ -107,11 +104,10 @@ public class ChangePasswordCommandValidatorTests command = command with { CurrentPassword = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.CurrentPassword) - .WithErrorMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.CurrentPasswordCannotBeEmpty); } [Fact] @@ -122,11 +118,10 @@ public class ChangePasswordCommandValidatorTests command = command with { NewPassword = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.NewPassword) - .WithErrorMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.NewPasswordCannotBeEmpty); } [Fact] @@ -137,11 +132,10 @@ public class ChangePasswordCommandValidatorTests command = command with { NewPassword = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.NewPassword) - .WithErrorMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.NewPasswordCannotBeEmpty); } [Fact] @@ -152,11 +146,10 @@ public class ChangePasswordCommandValidatorTests command = command with { NewPassword = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.NewPassword) - .WithErrorMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.NewPasswordCannotBeEmpty); } [Fact] @@ -167,11 +160,10 @@ public class ChangePasswordCommandValidatorTests command = command with { NewPasswordConfirm = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.NewPasswordConfirm) - .WithErrorMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.NewPasswordConfirmCannotBeEmpty); } [Fact] @@ -182,11 +174,10 @@ public class ChangePasswordCommandValidatorTests command = command with { NewPasswordConfirm = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.NewPasswordConfirm) - .WithErrorMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.NewPasswordConfirmCannotBeEmpty); } [Fact] @@ -197,11 +188,10 @@ public class ChangePasswordCommandValidatorTests command = command with { NewPasswordConfirm = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.NewPasswordConfirm) - .WithErrorMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.NewPasswordConfirmCannotBeEmpty); } [Fact] @@ -212,11 +202,10 @@ public class ChangePasswordCommandValidatorTests command = command with { NewPasswordConfirm = "$321Bcda" }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.NewPassword) - .WithErrorMessage(Errors.Authentication.PasswordsNotMatch.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordsNotMatch); } [Theory] @@ -233,11 +222,10 @@ public class ChangePasswordCommandValidatorTests command = command with { CurrentPassword = password }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.CurrentPassword) - .WithErrorMessage(Errors.Authentication.InvalidPassword.Description); + result.ShouldHaveValidationError(Errors.Authentication.InvalidPassword); } [Theory] @@ -254,11 +242,10 @@ public class ChangePasswordCommandValidatorTests command = command with { NewPassword = password, NewPasswordConfirm = password }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.NewPassword) - .WithErrorMessage(Errors.Authentication.InvalidPassword.Description); + result.ShouldHaveValidationError(Errors.Authentication.InvalidPassword); } [Theory] @@ -278,11 +265,11 @@ public class ChangePasswordCommandValidatorTests }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.CurrentPassword); - result.ShouldNotHaveValidationErrorFor(x => x.NewPassword); + result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword); + result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword); } [Fact] @@ -292,12 +279,12 @@ public class ChangePasswordCommandValidatorTests ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Username); - result.ShouldNotHaveValidationErrorFor(x => x.CurrentPassword); - result.ShouldNotHaveValidationErrorFor(x => x.NewPassword); - result.ShouldNotHaveValidationErrorFor(x => x.NewPasswordConfirm); + result.ShouldNotHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword); + result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword); + result.ShouldNotHaveValidationError(Errors.Authentication.NewPasswordConfirmCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs index 19af929a..8e24234c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Contracts.Responses.Authentication; @@ -44,15 +45,19 @@ public class RecoverPasswordCommandHandlerTests _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); _sut = new RecoverPasswordCommandHandler( _mockUnitOfWork, _mockHashService, _mockTotpTokenGenerator, - _mockCryptographyService); + _mockCryptographyService, + mockValidator); } [Fact] - public async Task Handle_WhenUserExistsAndTotpIsValid_ShouldResetPassword() + public async Task HandleAsync_WhenUserExistsAndTotpIsValid_ShouldResetPassword() { // Arrange string totpCode = "123456"; @@ -78,7 +83,7 @@ public class RecoverPasswordCommandHandlerTests .Returns(Result.Updated); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -92,7 +97,7 @@ public class RecoverPasswordCommandHandlerTests } [Fact] - public async Task Handle_WhenUserDoesNotExist_ShouldReturnError() + public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnError() { // Arrange RecoverPasswordCommand command = new("nonexistentUser", "123456"); @@ -101,7 +106,7 @@ public class RecoverPasswordCommandHandlerTests .Returns(ErrorOrFactory.From(null)); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -113,7 +118,7 @@ public class RecoverPasswordCommandHandlerTests } [Fact] - public async Task Handle_WhenTempPasswordExists_ShouldReturnError() + public async Task HandleAsync_WhenTempPasswordExists_ShouldReturnError() { // Arrange UserEntity user = UserEntityFixture.CreateUserEntity(); @@ -126,7 +131,7 @@ public class RecoverPasswordCommandHandlerTests .Returns(ErrorOrFactory.From(user)); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -138,7 +143,7 @@ public class RecoverPasswordCommandHandlerTests } [Fact] - public async Task Handle_WhenUserDoesNotUseTOTP_ShouldReturnError() + public async Task HandleAsync_WhenUserDoesNotUseTOTP_ShouldReturnError() { // Arrange UserEntity user = UserEntityFixture.CreateUserEntity(); @@ -150,7 +155,7 @@ public class RecoverPasswordCommandHandlerTests .Returns(ErrorOrFactory.From(user)); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -162,7 +167,7 @@ public class RecoverPasswordCommandHandlerTests } [Fact] - public async Task Handle_WhenTotpCodeIsInvalid_ShouldReturnError() + public async Task HandleAsync_WhenTotpCodeIsInvalid_ShouldReturnError() { // Arrange string totpCode = "123456"; @@ -182,7 +187,7 @@ public class RecoverPasswordCommandHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -195,7 +200,7 @@ public class RecoverPasswordCommandHandlerTests } [Fact] - public async Task Handle_WhenUpdateFails_ShouldReturnError() + public async Task HandleAsync_WhenUpdateFails_ShouldReturnError() { // Arrange string totpCode = "123456"; @@ -218,7 +223,7 @@ public class RecoverPasswordCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -231,7 +236,7 @@ public class RecoverPasswordCommandHandlerTests } [Fact] - public async Task Handle_WhenGetByUsernameReturnsError_ShouldReturnError() + public async Task HandleAsync_WhenGetByUsernameReturnsError_ShouldReturnError() { // Arrange string totpCode = "123456"; @@ -247,7 +252,7 @@ public class RecoverPasswordCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -259,7 +264,7 @@ public class RecoverPasswordCommandHandlerTests } [Fact] - public async Task Handle_WhenUserUsesTOTPButNoCodeProvided_ShouldReturnError() + public async Task HandleAsync_WhenUserUsesTOTPButNoCodeProvided_ShouldReturnError() { // Arrange string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); @@ -273,7 +278,7 @@ public class RecoverPasswordCommandHandlerTests .Returns(ErrorOrFactory.From(user)); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs index 1459a1ac..500be490 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -32,11 +34,10 @@ public class RecoverPasswordCommandValidatorTests command = command with { Username = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); } [Fact] @@ -47,11 +48,10 @@ public class RecoverPasswordCommandValidatorTests command = command with { Username = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); } [Fact] @@ -62,11 +62,10 @@ public class RecoverPasswordCommandValidatorTests command = command with { Username = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); } [Fact] @@ -77,11 +76,10 @@ public class RecoverPasswordCommandValidatorTests command = command with { TotpCode = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.TotpCode) - .WithErrorMessage(Errors.Authentication.TotpCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.TotpCannotBeEmpty); } [Fact] @@ -92,11 +90,10 @@ public class RecoverPasswordCommandValidatorTests command = command with { TotpCode = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.TotpCode) - .WithErrorMessage(Errors.Authentication.TotpCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.TotpCannotBeEmpty); } [Fact] @@ -107,11 +104,10 @@ public class RecoverPasswordCommandValidatorTests command = command with { TotpCode = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.TotpCode) - .WithErrorMessage(Errors.Authentication.TotpCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.TotpCannotBeEmpty); } [Theory] @@ -128,11 +124,10 @@ public class RecoverPasswordCommandValidatorTests command = command with { TotpCode = totpCode }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.TotpCode) - .WithErrorMessage(Errors.Authentication.InvalidTotpCode.Description); + result.ShouldHaveValidationError(Errors.Authentication.InvalidTotpCode); } [Theory] @@ -146,10 +141,10 @@ public class RecoverPasswordCommandValidatorTests command = command with { TotpCode = totpCode }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.TotpCode); + result.ShouldNotHaveValidationError(Errors.Authentication.InvalidTotpCode); } [Fact] @@ -159,10 +154,10 @@ public class RecoverPasswordCommandValidatorTests RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Username); - result.ShouldNotHaveValidationErrorFor(x => x.TotpCode); + result.ShouldNotHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Authentication.TotpCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs index 2b616481..01d1f8f6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; @@ -51,17 +52,21 @@ public class RegisterUserCommandHandlerTests _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); _mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); _sut = new RegisterUserCommandHandler( _mockUnitOfWork, _mockHashService, _mockCryptographyService, _mockTotpTokenGenerator, _mockQRCodeGenerator, - _mockDateTimeProvider); + _mockDateTimeProvider, + mockValidator); } [Fact] - public async Task Handle_WhenUserDoesNotExistAndWith2FA_ShouldRegisterUser() + public async Task HandleAsync_WhenUserDoesNotExistAndWith2FA_ShouldRegisterUser() { // Arrange RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); @@ -84,7 +89,7 @@ public class RegisterUserCommandHandlerTests .Returns(Result.Created); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -101,7 +106,7 @@ public class RegisterUserCommandHandlerTests } [Fact] - public async Task Handle_WhenUserDoesNotExistAndWithout2FA_ShouldRegisterUser() + public async Task HandleAsync_WhenUserDoesNotExistAndWithout2FA_ShouldRegisterUser() { // Arrange RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand() with { Use2fa = false }; @@ -115,7 +120,7 @@ public class RegisterUserCommandHandlerTests .Returns(Result.Created); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -132,7 +137,7 @@ public class RegisterUserCommandHandlerTests } [Fact] - public async Task Handle_WhenUserAlreadyExists_ShouldReturnError() + public async Task HandleAsync_WhenUserAlreadyExists_ShouldReturnError() { // Arrange RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); @@ -142,7 +147,7 @@ public class RegisterUserCommandHandlerTests .Returns(ErrorOrFactory.From(existingUser)); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -154,7 +159,7 @@ public class RegisterUserCommandHandlerTests } [Fact] - public async Task Handle_WhenInsertFails_ShouldReturnError() + public async Task HandleAsync_WhenInsertFails_ShouldReturnError() { // Arrange RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); @@ -166,7 +171,7 @@ public class RegisterUserCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -178,7 +183,7 @@ public class RegisterUserCommandHandlerTests } [Fact] - public async Task Handle_WhenGetByUsernameReturnsError_ShouldReturnError() + public async Task HandleAsync_WhenGetByUsernameReturnsError_ShouldReturnError() { // Arrange RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); @@ -188,7 +193,7 @@ public class RegisterUserCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs index ac218583..b517a24e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -32,11 +34,10 @@ public class RegisterUserCommandValidatorTests command = command with { Username = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); } [Fact] @@ -47,11 +48,10 @@ public class RegisterUserCommandValidatorTests command = command with { Username = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); } [Fact] @@ -62,11 +62,10 @@ public class RegisterUserCommandValidatorTests command = command with { Username = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); } [Fact] @@ -77,11 +76,10 @@ public class RegisterUserCommandValidatorTests command = command with { Password = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Password) - .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordCannotBeEmpty); } [Fact] @@ -92,11 +90,10 @@ public class RegisterUserCommandValidatorTests command = command with { Password = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Password) - .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordCannotBeEmpty); } [Fact] @@ -107,11 +104,10 @@ public class RegisterUserCommandValidatorTests command = command with { Password = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Password) - .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordCannotBeEmpty); } [Fact] @@ -122,11 +118,10 @@ public class RegisterUserCommandValidatorTests command = command with { PasswordConfirm = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm) - .WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordConfirmCannotBeEmpty); } [Fact] @@ -137,11 +132,10 @@ public class RegisterUserCommandValidatorTests command = command with { PasswordConfirm = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm) - .WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordConfirmCannotBeEmpty); } [Fact] @@ -152,11 +146,10 @@ public class RegisterUserCommandValidatorTests command = command with { PasswordConfirm = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm) - .WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordConfirmCannotBeEmpty); } [Fact] @@ -167,11 +160,10 @@ public class RegisterUserCommandValidatorTests command = command with { PasswordConfirm = "$321Bcda" }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Password) - .WithErrorMessage(Errors.Authentication.PasswordsNotMatch.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordsNotMatch); } [Theory] @@ -188,11 +180,10 @@ public class RegisterUserCommandValidatorTests command = command with { Password = password, PasswordConfirm = password }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Password) - .WithErrorMessage(Errors.Authentication.InvalidPassword.Description); + result.ShouldHaveValidationError(Errors.Authentication.InvalidPassword); } [Theory] @@ -207,10 +198,10 @@ public class RegisterUserCommandValidatorTests command = command with { Password = password, PasswordConfirm = password }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Password); + result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword); } [Fact] @@ -226,12 +217,12 @@ public class RegisterUserCommandValidatorTests }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Username); - result.ShouldNotHaveValidationErrorFor(x => x.Password); - result.ShouldNotHaveValidationErrorFor(x => x.PasswordConfirm); + result.ShouldNotHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword); + result.ShouldNotHaveValidationError(Errors.Authentication.PasswordConfirmCannotBeEmpty); } [Theory] @@ -245,11 +236,10 @@ public class RegisterUserCommandValidatorTests command = command with { Username = username }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameMustBeBetween3And255CharactersLong.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameMustBeBetween3And255CharactersLong); } [Theory] @@ -270,10 +260,10 @@ public class RegisterUserCommandValidatorTests command = command with { Username = username }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username); + result.ShouldHaveValidationError(Errors.Authentication.InvalidUsername); } [Theory] @@ -291,9 +281,9 @@ public class RegisterUserCommandValidatorTests command = command with { Username = username }; // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Username); - } + result.ShouldNotHaveValidationError(Errors.Authentication.InvalidUsername); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs index b458cc38..ca6631be 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs @@ -57,7 +57,7 @@ public class GetUsersQueryHandlerTests } [Fact] - public async Task Handle_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange GetUsersQuery query = _getUsersQueryFixture.CreateQuery(); @@ -65,7 +65,7 @@ public class GetUsersQueryHandlerTests .Returns(false); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -74,7 +74,7 @@ public class GetUsersQueryHandlerTests } [Fact] - public async Task Handle_WhenGetUsersFails_ShouldReturnError() + public async Task HandleAsync_WhenGetUsersFails_ShouldReturnError() { // Arrange GetUsersQuery query = _getUsersQueryFixture.CreateQuery(); @@ -86,7 +86,7 @@ public class GetUsersQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -94,7 +94,7 @@ public class GetUsersQueryHandlerTests } [Fact] - public async Task Handle_WhenAllOperationsSucceed_ShouldReturnUsers() + public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnUsers() { // Arrange GetUsersQuery query = _getUsersQueryFixture.CreateQuery(); @@ -107,7 +107,7 @@ public class GetUsersQueryHandlerTests .Returns(ErrorOrFactory.From(users)); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs index 383861ee..6d7ab1b0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Contracts.Responses.Authentication; @@ -50,17 +51,21 @@ public class LoginUserQueryHandlerTests _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); _mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); _sut = new LoginUserQueryHandler( _mockUnitOfWork, _mockHashService, _mockJwtTokenGenerator, _mockTotpTokenGenerator, _mockCryptographyService, - _mockDateTimeProvider); + _mockDateTimeProvider, + mockValidator); } [Fact] - public async Task Handle_WhenValidCredentialsWithoutTOTP_ShouldReturnLoginResponse() + public async Task HandleAsync_WhenValidCredentialsWithoutTOTP_ShouldReturnLoginResponse() { // Arrange string password = "password123"; @@ -81,7 +86,7 @@ public class LoginUserQueryHandlerTests .Returns(jwtToken); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -92,7 +97,7 @@ public class LoginUserQueryHandlerTests } [Fact] - public async Task Handle_WhenValidCredentialsWithTOTP_ShouldReturnLoginResponse() + public async Task HandleAsync_WhenValidCredentialsWithTOTP_ShouldReturnLoginResponse() { // Arrange string password = "password123"; @@ -120,7 +125,7 @@ public class LoginUserQueryHandlerTests .Returns(true); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -131,7 +136,7 @@ public class LoginUserQueryHandlerTests } [Fact] - public async Task Handle_WhenUserDoesNotExist_ShouldReturnError() + public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnError() { // Arrange LoginUserQuery query = new("nonexistentUser", "password"); @@ -140,7 +145,7 @@ public class LoginUserQueryHandlerTests .Returns(ErrorOrFactory.From(null)); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -148,7 +153,7 @@ public class LoginUserQueryHandlerTests } [Fact] - public async Task Handle_WhenPasswordIsIncorrect_ShouldReturnError() + public async Task HandleAsync_WhenPasswordIsIncorrect_ShouldReturnError() { // Arrange string password = "wrongPassword"; @@ -166,7 +171,7 @@ public class LoginUserQueryHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -174,7 +179,7 @@ public class LoginUserQueryHandlerTests } [Fact] - public async Task Handle_WhenTempPasswordIsExpired_ShouldReturnError() + public async Task HandleAsync_WhenTempPasswordIsExpired_ShouldReturnError() { // Arrange string password = "tempPassword"; @@ -196,7 +201,7 @@ public class LoginUserQueryHandlerTests .Returns(true); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -209,7 +214,7 @@ public class LoginUserQueryHandlerTests } [Fact] - public async Task Handle_WhenValidTempPassword_ShouldReturnLoginResponse() + public async Task HandleAsync_WhenValidTempPassword_ShouldReturnLoginResponse() { // Arrange string password = "tempPassword"; @@ -236,7 +241,7 @@ public class LoginUserQueryHandlerTests .Returns(jwtToken); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -247,7 +252,7 @@ public class LoginUserQueryHandlerTests } [Fact] - public async Task Handle_WhenUserHasTOTPButNoCodeProvided_ShouldReturnError() + public async Task HandleAsync_WhenUserHasTOTPButNoCodeProvided_ShouldReturnError() { // Arrange string password = "password123"; @@ -266,7 +271,7 @@ public class LoginUserQueryHandlerTests .Returns(true); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -274,7 +279,7 @@ public class LoginUserQueryHandlerTests } [Fact] - public async Task Handle_WhenTOTPCodeIsInvalid_ShouldReturnError() + public async Task HandleAsync_WhenTOTPCodeIsInvalid_ShouldReturnError() { // Arrange string password = "password123"; @@ -299,7 +304,7 @@ public class LoginUserQueryHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -307,7 +312,7 @@ public class LoginUserQueryHandlerTests } [Fact] - public async Task Handle_WhenGetByUsernameReturnsError_ShouldReturnError() + public async Task HandleAsync_WhenGetByUsernameReturnsError_ShouldReturnError() { // Arrange LoginUserQuery query = new("username", "password"); @@ -317,7 +322,7 @@ public class LoginUserQueryHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -325,7 +330,7 @@ public class LoginUserQueryHandlerTests } [Fact] - public async Task Handle_WhenBothRegularAndTempPasswordsAreIncorrect_ShouldReturnError() + public async Task HandleAsync_WhenBothRegularAndTempPasswordsAreIncorrect_ShouldReturnError() { // Arrange string password = "wrongPassword"; @@ -347,7 +352,7 @@ public class LoginUserQueryHandlerTests .Returns(false); // Temp password check also fails // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs index 3bae7a22..6926bf1a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -32,11 +34,10 @@ public class LoginUserQueryValidatorTests query = query with { Username = null! }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); } [Fact] @@ -47,11 +48,10 @@ public class LoginUserQueryValidatorTests query = query with { Username = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); } [Fact] @@ -62,11 +62,10 @@ public class LoginUserQueryValidatorTests query = query with { Username = " " }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Username) - .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); } [Fact] @@ -77,11 +76,10 @@ public class LoginUserQueryValidatorTests query = query with { Password = null! }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Password) - .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordCannotBeEmpty); } [Fact] @@ -92,11 +90,10 @@ public class LoginUserQueryValidatorTests query = query with { Password = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Password) - .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordCannotBeEmpty); } [Fact] @@ -107,11 +104,10 @@ public class LoginUserQueryValidatorTests query = query with { Password = " " }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Password) - .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Authentication.PasswordCannotBeEmpty); } [Theory] @@ -128,11 +124,10 @@ public class LoginUserQueryValidatorTests query = query with { Password = password }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Password) - .WithErrorMessage(Errors.Authentication.InvalidPassword.Description); + result.ShouldHaveValidationError(Errors.Authentication.InvalidPassword); } [Theory] @@ -147,10 +142,10 @@ public class LoginUserQueryValidatorTests query = query with { Password = password }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Password); + result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword); } [Theory] @@ -167,11 +162,10 @@ public class LoginUserQueryValidatorTests query = query with { TotpCode = totpCode }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.TotpCode) - .WithErrorMessage(Errors.Authentication.InvalidTotpCode.Description); + result.ShouldHaveValidationError(Errors.Authentication.InvalidTotpCode); } [Theory] @@ -185,10 +179,10 @@ public class LoginUserQueryValidatorTests query = query with { TotpCode = totpCode }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.TotpCode); + result.ShouldNotHaveValidationError(Errors.Authentication.InvalidTotpCode); } [Fact] @@ -199,10 +193,10 @@ public class LoginUserQueryValidatorTests query = query with { TotpCode = null }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.TotpCode); + result.ShouldNotHaveValidationError(Errors.Authentication.InvalidTotpCode); } [Fact] @@ -212,11 +206,11 @@ public class LoginUserQueryValidatorTests LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(true); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Username); - result.ShouldNotHaveValidationErrorFor(x => x.Password); - result.ShouldNotHaveValidationErrorFor(x => x.TotpCode); + result.ShouldNotHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword); + result.ShouldNotHaveValidationError(Errors.Authentication.InvalidTotpCode); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs index 44a6065f..61d12cc2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions.Fixtures; @@ -60,14 +61,18 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockUnitOfWork.GetRepository().Returns(_mockRoleRepository); _mockUnitOfWork.GetRepository().Returns(_mockPermissionRepository); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); _sut = new UpdateUserRoleAndPermissionsCommandHandler( _mockAuthorizationService, _mockCurrentUserService, - _mockUnitOfWork); + _mockUnitOfWork, + mockValidator); } [Fact] - public async Task Handle_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(); @@ -75,7 +80,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -84,7 +89,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests } [Fact] - public async Task Handle_WhenUserDoesNotExist_ShouldReturnUserDoesNotExistError() + public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnUserDoesNotExistError() { // Arrange UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(); @@ -94,7 +99,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests .Returns((UserEntity?)null); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -102,7 +107,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests } [Fact] - public async Task Handle_WhenRoleDoesNotExist_ShouldReturnRoleNotFoundError() + public async Task HandleAsync_WhenRoleDoesNotExist_ShouldReturnRoleNotFoundError() { // Arrange UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid()); @@ -116,7 +121,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests .Returns((RoleEntity?)null); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -124,7 +129,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests } [Fact] - public async Task Handle_WhenRemovingLastAdmin_ShouldReturnCannotRemoveLastAdminError() + public async Task HandleAsync_WhenRemovingLastAdmin_ShouldReturnCannotRemoveLastAdminError() { // Arrange UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid()); @@ -162,7 +167,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests .Returns(ErrorOrFactory.From(users)); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -170,7 +175,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests } [Fact] - public async Task Handle_WhenUpdateFails_ShouldReturnError() + public async Task HandleAsync_WhenUpdateFails_ShouldReturnError() { // Arrange UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid()); @@ -192,7 +197,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -201,7 +206,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests } [Fact] - public async Task Handle_WhenAllOperationsSucceed_ShouldReturnSuccessResponse() + public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccessResponse() { // Arrange UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid()); @@ -242,7 +247,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests .Returns(Result.Updated); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -253,7 +258,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests } [Fact] - public async Task Handle_WhenGetAllUsersFails_ShouldReturnError() + public async Task HandleAsync_WhenGetAllUsersFails_ShouldReturnError() { // Arrange UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid()); @@ -286,7 +291,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -294,7 +299,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests } [Fact] - public async Task Handle_WhenGetPermissionsFails_ShouldReturnError() + public async Task HandleAsync_WhenGetPermissionsFails_ShouldReturnError() { // Arrange UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid()); @@ -321,7 +326,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(command, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs index f17dc2d8..c40b203a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs @@ -1,7 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; +using Lumina.Application.UnitTests.Common.Setup; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors; @@ -35,11 +37,10 @@ public class UpdateUserRoleAndPermissionsCommandValidatorTests [Guid.NewGuid()]); // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor(x => x.UserId) - .WithErrorMessage(DomainErrors.Users.UserIdCannotBeEmpty.Description); + result.ShouldHaveValidationError(DomainErrors.Users.UserIdCannotBeEmpty); } [Fact] @@ -52,11 +53,10 @@ public class UpdateUserRoleAndPermissionsCommandValidatorTests [Guid.Empty, Guid.NewGuid()]); // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldHaveValidationErrorFor("Permissions[0]") - .WithErrorMessage(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty.Description); + result.ShouldHaveValidationError(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty); } [Fact] @@ -69,10 +69,10 @@ public class UpdateUserRoleAndPermissionsCommandValidatorTests null!); // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Permissions); + result.ShouldNotHaveValidationError(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty); } [Fact] @@ -85,10 +85,10 @@ public class UpdateUserRoleAndPermissionsCommandValidatorTests []); // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Permissions); + result.ShouldNotHaveValidationError(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty); } [Fact] @@ -101,7 +101,7 @@ public class UpdateUserRoleAndPermissionsCommandValidatorTests [Guid.NewGuid()]); // Act - TestValidationResult result = _validator.TestValidate(command); + List result = _validator.TestValidate(command); // Assert result.ShouldNotHaveAnyValidationErrors(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs index 1b17edea..cf54a454 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization.Fixtures; using Lumina.Contracts.Responses.Authorization; @@ -33,11 +34,14 @@ public class GetAuthorizationQueryHandlerTests { _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); - _sut = new GetAuthorizationQueryHandler(_mockAuthorizationService, _mockCurrentUserService); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new GetAuthorizationQueryHandler(_mockAuthorizationService, _mockCurrentUserService, mockValidator); } [Fact] - public async Task Handle_WhenRequestingOwnAuthorization_ShouldReturnAuthorization() + public async Task HandleAsync_WhenRequestingOwnAuthorization_ShouldReturnAuthorization() { // Arrange Guid userId = Guid.NewGuid(); @@ -49,7 +53,7 @@ public class GetAuthorizationQueryHandlerTests .Returns(ErrorOrFactory.From(authEntity)); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -59,7 +63,7 @@ public class GetAuthorizationQueryHandlerTests } [Fact] - public async Task Handle_WhenAdminRequestingOtherUserAuthorization_ShouldReturnAuthorization() + public async Task HandleAsync_WhenAdminRequestingOtherUserAuthorization_ShouldReturnAuthorization() { // Arrange Guid adminUserId = Guid.NewGuid(); @@ -75,7 +79,7 @@ public class GetAuthorizationQueryHandlerTests .Returns(ErrorOrFactory.From(targetAuthEntity)); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -85,7 +89,7 @@ public class GetAuthorizationQueryHandlerTests } [Fact] - public async Task Handle_WhenNonAdminRequestingOtherUserAuthorization_ShouldReturnError() + public async Task HandleAsync_WhenNonAdminRequestingOtherUserAuthorization_ShouldReturnError() { // Arrange Guid currentUserId = Guid.NewGuid(); @@ -98,7 +102,7 @@ public class GetAuthorizationQueryHandlerTests .Returns(ErrorOrFactory.From(currentUserAuth)); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -106,7 +110,7 @@ public class GetAuthorizationQueryHandlerTests } [Fact] - public async Task Handle_WhenGetCurrentUserAuthorizationFails_ShouldReturnError() + public async Task HandleAsync_WhenGetCurrentUserAuthorizationFails_ShouldReturnError() { // Arrange Guid currentUserId = Guid.NewGuid(); @@ -119,7 +123,7 @@ public class GetAuthorizationQueryHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -127,7 +131,7 @@ public class GetAuthorizationQueryHandlerTests } [Fact] - public async Task Handle_WhenGetTargetUserAuthorizationFails_ShouldReturnError() + public async Task HandleAsync_WhenGetTargetUserAuthorizationFails_ShouldReturnError() { // Arrange Guid adminUserId = Guid.NewGuid(); @@ -143,7 +147,7 @@ public class GetAuthorizationQueryHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidatorTests.cs index 2de98dda..55f319d7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidatorTests.cs @@ -1,9 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization.Fixtures; using Lumina.Domain.SharedKernel.Common.Errors; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -33,11 +35,10 @@ public class GetAuthorizationQueryValidatorTests query = query with { UserId = null }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.UserId) - .WithErrorMessage(Errors.Users.UserIdCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Users.UserIdCannotBeEmpty); } [Fact] @@ -48,11 +49,10 @@ public class GetAuthorizationQueryValidatorTests query = query with { UserId = Guid.Empty }; // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.UserId) - .WithErrorMessage(Errors.Users.UserIdCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Users.UserIdCannotBeEmpty); } [Fact] @@ -62,9 +62,9 @@ public class GetAuthorizationQueryValidatorTests GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.UserId); + result.ShouldNotHaveValidationError(Errors.Users.UserIdCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs index b32d7d53..4225df62 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetUserPermissions.Fixtures; using Lumina.Contracts.Responses.Authorization; @@ -50,14 +51,18 @@ public class GetUserPermissionsQueryHandlerTests _mockCurrentUserService.UserId.Returns(_userId); _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); _sut = new GetUserPermissionsQueryHandler( _mockAuthorizationService, _mockCurrentUserService, - _mockUnitOfWork); + _mockUnitOfWork, + mockValidator); } [Fact] - public async Task Handle_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.CreateQuery(); @@ -65,7 +70,7 @@ public class GetUserPermissionsQueryHandlerTests .Returns(false); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -74,7 +79,7 @@ public class GetUserPermissionsQueryHandlerTests } [Fact] - public async Task Handle_WhenGetUserByIdFails_ShouldReturnError() + public async Task HandleAsync_WhenGetUserByIdFails_ShouldReturnError() { // Arrange GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.CreateQuery(); @@ -86,7 +91,7 @@ public class GetUserPermissionsQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -94,7 +99,7 @@ public class GetUserPermissionsQueryHandlerTests } [Fact] - public async Task Handle_WhenUserDoesNotExist_ShouldReturnUsernameDoesNotExistError() + public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnUsernameDoesNotExistError() { // Arrange GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.CreateQuery(); @@ -105,7 +110,7 @@ public class GetUserPermissionsQueryHandlerTests .Returns((UserEntity?)null); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -113,7 +118,7 @@ public class GetUserPermissionsQueryHandlerTests } [Fact] - public async Task Handle_WhenUserHasPermissions_ShouldReturnPermissions() + public async Task HandleAsync_WhenUserHasPermissions_ShouldReturnPermissions() { // Arrange GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.CreateQuery(); @@ -144,7 +149,7 @@ public class GetUserPermissionsQueryHandlerTests .Returns(user); // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs index 1abc205b..48b5045f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.SharedKernel.Common.Errors; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -31,11 +33,10 @@ public class GetUserPermissionsQueryValidatorTests GetUserPermissionsQuery query = new(null); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.UserId) - .WithErrorMessage(Errors.Users.UserIdCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Users.UserIdCannotBeEmpty); } [Fact] @@ -45,11 +46,10 @@ public class GetUserPermissionsQueryValidatorTests GetUserPermissionsQuery query = new(Guid.Empty); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.UserId) - .WithErrorMessage(Errors.Users.UserIdCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Users.UserIdCannotBeEmpty); } [Fact] @@ -59,9 +59,9 @@ public class GetUserPermissionsQueryValidatorTests GetUserPermissionsQuery query = new(Guid.NewGuid()); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.UserId); + result.ShouldNotHaveValidationError(Errors.Users.UserIdCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs index eded78a2..ea7d537c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetUserRole.Fixtures; @@ -48,14 +49,18 @@ public class GetUserRoleQueryHandlerTests _mockCurrentUserService.UserId.Returns(_userId); _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); _sut = new GetUserRoleQueryHandler( _mockAuthorizationService, _mockCurrentUserService, - _mockUnitOfWork); + _mockUnitOfWork, + mockValidator); } [Fact] - public async Task Handle_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange GetUserRoleQuery query = _getUserRoleQueryFixture.CreateQuery(); @@ -63,7 +68,7 @@ public class GetUserRoleQueryHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -72,7 +77,7 @@ public class GetUserRoleQueryHandlerTests } [Fact] - public async Task Handle_WhenGetUserByIdFails_ShouldReturnError() + public async Task HandleAsync_WhenGetUserByIdFails_ShouldReturnError() { // Arrange GetUserRoleQuery query = _getUserRoleQueryFixture.CreateQuery(); @@ -84,7 +89,7 @@ public class GetUserRoleQueryHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -92,7 +97,7 @@ public class GetUserRoleQueryHandlerTests } [Fact] - public async Task Handle_WhenUserDoesNotExist_ShouldReturnUsernameDoesNotExistError() + public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnUsernameDoesNotExistError() { // Arrange GetUserRoleQuery query = _getUserRoleQueryFixture.CreateQuery(); @@ -103,7 +108,7 @@ public class GetUserRoleQueryHandlerTests .Returns((UserEntity?)null); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsError); @@ -111,7 +116,7 @@ public class GetUserRoleQueryHandlerTests } [Fact] - public async Task Handle_WhenUserHasNoRole_ShouldReturnNull() + public async Task HandleAsync_WhenUserHasNoRole_ShouldReturnNull() { // Arrange GetUserRoleQuery query = _getUserRoleQueryFixture.CreateQuery(); @@ -123,7 +128,7 @@ public class GetUserRoleQueryHandlerTests .Returns(user); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); @@ -131,7 +136,7 @@ public class GetUserRoleQueryHandlerTests } [Fact] - public async Task Handle_WhenUserHasRole_ShouldReturnRole() + public async Task HandleAsync_WhenUserHasRole_ShouldReturnRole() { // Arrange GetUserRoleQuery query = _getUserRoleQueryFixture.CreateQuery(); @@ -159,7 +164,7 @@ public class GetUserRoleQueryHandlerTests .Returns(user); // Act - ErrorOr result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsError); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs index 3e1133ce..808e6c7e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; +using ErrorOr; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; +using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.SharedKernel.Common.Errors; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -31,11 +33,10 @@ public class GetUserRoleQueryValidatorTests GetUserRoleQuery query = new(null); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.UserId) - .WithErrorMessage(Errors.Users.UserIdCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Users.UserIdCannotBeEmpty); } [Fact] @@ -45,11 +46,10 @@ public class GetUserRoleQueryValidatorTests GetUserRoleQuery query = new(Guid.Empty); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.UserId) - .WithErrorMessage(Errors.Users.UserIdCannotBeEmpty.Description); + result.ShouldHaveValidationError(Errors.Users.UserIdCannotBeEmpty); } [Fact] @@ -59,9 +59,9 @@ public class GetUserRoleQueryValidatorTests GetUserRoleQuery query = new(Guid.NewGuid()); // Act - TestValidationResult result = _validator.TestValidate(query); + List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.UserId); + result.ShouldNotHaveValidationError(Errors.Users.UserIdCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DomainEvents/DomainEventPublisherTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DomainEvents/DomainEventPublisherTests.cs new file mode 100644 index 00000000..77250d85 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DomainEvents/DomainEventPublisherTests.cs @@ -0,0 +1,194 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Infrastructure.Common.DomainEvents; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.DomainEvents; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DomainEventPublisherTests +{ + public sealed record TestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent; + + public sealed record NestedTestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent; + + private sealed class RecordingDomainEventHandler : IDomainEventHandler + { + private readonly List _callLog; + private readonly string _handlerName; + + public RecordingDomainEventHandler(List callLog, string handlerName) + { + _callLog = callLog; + _handlerName = handlerName; + } + + public ValueTask HandleAsync(TestDomainEvent domainEvent, CancellationToken cancellationToken) + { + _callLog.Add(_handlerName); + return ValueTask.CompletedTask; + } + } + + /// + /// Creates a publisher wired to a fresh service provider, optionally registering additional services. + /// + /// Optional action used to register additional services into the provider. + /// A domain event publisher resolved from the created provider. + private static IDomainEventPublisher CreatePublisher(Action? configureServices = null) + { + IServiceCollection services = new ServiceCollection(); + services.AddScoped(); + configureServices?.Invoke(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + return serviceProvider.GetRequiredService(); + } + + /// + /// Creates a valid instance of . + /// + /// The created domain event. + private static TestDomainEvent CreateTestDomainEvent() + { + return new TestDomainEvent(Guid.NewGuid(), DateTime.UtcNow); + } + + /// + /// Creates a valid instance of . + /// + /// The created domain event. + private static NestedTestDomainEvent CreateNestedTestDomainEvent() + { + return new NestedTestDomainEvent(Guid.NewGuid(), DateTime.UtcNow); + } + + [Fact] + public async Task Publish_WhenHandlersAreRegistered_ShouldInvokeAllHandlersInOrder() + { + // Arrange + TestDomainEvent domainEvent = CreateTestDomainEvent(); + List callLog = []; + IDomainEventPublisher publisher = CreatePublisher(services => + { + services.AddScoped>(_ => new RecordingDomainEventHandler(callLog, "first")); + services.AddScoped>(_ => new RecordingDomainEventHandler(callLog, "second")); + }); + + // Act + await publisher.PublishAsync(domainEvent, CancellationToken.None); + + // Assert + Assert.Equal(["first", "second"], callLog); + } + + [Fact] + public async Task Publish_WhenNoHandlersAreRegisteredForTheEventType_ShouldNotThrow() + { + // Arrange + TestDomainEvent domainEvent = CreateTestDomainEvent(); + IDomainEventPublisher publisher = CreatePublisher(); + + // Act + await publisher.PublishAsync(domainEvent, CancellationToken.None); + + // Assert + // reaching this point without an exception means the publish was a no-op, as expected + } + + [Fact] + public async Task Publish_WhenOnlyAnotherEventTypeHasHandlers_ShouldNotInvokeThem() + { + // Arrange + TestDomainEvent domainEvent = CreateTestDomainEvent(); + IDomainEventHandler nestedHandler = Substitute.For>(); + IDomainEventPublisher publisher = CreatePublisher(services => services.AddScoped(_ => nestedHandler)); + + // Act + await publisher.PublishAsync(domainEvent, CancellationToken.None); + + // Assert + await nestedHandler.DidNotReceive().HandleAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Publish_WhenHandlerThrows_ShouldPropagateTheException() + { + // Arrange + TestDomainEvent domainEvent = CreateTestDomainEvent(); + InvalidOperationException expectedException = new("Test exception"); + IDomainEventHandler handler = Substitute.For>(); + handler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => throw expectedException); + IDomainEventPublisher publisher = CreatePublisher(services => services.AddScoped>(_ => handler)); + + // Act + InvalidOperationException result = await Assert.ThrowsAsync( + () => publisher.PublishAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Same(expectedException, result); + } + + [Fact] + public async Task Publish_WhenHandlerPublishesAnotherEvent_ShouldInvokeNestedHandlers() + { + // Arrange + TestDomainEvent domainEvent = CreateTestDomainEvent(); + NestedTestDomainEvent nestedDomainEvent = CreateNestedTestDomainEvent(); + IDomainEventHandler handler = Substitute.For>(); + IDomainEventHandler nestedHandler = Substitute.For>(); + IDomainEventPublisher publisher = CreatePublisher(services => + { + services.AddScoped(_ => handler); + services.AddScoped(_ => nestedHandler); + }); + handler.HandleAsync(domainEvent, Arg.Any()) + .Returns(callInfo => publisher.PublishAsync(nestedDomainEvent, callInfo.Arg())); + + // Act + await publisher.PublishAsync(domainEvent, CancellationToken.None); + + // Assert + await nestedHandler.Received(1).HandleAsync(nestedDomainEvent, Arg.Any()); + } + + [Fact] + public async Task Publish_WhenCancellationRequested_ShouldPassTokenToHandlers() + { + // Arrange + TestDomainEvent domainEvent = CreateTestDomainEvent(); + using CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + IDomainEventHandler handler = Substitute.For>(); + IDomainEventPublisher publisher = CreatePublisher(services => services.AddScoped(_ => handler)); + + // Act + await publisher.PublishAsync(domainEvent, cancellationToken); + + // Assert + await handler.Received(1).HandleAsync(domainEvent, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task Publish_WhenDomainEventIsNull_ShouldThrowArgumentNullException() + { + // Arrange + IDomainEventPublisher publisher = CreatePublisher(); + + // Act + ArgumentNullException result = await Assert.ThrowsAsync(() => publisher.PublishAsync(null!, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal("domainEvent", result.ParamName); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/Fixtures/OptionsBuilderFluentValidationUtilitiesFixture.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/Fixtures/OptionsBuilderValidationUtilitiesFixture.cs similarity index 68% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/Fixtures/OptionsBuilderFluentValidationUtilitiesFixture.cs rename to tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/Fixtures/OptionsBuilderValidationUtilitiesFixture.cs index 336282ec..4ead5274 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/Fixtures/OptionsBuilderFluentValidationUtilitiesFixture.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/Fixtures/OptionsBuilderValidationUtilitiesFixture.cs @@ -5,10 +5,10 @@ using System.Diagnostics.CodeAnalysis; namespace Lumina.Infrastructure.UnitTests.Common.Utilities.Fixtures; /// -/// Contains unit tests for the class. +/// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] -public class OptionsBuilderFluentValidationUtilitiesFixture +public class OptionsBuilderValidationUtilitiesFixture { -} \ No newline at end of file +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/OptionsBuilderFluentValidationUtilitiesTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/OptionsBuilderValidationUtilitiesTests.cs similarity index 66% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/OptionsBuilderFluentValidationUtilitiesTests.cs rename to tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/OptionsBuilderValidationUtilitiesTests.cs index add0c956..c852568a 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/OptionsBuilderFluentValidationUtilitiesTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/OptionsBuilderValidationUtilitiesTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using FluentValidation; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Infrastructure.Common.Utilities; using Lumina.Infrastructure.Common.Validation; using Lumina.Infrastructure.UnitTests.Common.Utilities.Fixtures; @@ -16,17 +16,17 @@ using System.Linq; namespace Lumina.Infrastructure.UnitTests.Common.Utilities; /// -/// Contains unit tests for the class. +/// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] -public class OptionsBuilderFluentValidationUtilitiesTests +public class OptionsBuilderValidationUtilitiesTests { private readonly IFixture _fixture; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public OptionsBuilderFluentValidationUtilitiesTests() + public OptionsBuilderValidationUtilitiesTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); } @@ -37,15 +37,15 @@ public class OptionsBuilderFluentValidationUtilitiesTests // Arrange IServiceCollection services = Substitute.For(); string name = _fixture.Create(); - OptionsBuilder optionsBuilder = new(services, name); + OptionsBuilder optionsBuilder = new(services, name); // Act - OptionsBuilder result = optionsBuilder.ValidateFluently(); + OptionsBuilder result = optionsBuilder.ValidateFluently(); // Assert Assert.Same(optionsBuilder, result); services.Received(1).Add(Arg.Is(sd => - sd.ServiceType == typeof(IValidateOptions) && + sd.ServiceType == typeof(IValidateOptions) && sd.Lifetime == ServiceLifetime.Singleton && sd.ImplementationFactory != null)); } @@ -56,14 +56,14 @@ public class OptionsBuilderFluentValidationUtilitiesTests // Arrange ServiceCollection services = new(); string name = _fixture.Create(); - OptionsBuilder optionsBuilder = new(services, name); + OptionsBuilder optionsBuilder = new(services, name); // Act optionsBuilder.ValidateFluently(); // Assert ServiceDescriptor? serviceDescriptor = services.FirstOrDefault(sd => - sd.ServiceType == typeof(IValidateOptions) && + sd.ServiceType == typeof(IValidateOptions) && sd.Lifetime == ServiceLifetime.Singleton && sd.ImplementationFactory != null); @@ -73,12 +73,12 @@ public class OptionsBuilderFluentValidationUtilitiesTests Assert.NotNull(implementationFactory); IServiceProvider serviceProvider = Substitute.For(); - IValidator mockValidator = Substitute.For>(); - serviceProvider.GetService(typeof(IValidator)) + IValidator mockValidator = Substitute.For>(); + serviceProvider.GetService(typeof(IValidator)) .Returns(mockValidator); - FluentValidationOptions? fluentValidationOptions = implementationFactory!(serviceProvider) as FluentValidationOptions; - Assert.NotNull(fluentValidationOptions); - Assert.Equal(name, fluentValidationOptions.Name); + ValidationOptions? validationOptions = implementationFactory!(serviceProvider) as ValidationOptions; + Assert.NotNull(validationOptions); + Assert.Equal(name, validationOptions.Name); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/Fixtures/FluentValidationOptionsFixture.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/Fixtures/ValidationOptionsFixture.cs similarity index 73% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/Fixtures/FluentValidationOptionsFixture.cs rename to tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/Fixtures/ValidationOptionsFixture.cs index b8156379..8a793d55 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/Fixtures/FluentValidationOptionsFixture.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/Fixtures/ValidationOptionsFixture.cs @@ -5,10 +5,10 @@ using System.Diagnostics.CodeAnalysis; namespace Lumina.Infrastructure.UnitTests.Common.Validation.Fixtures; /// -/// Contains unit tests for the class. +/// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] -public class FluentValidationOptionsFixture +public class ValidationOptionsFixture { -} \ No newline at end of file +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/FluentValidationOptionsTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/ValidationOptionsTests.cs similarity index 57% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/FluentValidationOptionsTests.cs rename to tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/ValidationOptionsTests.cs index 5f7d6dc6..b331532f 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/FluentValidationOptionsTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/ValidationOptionsTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using FluentValidation; -using FluentValidation.Results; +using ErrorOr; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Infrastructure.Common.Validation; using Lumina.Infrastructure.UnitTests.Common.Validation.Fixtures; using Microsoft.Extensions.Options; @@ -15,17 +15,17 @@ using System.Diagnostics.CodeAnalysis; namespace Lumina.Infrastructure.UnitTests.Common.Validation; /// -/// Contains unit tests for the class. +/// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] -public class FluentValidationOptionsTests +public class ValidationOptionsTests { private readonly IFixture _fixture; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public FluentValidationOptionsTests() + public ValidationOptionsTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); } @@ -35,10 +35,10 @@ public class FluentValidationOptionsTests { // Arrange string name = _fixture.Create(); - FluentValidationOptionsFixture options = _fixture.Create(); - IValidator validator = Substitute.For>(); - validator.Validate(options).Returns(new ValidationResult()); - FluentValidationOptions sut = new(name, validator); + ValidationOptionsFixture options = _fixture.Create(); + IValidator validator = Substitute.For>(); + validator.Validate(options).Returns([]); + ValidationOptions sut = new(name, validator); // Act ValidateOptionsResult result = sut.Validate(name, options); @@ -55,9 +55,9 @@ public class FluentValidationOptionsTests // Arrange string name = _fixture.Create(); string differentName = _fixture.Create(); - FluentValidationOptionsFixture options = _fixture.Create(); - IValidator validator = Substitute.For>(); - FluentValidationOptions sut = new(name, validator); + ValidationOptionsFixture options = _fixture.Create(); + IValidator validator = Substitute.For>(); + ValidationOptions sut = new(name, validator); // Act ValidateOptionsResult result = sut.Validate(differentName, options); @@ -71,10 +71,10 @@ public class FluentValidationOptionsTests public void Validate_WhenNullName_ShouldValidateOptions() { // Arrange - FluentValidationOptionsFixture options = _fixture.Create(); - IValidator validator = Substitute.For>(); - validator.Validate(options).Returns(new ValidationResult()); - FluentValidationOptions sut = new(null, validator); + ValidationOptionsFixture options = _fixture.Create(); + IValidator validator = Substitute.For>(); + validator.Validate(options).Returns([]); + ValidationOptions sut = new(null, validator); // Act ValidateOptionsResult result = sut.Validate(_fixture.Create(), options); @@ -90,8 +90,8 @@ public class FluentValidationOptionsTests { // Arrange string name = _fixture.Create(); - IValidator validator = Substitute.For>(); - FluentValidationOptions sut = new(name, validator); + IValidator validator = Substitute.For>(); + ValidationOptions sut = new(name, validator); // Act Action act = () => sut.Validate(name, null!); @@ -105,14 +105,14 @@ public class FluentValidationOptionsTests { // Arrange string name = _fixture.Create(); - FluentValidationOptionsFixture options = _fixture.Create(); - IValidator validator = Substitute.For>(); - List validationFailures = + ValidationOptionsFixture options = _fixture.Create(); + IValidator validator = Substitute.For>(); + List validationFailures = [ - new("PropertyName", "Error Message") + Error.Validation("PropertyName", "Error Message") ]; - validator.Validate(options).Returns(new ValidationResult(validationFailures)); - FluentValidationOptions sut = new(name, validator); + validator.Validate(options).Returns(validationFailures); + ValidationOptions sut = new(name, validator); // Act ValidateOptionsResult result = sut.Validate(name, options); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs index c7b5db7c..42e906a3 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs @@ -1,9 +1,11 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; +using ErrorOr; using Lumina.Infrastructure.Common.Errors; using Lumina.Infrastructure.Common.Models.DTO.Configuration; using Lumina.Infrastructure.Common.Validators; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -36,11 +38,10 @@ public class CommonSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.True(result.IsValid); - Assert.Empty(result.Errors); + Assert.Empty(result); } [Fact] @@ -52,11 +53,10 @@ public class CommonSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.False(result.IsValid); - Assert.Single(result.Errors); - Assert.Equal(Errors.Configuration.ApplicationThemeCannotBeEmpty.Description, result.Errors[0].ErrorMessage); + Assert.Single(result); + Assert.Equal(Errors.Configuration.ApplicationThemeCannotBeEmpty.Description, result[0].Description); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs index 2192628f..13eca23c 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs @@ -1,9 +1,11 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; +using ErrorOr; using Lumina.Infrastructure.Common.Errors; using Lumina.Infrastructure.Common.Models.DTO.Configuration; using Lumina.Infrastructure.Common.Validators; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -36,11 +38,10 @@ public class DatabaseSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.True(result.IsValid); - Assert.Empty(result.Errors); + Assert.Empty(result); } [Fact] @@ -52,11 +53,10 @@ public class DatabaseSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.False(result.IsValid); - Assert.Single(result.Errors); - Assert.Equal(Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Description, result.Errors[0].ErrorMessage); + Assert.Single(result); + Assert.Equal(Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Description, result[0].Description); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsDtoValidatorTests.cs index 69887a43..b9291c59 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsDtoValidatorTests.cs @@ -1,9 +1,11 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; +using ErrorOr; using Lumina.Infrastructure.Common.Errors; using Lumina.Infrastructure.Common.Models.DTO.Configuration; using Lumina.Infrastructure.Common.Validators; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -36,11 +38,10 @@ public class EncryptionSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.True(result.IsValid); - Assert.Empty(result.Errors); + Assert.Empty(result); } [Fact] @@ -52,12 +53,11 @@ public class EncryptionSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.False(result.IsValid); - Assert.Single(result.Errors); - Assert.Equal(Errors.Configuration.EncryptionSecretKeyCannotBeEmpty.Description, result.Errors[0].ErrorMessage); + Assert.Single(result); + Assert.Equal(Errors.Configuration.EncryptionSecretKeyCannotBeEmpty.Description, result[0].Description); } [Theory] @@ -72,11 +72,10 @@ public class EncryptionSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.False(result.IsValid); - Assert.Single(result.Errors); - Assert.Equal(Errors.Configuration.EncryptionSecretKeyMustBeABase64String.Description, result.Errors[0].ErrorMessage); + Assert.Single(result); + Assert.Equal(Errors.Configuration.EncryptionSecretKeyMustBeABase64String.Description, result[0].Description); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsDtoValidatorTests.cs index 9c4e4ab8..03af6439 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsDtoValidatorTests.cs @@ -1,11 +1,12 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; +using ErrorOr; using Lumina.Infrastructure.Common.Errors; using Lumina.Infrastructure.Common.Models.DTO.Configuration; using Lumina.Infrastructure.Common.Validators; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; #endregion namespace Lumina.Infrastructure.UnitTests.Common.Validators; @@ -40,11 +41,10 @@ public class JwtSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.True(result.IsValid); - Assert.Empty(result.Errors); + Assert.Empty(result); } [Fact] @@ -59,13 +59,12 @@ public class JwtSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.False(result.IsValid); - Assert.Equal(2, result.Errors.Count); - Assert.Contains(Errors.Configuration.JwtSecretKeyCannotBeEmpty.Description, result.Errors.Select(e => e.ErrorMessage)); - Assert.Contains(Errors.Configuration.JwtSecretKeyTooShort.Description, result.Errors.Select(e => e.ErrorMessage)); + Assert.Equal(2, result.Count); + Assert.Contains(result, error => error.Description == Errors.Configuration.JwtSecretKeyCannotBeEmpty.Description); + Assert.Contains(result, error => error.Description == Errors.Configuration.JwtSecretKeyTooShort.Description); } [Fact] @@ -80,12 +79,11 @@ public class JwtSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.False(result.IsValid); - Assert.Single(result.Errors); - Assert.Equal(Errors.Configuration.JwtSecretKeyTooShort.Description, result.Errors[0].ErrorMessage); + Assert.Single(result); + Assert.Equal(Errors.Configuration.JwtSecretKeyTooShort.Description, result[0].Description); } [Theory] @@ -103,12 +101,11 @@ public class JwtSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.False(result.IsValid); - Assert.Single(result.Errors); - Assert.Equal(Errors.Configuration.JwtExpiryMinutesMustBePositive.Description, result.Errors[0].ErrorMessage); + Assert.Single(result); + Assert.Equal(Errors.Configuration.JwtExpiryMinutesMustBePositive.Description, result[0].Description); } [Fact] @@ -123,12 +120,11 @@ public class JwtSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.False(result.IsValid); - Assert.Single(result.Errors); - Assert.Equal(Errors.Configuration.JwtIssuerCannotBeEmpty.Description, result.Errors[0].ErrorMessage); + Assert.Single(result); + Assert.Equal(Errors.Configuration.JwtIssuerCannotBeEmpty.Description, result[0].Description); } [Fact] @@ -143,11 +139,10 @@ public class JwtSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.False(result.IsValid); - Assert.Single(result.Errors); - Assert.Equal(Errors.Configuration.JwtAudienceCannotBeEmpty.Description, result.Errors[0].ErrorMessage); + Assert.Single(result); + Assert.Equal(Errors.Configuration.JwtAudienceCannotBeEmpty.Description, result[0].Description); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsDtoValidatorTests.cs index 9a20a368..35d0108d 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsDtoValidatorTests.cs @@ -1,9 +1,11 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; +using ErrorOr; using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; using Lumina.Infrastructure.Common.Errors; using Lumina.Infrastructure.Common.Validators; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -36,11 +38,10 @@ public class MediaSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.True(result.IsValid); - Assert.Empty(result.Errors); + Assert.Empty(result); } [Fact] @@ -52,12 +53,11 @@ public class MediaSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.False(result.IsValid); - Assert.Single(result.Errors); - Assert.Equal(Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description, result.Errors[0].ErrorMessage); + Assert.Single(result); + Assert.Equal(Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description, result[0].Description); } [Fact] @@ -69,12 +69,11 @@ public class MediaSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.False(result.IsValid); - Assert.Single(result.Errors); - Assert.Equal(Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description, result.Errors[0].ErrorMessage); + Assert.Single(result); + Assert.Equal(Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description, result[0].Description); } [Fact] @@ -86,12 +85,11 @@ public class MediaSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.False(result.IsValid); - Assert.Single(result.Errors); - Assert.Equal(Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty.Description, result.Errors[0].ErrorMessage); + Assert.Single(result); + Assert.Equal(Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty.Description, result[0].Description); } [Fact] @@ -103,11 +101,10 @@ public class MediaSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.True(result.IsValid); - Assert.Empty(result.Errors); + Assert.Empty(result); } [Fact] @@ -119,11 +116,10 @@ public class MediaSettingsDtoValidatorTests .Create(); // Act - FluentValidation.Results.ValidationResult result = _validator.Validate(model); + List result = _validator.Validate(model); // Assert - Assert.False(result.IsValid); - Assert.Single(result.Errors); - Assert.Equal(Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty.Description, result.Errors[0].ErrorMessage); + Assert.Single(result); + Assert.Equal(Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty.Description, result[0].Description); } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointTests.cs index 422db9b8..fec666db 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Permissions.GetPermissions; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -25,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Admin.Authorization.P [ExcludeFromCodeCoverage] public class GetPermissionsEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler>> _mockHandler; private readonly GetPermissionsEndpoint _sut; /// @@ -33,8 +33,8 @@ public class GetPermissionsEndpointTests /// public GetPermissionsEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); } [Fact] @@ -48,7 +48,7 @@ public class GetPermissionsEndpointTests new(Guid.NewGuid(), AuthorizationPermission.CanDeleteUsers), new(Guid.NewGuid(), AuthorizationPermission.CanRegisterUsers) ]; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -60,12 +60,12 @@ public class GetPermissionsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("Permissions.NotFound", "No permissions found."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -90,16 +90,14 @@ public class GetPermissionsEndpointTests // Arrange CancellationToken cancellationToken = CancellationToken.None; IEnumerable response = []; - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(new ValueTask>>( - ErrorOrFactory.From(response) - )); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(response)); // Act await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Any(), Arg.Is(cancellationToken)); } @@ -112,16 +110,14 @@ public class GetPermissionsEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(info => new ValueTask>>( - Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(Enumerable.Empty()); - }, info.Arg()) - )); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(Enumerable.Empty()); + }, info.Arg())); // Act Task operationTask = _sut.ExecuteAsync(new EmptyRequest(), cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs index e5fcf3d5..b1cc0e5f 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs @@ -1,23 +1,15 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; -using Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; -using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; using Lumina.Contracts.DTO.Authentication; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; -using Lumina.Domain.SharedKernel.Common.Enums.Authorization; -using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Permissions.GetPermissions; using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.AddRole; -using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.GetAuthorization; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authorization.GetAuthorization.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; @@ -32,7 +24,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Admin.Authorization.R [ExcludeFromCodeCoverage] public class AddRoleEndpointTests { - private readonly ISender _mockSender; + private readonly ICommandHandler> _mockHandler; private readonly AddRoleEndpoint _sut; /// @@ -40,8 +32,8 @@ public class AddRoleEndpointTests /// public AddRoleEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); } [Fact] @@ -51,7 +43,7 @@ public class AddRoleEndpointTests AddRoleRequest request = new("Admin", [Guid.NewGuid()]); CancellationToken cancellationToken = CancellationToken.None; RolePermissionsResponse expectedResponse = new(new RoleDto(Guid.NewGuid(), "Admin"), []); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -63,13 +55,13 @@ public class AddRoleEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange AddRoleRequest request = new("Admin", [Guid.NewGuid()]); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("Role.Creation.Failed", "Failed to create role."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -94,14 +86,14 @@ public class AddRoleEndpointTests // Arrange AddRoleRequest request = new("Admin", [Guid.NewGuid()]); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(new RolePermissionsResponse(new RoleDto(Guid.NewGuid(), "Admin"), []))); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(cmd => cmd.RoleName == request.RoleName && cmd.Permissions.SequenceEqual(request.Permissions!)), @@ -116,16 +108,14 @@ public class AddRoleEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(info => new ValueTask>( - Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new RolePermissionsResponse(new RoleDto(Guid.NewGuid(), "Admin"), [])); - }, info.Arg()) - )); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(new RolePermissionsResponse(new RoleDto(Guid.NewGuid(), "Admin"), [])); + }, info.Arg())); // Act Task operationTask = _sut.ExecuteAsync(new AddRoleRequest("Admin", []), cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs index 2294a13d..20399910 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs @@ -1,10 +1,9 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; using Lumina.Contracts.Requests.Authorization; using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -22,7 +21,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Admin.Authorization.R [ExcludeFromCodeCoverage] public class DeleteRoleEndpointTests { - private readonly ISender _mockSender; + private readonly ICommandHandler> _mockHandler; private readonly DeleteRoleEndpoint _sut; /// @@ -30,8 +29,8 @@ public class DeleteRoleEndpointTests /// public DeleteRoleEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); } [Fact] @@ -40,7 +39,7 @@ public class DeleteRoleEndpointTests // Arrange DeleteRoleRequest request = new(Guid.NewGuid()); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(Result.Deleted)); // Act @@ -51,13 +50,13 @@ public class DeleteRoleEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange DeleteRoleRequest request = new(Guid.NewGuid()); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("Role.Deletion.Failed", "Failed to delete role."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -83,14 +82,14 @@ public class DeleteRoleEndpointTests Guid roleId = Guid.NewGuid(); DeleteRoleRequest request = new(roleId); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(Result.Deleted)); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(cmd => cmd.RoleId == request.RoleId), Arg.Is(cancellationToken)); } @@ -103,16 +102,14 @@ public class DeleteRoleEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(info => new ValueTask>( - Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(Result.Deleted); - }, info.Arg()) - )); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(Result.Deleted); + }, info.Arg())); // Act Task operationTask = _sut.ExecuteAsync(new DeleteRoleRequest(Guid.NewGuid()), cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs index 98bcb904..ed31a762 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; using Lumina.Contracts.DTO.Authentication; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -25,7 +24,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Admin.Authorization.R [ExcludeFromCodeCoverage] public class GetRolePermissionsEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler> _mockHandler; private readonly GetRolePermissionsEndpoint _sut; /// @@ -33,8 +32,8 @@ public class GetRolePermissionsEndpointTests /// public GetRolePermissionsEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); } [Fact] @@ -47,7 +46,7 @@ public class GetRolePermissionsEndpointTests new RoleDto(Guid.NewGuid(), "Admin"), [new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanViewUsers)] ); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -59,13 +58,13 @@ public class GetRolePermissionsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange GetRolePermissionsRequest request = new(Guid.NewGuid()); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("Role.Permissions.NotFound", "Role permissions not found."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -91,7 +90,7 @@ public class GetRolePermissionsEndpointTests Guid roleId = Guid.NewGuid(); GetRolePermissionsRequest request = new(roleId); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(new RolePermissionsResponse( new RoleDto(Guid.NewGuid(), "Admin"), [] @@ -101,7 +100,7 @@ public class GetRolePermissionsEndpointTests await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(cmd => cmd.RoleId == request.RoleId), Arg.Is(cancellationToken)); } @@ -114,19 +113,17 @@ public class GetRolePermissionsEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(info => new ValueTask>( - Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new RolePermissionsResponse( - new RoleDto(Guid.NewGuid(), "Admin"), - [] - )); - }, info.Arg()) - )); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(new RolePermissionsResponse( + new RoleDto(Guid.NewGuid(), "Admin"), + [] + )); + }, info.Arg())); // Act Task operationTask = _sut.ExecuteAsync(new GetRolePermissionsRequest(Guid.NewGuid()), cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs index cabeba76..4d4059db 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; using Lumina.Contracts.Responses.Authorization; using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.GetRoles; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -23,7 +23,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Admin.Authorization.R [ExcludeFromCodeCoverage] public class GetRolesEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler>> _mockHandler; private readonly GetRolesEndpoint _sut; /// @@ -31,8 +31,8 @@ public class GetRolesEndpointTests /// public GetRolesEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); } [Fact] @@ -44,7 +44,7 @@ public class GetRolesEndpointTests [ new RoleResponse(Guid.NewGuid(), "Admin") ]; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -56,12 +56,12 @@ public class GetRolesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("Roles.NotFound", "No roles found."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -85,19 +85,17 @@ public class GetRolesEndpointTests { // Arrange CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(new ValueTask>>( - ErrorOrFactory.From(new List + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(new List { new(Guid.NewGuid(), "Admin") - } as IEnumerable) - )); + } as IEnumerable)); // Act await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Any(), Arg.Is(cancellationToken)); } @@ -110,16 +108,14 @@ public class GetRolesEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(info => new ValueTask>>( - Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new List() as IEnumerable); - }, info.Arg()) - )); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(new List() as IEnumerable); + }, info.Arg())); // Act Task operationTask = _sut.ExecuteAsync(new EmptyRequest(), cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs index efa55181..e36bc26c 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; using Lumina.Contracts.DTO.Authentication; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.UpdateRole; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -27,7 +26,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Admin.Authorization.R [ExcludeFromCodeCoverage] public class UpdateRoleEndpointTests { - private readonly ISender _mockSender; + private readonly ICommandHandler> _mockHandler; private readonly UpdateRoleEndpoint _sut; /// @@ -35,8 +34,8 @@ public class UpdateRoleEndpointTests /// public UpdateRoleEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); } [Fact] @@ -49,7 +48,7 @@ public class UpdateRoleEndpointTests new RoleDto(Guid.NewGuid(), "UpdatedAdmin"), [new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanViewUsers)] ); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -61,13 +60,13 @@ public class UpdateRoleEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange UpdateRoleRequest request = new(Guid.NewGuid(), "UpdatedAdmin", [Guid.NewGuid()]); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("Role.Update.Failed", "Failed to update role."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -92,7 +91,7 @@ public class UpdateRoleEndpointTests // Arrange UpdateRoleRequest request = new(Guid.NewGuid(), "UpdatedAdmin", [Guid.NewGuid()]); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(new RolePermissionsResponse( new RoleDto(Guid.NewGuid(), "UpdatedAdmin"), [] @@ -102,7 +101,7 @@ public class UpdateRoleEndpointTests await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(cmd => cmd.RoleId == request.RoleId && cmd.RoleName == request.RoleName && @@ -118,19 +117,17 @@ public class UpdateRoleEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(info => new ValueTask>( - Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new RolePermissionsResponse( - new RoleDto(Guid.NewGuid(), "UpdatedAdmin"), - [] - )); - }, info.Arg()) - )); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(new RolePermissionsResponse( + new RoleDto(Guid.NewGuid(), "UpdatedAdmin"), + [] + )); + }, info.Arg())); // Act Task operationTask = _sut.ExecuteAsync( diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs index 768310fe..d0403a76 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs @@ -3,11 +3,11 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; using Lumina.Contracts.Requests.FileSystemManagement.Directories; using Lumina.Contracts.Responses.FileSystemManagement.Directories; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -28,7 +28,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. public class GetDirectoriesEndpointTests { private readonly IFixture _fixture; - private readonly ISender _mockSender; + private readonly IQueryHandler>> _mockHandler; private readonly GetDirectoriesEndpoint _sut; /// @@ -37,8 +37,8 @@ public class GetDirectoriesEndpointTests public GetDirectoriesEndpointTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); } [Fact] @@ -48,7 +48,7 @@ public class GetDirectoriesEndpointTests GetDirectoriesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; List expectedResponses = _fixture.CreateMany(3).ToList(); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); // Act @@ -60,13 +60,13 @@ public class GetDirectoriesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange GetDirectoriesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("Directory.NotFound", "The requested directory was not found."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -86,13 +86,13 @@ public class GetDirectoriesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() { // Arrange GetDirectoriesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -112,19 +112,19 @@ public class GetDirectoriesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetDirectoriesQueryToMediator() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetDirectoriesQueryToHandler() { // Arrange GetDirectoriesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(Enumerable.Empty())); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements), Arg.Is(cancellationToken)); } @@ -138,14 +138,14 @@ public class GetDirectoriesEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return ErrorOrFactory.From(_fixture.CreateMany(3).AsEnumerable()); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs index 29a68580..28c9223b 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.GetDrives; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -25,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class GetDrivesEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler>> _mockHandler; private readonly GetDrivesEndpoint _sut; private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; @@ -34,9 +34,9 @@ public class GetDrivesEndpointTests /// public GetDrivesEndpointTests() { - _mockSender = Substitute.For(); + _mockHandler = Substitute.For>>>(); _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); - _sut = Factory.Create(_mockSender); + _sut = Factory.Create(_mockHandler); } [Fact] @@ -45,7 +45,7 @@ public class GetDrivesEndpointTests // Arrange CancellationToken cancellationToken = CancellationToken.None; List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); // Act @@ -57,12 +57,12 @@ public class GetDrivesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("Drive.NotFound", "The requested drive was not found."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -82,18 +82,18 @@ public class GetDrivesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetDrivesQueryToMediator() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetDrivesQueryToHandler() { // Arrange CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(Enumerable.Empty())); // Act await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); // Assert - await _mockSender.Received(1).Send(Arg.Any(), Arg.Is(cancellationToken)); + await _mockHandler.Received(1).HandleAsync(Arg.Any(), Arg.Is(cancellationToken)); } [Fact] @@ -104,14 +104,14 @@ public class GetDrivesEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1).AsEnumerable()); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(new EmptyRequest(), cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs index 7e10d198..7a0d5075 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem.GetType; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -22,7 +22,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class GetFileSystemTypeEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler _mockHandler; private readonly GetTypeEndpoint _sut; /// @@ -30,8 +30,8 @@ public class GetFileSystemTypeEndpointTests /// public GetFileSystemTypeEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>(); + _sut = Factory.Create(_mockHandler); } [Fact] @@ -40,7 +40,7 @@ public class GetFileSystemTypeEndpointTests // Arrange CancellationToken cancellationToken = CancellationToken.None; FileSystemTypeResponse expectedResponse = new(PlatformType.Windows); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedResponse); // Act @@ -59,7 +59,7 @@ public class GetFileSystemTypeEndpointTests // Arrange CancellationToken cancellationToken = CancellationToken.None; FileSystemTypeResponse expectedResponse = new(platformType); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedResponse); // Act @@ -71,18 +71,18 @@ public class GetFileSystemTypeEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetFileSystemQueryToMediator() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetFileSystemQueryToHandler() { // Arrange CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(new FileSystemTypeResponse(PlatformType.Windows)); // Act await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); // Assert - await _mockSender.Received(1).Send(Arg.Any(), Arg.Is(cancellationToken)); + await _mockHandler.Received(1).HandleAsync(Arg.Any(), Arg.Is(cancellationToken)); } [Fact] @@ -93,14 +93,14 @@ public class GetFileSystemTypeEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return new FileSystemTypeResponse(PlatformType.Windows); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(new EmptyRequest(), cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs index 6424c243..0e207562 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs @@ -3,12 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; using Lumina.Contracts.Requests.FileSystemManagement.Files; using Lumina.Contracts.Responses.FileSystemManagement.Files; using Lumina.Presentation.Api.Common.Http; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetFiles; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -30,7 +30,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. public class GetFilesEndpointTests { private readonly IFixture _fixture; - private readonly ISender _mockSender; + private readonly IQueryHandler>> _mockHandler; private readonly GetFilesEndpoint _sut; /// @@ -39,8 +39,8 @@ public class GetFilesEndpointTests public GetFilesEndpointTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); } [Fact] @@ -50,7 +50,7 @@ public class GetFilesEndpointTests GetFilesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; List expectedResponses = _fixture.CreateMany(3).ToList(); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); // Act @@ -62,13 +62,13 @@ public class GetFilesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange GetFilesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("File.NotFound", "The requested file was not found."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -88,13 +88,13 @@ public class GetFilesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() { // Arrange GetFilesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -119,14 +119,14 @@ public class GetFilesEndpointTests // Arrange GetFilesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(Enumerable.Empty())); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send(Arg.Is(q => + await _mockHandler.Received(1).HandleAsync(Arg.Is(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements), Arg.Is(cancellationToken)); @@ -141,14 +141,14 @@ public class GetFilesEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return ErrorOrFactory.From(_fixture.CreateMany(3).AsEnumerable()); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs index 041af9a8..455ce8be 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs @@ -3,12 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; using Lumina.Contracts.Requests.FileSystemManagement.Files; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -29,7 +29,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. public class GetTreeFilesEndpointTests { private readonly IFixture _fixture; - private readonly ISender _mockSender; + private readonly IQueryHandler>> _mockHandler; private readonly GetTreeFilesEndpoint _sut; private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; @@ -39,9 +39,9 @@ public class GetTreeFilesEndpointTests public GetTreeFilesEndpointTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _mockSender = Substitute.For(); + _mockHandler = Substitute.For>>>(); _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); - _sut = Factory.Create(_mockSender); + _sut = Factory.Create(_mockHandler); } [Fact] @@ -51,7 +51,7 @@ public class GetTreeFilesEndpointTests GetTreeFilesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); // Act @@ -63,13 +63,13 @@ public class GetTreeFilesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange GetTreeFilesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("File.NotFound", "The requested file was not found."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -89,13 +89,13 @@ public class GetTreeFilesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() { // Arrange GetTreeFilesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -120,14 +120,14 @@ public class GetTreeFilesEndpointTests // Arrange GetTreeFilesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(Enumerable.Empty())); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send(Arg.Is(q => + await _mockHandler.Received(1).HandleAsync(Arg.Is(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements), Arg.Is(cancellationToken)); @@ -142,14 +142,14 @@ public class GetTreeFilesEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5).AsEnumerable()); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs index 107a1113..86ade8a8 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -24,7 +24,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class CheckPathExistsEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler> _mockHandler; private readonly CheckPathExistsEndpoint _sut; private readonly CheckPathExistsRequestFixture _checkPathExistsRequestFixture; @@ -33,8 +33,8 @@ public class CheckPathExistsEndpointTests /// public CheckPathExistsEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); _checkPathExistsRequestFixture = new CheckPathExistsRequestFixture(); } @@ -45,7 +45,7 @@ public class CheckPathExistsEndpointTests CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true); CancellationToken cancellationToken = CancellationToken.None; PathExistsResponse expectedResponse = new(true); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedResponse); // Act @@ -57,19 +57,19 @@ public class CheckPathExistsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendCheckPathExistsQueryToMediator() + public async Task ExecuteAsync_WhenCalled_ShouldSendCheckPathExistsQueryToHandler() { // Arrange CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(new PathExistsResponse(true)); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements), Arg.Is(cancellationToken)); } @@ -83,14 +83,14 @@ public class CheckPathExistsEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return ErrorOrFactory.From(new PathExistsResponse(true)); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs index 3ab57ee1..cbc83e0c 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs @@ -1,12 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CombinePath; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -24,7 +23,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class CombinePathEndpointTests { - private readonly ISender _mockSender; + private readonly ICommandHandler> _mockHandler; private readonly CombinePathEndpoint _sut; private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; private readonly CombinePathRequestFixture _combinePathRequestFixture; @@ -34,8 +33,8 @@ public class CombinePathEndpointTests /// public CombinePathEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); _pathSegmentResponseFixture = new PathSegmentResponseFixture(); _combinePathRequestFixture = new CombinePathRequestFixture(); } @@ -47,7 +46,7 @@ public class CombinePathEndpointTests CombinePathRequest request = _combinePathRequestFixture.Create("C:\\Users", "TestUser"); CancellationToken cancellationToken = CancellationToken.None; PathSegmentResponse expectedResponse = _pathSegmentResponseFixture.Create(); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -59,13 +58,13 @@ public class CombinePathEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange CombinePathRequest request = _combinePathRequestFixture.Create("InvalidPath", "TestUser"); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("Path.NotFound", "The requested path was not found."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -85,13 +84,13 @@ public class CombinePathEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() { // Arrange CombinePathRequest request = _combinePathRequestFixture.Create("InvalidPath", "TestUser"); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -111,19 +110,19 @@ public class CombinePathEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendCombinePathCommandToMediator() + public async Task ExecuteAsync_WhenCalled_ShouldSendCombinePathCommandToHandler() { // Arrange CombinePathRequest request = _combinePathRequestFixture.Create("C:\\Users", "TestUser"); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.Create())); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(c => c.OriginalPath == request.OriginalPath && c.NewPath == request.NewPath), Arg.Is(cancellationToken)); } @@ -137,14 +136,14 @@ public class CombinePathEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return ErrorOrFactory.From(_pathSegmentResponseFixture.Create()); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs index c7bc3564..ec7c18f5 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathParent; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -26,7 +26,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class GetPathParentEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler>> _mockHandler; private readonly GetPathParentEndpoint _sut; private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; private readonly GetPathParentRequestFixture _getPathParentRequestFixture; @@ -36,8 +36,8 @@ public class GetPathParentEndpointTests /// public GetPathParentEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); _pathSegmentResponseFixture = new PathSegmentResponseFixture(); _getPathParentRequestFixture = new GetPathParentRequestFixture(); } @@ -49,7 +49,7 @@ public class GetPathParentEndpointTests GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser"); CancellationToken cancellationToken = CancellationToken.None; IEnumerable expectedResponse = _pathSegmentResponseFixture.CreateMany(); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -61,13 +61,13 @@ public class GetPathParentEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser"); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("Path.NotFound", "The requested path was not found."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -87,13 +87,13 @@ public class GetPathParentEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() { // Arrange GetPathParentRequest request = _getPathParentRequestFixture.Create(@"InvalidPath"); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -113,19 +113,19 @@ public class GetPathParentEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathParentQueryToMediator() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathParentQueryToHandler() { // Arrange GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser"); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.CreateMany().AsEnumerable())); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send(Arg.Is(q => q.Path == request.Path), Arg.Is(cancellationToken)); + await _mockHandler.Received(1).HandleAsync(Arg.Is(q => q.Path == request.Path), Arg.Is(cancellationToken)); } [Fact] @@ -137,14 +137,14 @@ public class GetPathParentEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return ErrorOrFactory.From(_pathSegmentResponseFixture.CreateMany().AsEnumerable()); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs index 15649064..96ad81fb 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -24,7 +24,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class GetPathRootEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler> _mockHandler; private readonly GetPathRootEndpoint _sut; private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; private readonly GetPathRootRequestFixture _getPathRootRequestFixture; @@ -34,8 +34,8 @@ public class GetPathRootEndpointTests /// public GetPathRootEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); _pathSegmentResponseFixture = new PathSegmentResponseFixture(); _getPathRootRequestFixture = new GetPathRootRequestFixture(); } @@ -47,7 +47,7 @@ public class GetPathRootEndpointTests GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser"); CancellationToken cancellationToken = CancellationToken.None; PathSegmentResponse expectedResponse = _pathSegmentResponseFixture.Create(); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -59,13 +59,13 @@ public class GetPathRootEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser"); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("Path.NotFound", "The requested path was not found."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -85,13 +85,13 @@ public class GetPathRootEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() { // Arrange GetPathRootRequest request = _getPathRootRequestFixture.Create(@"InvalidPath"); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -111,19 +111,19 @@ public class GetPathRootEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathRootQueryToMediator() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathRootQueryToHandler() { // Arrange GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser"); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.Create())); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send(Arg.Is(q => q.Path == request.Path), Arg.Is(cancellationToken)); + await _mockHandler.Received(1).HandleAsync(Arg.Is(q => q.Path == request.Path), Arg.Is(cancellationToken)); } [Fact] @@ -135,14 +135,14 @@ public class GetPathRootEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return ErrorOrFactory.From(_pathSegmentResponseFixture.Create()); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs index fd7c3a3c..39d4baf2 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSeparator; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -22,7 +22,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class GetPathSeparatorEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler _mockHandler; private readonly GetPathSeparatorEndpoint _sut; private readonly PathSeparatorResponseFixture _pathSeparatorResponseFixture; @@ -31,8 +31,8 @@ public class GetPathSeparatorEndpointTests /// public GetPathSeparatorEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>(); + _sut = Factory.Create(_mockHandler); _pathSeparatorResponseFixture = new PathSeparatorResponseFixture(); } @@ -42,7 +42,7 @@ public class GetPathSeparatorEndpointTests // Arrange CancellationToken cancellationToken = CancellationToken.None; PathSeparatorResponse expectedResponse = _pathSeparatorResponseFixture.Create(); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedResponse); // Act @@ -54,18 +54,18 @@ public class GetPathSeparatorEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathSeparatorQueryToMediator() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathSeparatorQueryToHandler() { // Arrange CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(_pathSeparatorResponseFixture.Create()); // Act await _sut.ExecuteAsync(cancellationToken); // Assert - await _mockSender.Received(1).Send(Arg.Any(), Arg.Is(cancellationToken)); + await _mockHandler.Received(1).HandleAsync(Arg.Any(), Arg.Is(cancellationToken)); } [Fact] @@ -76,14 +76,14 @@ public class GetPathSeparatorEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return _pathSeparatorResponseFixture.Create(); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs index 5c8d1ec2..3eadf322 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs @@ -1,12 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.SplitPath; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -26,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class SplitPathEndpointTests { - private readonly ISender _mockSender; + private readonly ICommandHandler>> _mockHandler; private readonly SplitPathEndpoint _sut; private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; private readonly SplitPathRequestFixture _splitPathRequestFixture; @@ -36,8 +35,8 @@ public class SplitPathEndpointTests /// public SplitPathEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); _pathSegmentResponseFixture = new PathSegmentResponseFixture(); _splitPathRequestFixture = new SplitPathRequestFixture(); } @@ -49,7 +48,7 @@ public class SplitPathEndpointTests SplitPathRequest request = _splitPathRequestFixture.Create(@"C:\Users\TestUser\Documents"); CancellationToken cancellationToken = CancellationToken.None; IEnumerable expectedResponse = _pathSegmentResponseFixture.CreateMany(); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -61,13 +60,13 @@ public class SplitPathEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange SplitPathRequest request = _splitPathRequestFixture.Create(@"InvalidPath"); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -88,19 +87,19 @@ public class SplitPathEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendSplitPathCommandToMediator() + public async Task ExecuteAsync_WhenCalled_ShouldSendSplitPathCommandToHandler() { // Arrange SplitPathRequest request = _splitPathRequestFixture.Create(@"C:\Users\TestUser\Documents"); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.CreateMany().AsEnumerable())); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(c => c.Path == request.Path), Arg.Is(cancellationToken)); } @@ -114,8 +113,8 @@ public class SplitPathEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; @@ -124,7 +123,7 @@ public class SplitPathEndpointTests { _pathSegmentResponseFixture.Create() }.AsEnumerable()); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs index 101f23a4..3cd52a83 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs @@ -1,13 +1,15 @@ #region ========================================================================= USING ===================================================================================== +using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.ValidatePath; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -23,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class ValidatePathEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler> _mockHandler; private readonly ValidatePathEndpoint _sut; private readonly ValidatePathRequestFixture _validatePathRequestFixture; @@ -32,8 +34,8 @@ public class ValidatePathEndpointTests /// public ValidatePathEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); _validatePathRequestFixture = new ValidatePathRequestFixture(); } @@ -44,7 +46,7 @@ public class ValidatePathEndpointTests ValidatePathRequest request = _validatePathRequestFixture.Create(@"C:\Users\TestUser\Documents"); CancellationToken cancellationToken = CancellationToken.None; PathValidResponse expectedResponse = new(true); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedResponse); // Act @@ -56,23 +58,49 @@ public class ValidatePathEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendValidatePathQueryToMediator() + public async Task ExecuteAsync_WhenCalled_ShouldSendValidatePathQueryToHandler() { // Arrange ValidatePathRequest request = _validatePathRequestFixture.Create(@"C:\Users\TestUser\Documents"); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(new PathValidResponse(true)); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(q => q.Path == request.Path), Arg.Is(cancellationToken)); } + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + ValidatePathRequest request = _validatePathRequestFixture.Create(@"C:\Users\TestUser\Documents"); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "The provided path is invalid." }, validationProblemDetails.Errors["Path.Invalid"]); + } + [Fact] public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { @@ -82,14 +110,14 @@ public class ValidatePathEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return new PathValidResponse(true); - }, callInfo.Arg()))); + return ErrorOrFactory.From(new PathValidResponse(true)); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs index b57987e9..9fd3fcfd 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; using Lumina.Presentation.Api.Common.Utilities; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -25,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class GetThumbnailEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler> _mockHandler; private readonly GetThumbnailEndpoint _sut; private readonly GetThumbnailRequestFixture _getThumbnailRequestFixture; @@ -34,8 +34,8 @@ public class GetThumbnailEndpointTests /// public GetThumbnailEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); _getThumbnailRequestFixture = new GetThumbnailRequestFixture(); } @@ -46,7 +46,7 @@ public class GetThumbnailEndpointTests GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/file.jpg", 80); CancellationToken cancellationToken = CancellationToken.None; ThumbnailResponse expectedResponse = ThumbnailResponseFixture.CreateThumbnailResponse(); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -59,13 +59,13 @@ public class GetThumbnailEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/nonexistent/file.jpg", 80); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("Thumbnail.NotFound", "The requested thumbnail was not found."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -85,13 +85,13 @@ public class GetThumbnailEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() { // Arrange GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/nonexistent/file.jpg", 80); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -116,14 +116,14 @@ public class GetThumbnailEndpointTests // Arrange GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/file.jpg", 80); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(ThumbnailResponseFixture.CreateThumbnailResponse())); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send(Arg.Is(q => q.Path == request.Path && q.Quality == request.Quality), Arg.Is(cancellationToken)); + await _mockHandler.Received(1).HandleAsync(Arg.Is(q => q.Path == request.Path && q.Quality == request.Quality), Arg.Is(cancellationToken)); } [Fact] @@ -135,14 +135,14 @@ public class GetThumbnailEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return ErrorOrFactory.From(ThumbnailResponseFixture.CreateThumbnailResponse()); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs index 706bc78a..53e94a62 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; using Lumina.Contracts.Responses.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -21,7 +21,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.Applicati [ExcludeFromCodeCoverage] public class CheckInitializationEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler _mockHandler; private readonly CheckInitializationEndpoint _sut; /// @@ -29,8 +29,8 @@ public class CheckInitializationEndpointTests /// public CheckInitializationEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>(); + _sut = Factory.Create(_mockHandler); } [Fact] @@ -39,7 +39,7 @@ public class CheckInitializationEndpointTests // Arrange CancellationToken cancellationToken = CancellationToken.None; InitializationResponse expectedResponse = new(IsInitialized: true); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedResponse); // Act @@ -51,18 +51,18 @@ public class CheckInitializationEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendCheckInitializationQueryToMediator() + public async Task ExecuteAsync_WhenCalled_ShouldSendCheckInitializationQueryToHandler() { // Arrange CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(new InitializationResponse(IsInitialized: true)); // Act await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Any(), Arg.Is(cancellationToken)); } @@ -75,14 +75,14 @@ public class CheckInitializationEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return new InitializationResponse(IsInitialized: true); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(new EmptyRequest(), cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs index 56a72021..25381421 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; using Lumina.Contracts.Requests.Authentication; @@ -8,7 +8,6 @@ using Lumina.Contracts.Responses.Authentication; using Lumina.Contracts.Responses.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.ApplicationSetup.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -26,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.Applicati [ExcludeFromCodeCoverage] public class SetupApplicationEndpointTests { - private readonly ISender _mockSender; + private readonly ICommandHandler> _mockHandler; private readonly SetupApplicationEndpoint _sut; private readonly RegistrationRequestFixture _registrationRequestFixture; @@ -35,8 +34,8 @@ public class SetupApplicationEndpointTests /// public SetupApplicationEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); _registrationRequestFixture = new RegistrationRequestFixture(); } @@ -47,7 +46,7 @@ public class SetupApplicationEndpointTests RegistrationRequest request = _registrationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; RegistrationResponse expectedResponse = new(Guid.NewGuid(), "testUser", "TOTP123"); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -60,13 +59,13 @@ public class SetupApplicationEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange RegistrationRequest request = _registrationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Conflict("Registration.Failed", "The application is already initialized."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -91,14 +90,14 @@ public class SetupApplicationEndpointTests // Arrange RegistrationRequest request = _registrationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123"))); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(cmd => cmd.Username == request.Username && cmd.Password == request.Password && @@ -116,14 +115,14 @@ public class SetupApplicationEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123")); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs index 22ccf235..c72a5ce6 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs @@ -1,12 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.ChangePassword; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -24,7 +23,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authe [ExcludeFromCodeCoverage] public class ChangePasswordEndpointTests { - private readonly ISender _mockSender; + private readonly ICommandHandler> _mockHandler; private readonly ChangePasswordEndpoint _sut; private readonly ChangePasswordRequestFixture _changePasswordRequestFixture; @@ -33,8 +32,8 @@ public class ChangePasswordEndpointTests /// public ChangePasswordEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); _changePasswordRequestFixture = new ChangePasswordRequestFixture(); } @@ -45,7 +44,7 @@ public class ChangePasswordEndpointTests ChangePasswordRequest request = _changePasswordRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; ChangePasswordResponse expectedResponse = new(IsPasswordChanged: true); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -57,13 +56,13 @@ public class ChangePasswordEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange ChangePasswordRequest request = _changePasswordRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("Password.Invalid", "The current password is incorrect."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -87,14 +86,14 @@ public class ChangePasswordEndpointTests // Arrange ChangePasswordRequest request = _changePasswordRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(new ChangePasswordResponse(true))); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(cmd => cmd.Username == request.Username && cmd.CurrentPassword == request.CurrentPassword && @@ -112,14 +111,14 @@ public class ChangePasswordEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return ErrorOrFactory.From(new ChangePasswordResponse(true)); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs index b99e15aa..e366677f 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUsers; using Lumina.Contracts.Responses.UsersManagement.Users; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.GetUsers; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -23,15 +23,15 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authe [ExcludeFromCodeCoverage] public class GetUsersEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler>> _mockHandler; private readonly GetUsersEndpoint _sut; /// /// Initializes a new instance of the class. /// public GetUsersEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); } [Fact] @@ -43,7 +43,7 @@ public class GetUsersEndpointTests [ new UserResponse(Guid.NewGuid(), "testUser", DateTime.UtcNow, null) ]; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -55,12 +55,12 @@ public class GetUsersEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("Users.NotFound", "No users found."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -84,16 +84,14 @@ public class GetUsersEndpointTests { // Arrange CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(new ValueTask>>( - ErrorOrFactory.From(Array.Empty() as IEnumerable) - )); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(Array.Empty() as IEnumerable)); // Act await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Any(), Arg.Is(cancellationToken)); } @@ -106,16 +104,14 @@ public class GetUsersEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(info => new ValueTask>>( - Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(Array.Empty() as IEnumerable); - }, info.Arg()) - )); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(Array.Empty() as IEnumerable); + }, info.Arg())); // Act Task operationTask = _sut.ExecuteAsync(new EmptyRequest(), cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs index 5e1d26a2..06e08639 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Login; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.Login.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -24,7 +24,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authe [ExcludeFromCodeCoverage] public class LoginEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler> _mockHandler; private readonly LoginEndpoint _sut; private readonly LoginRequestFixture _loginRequestFixture; @@ -33,8 +33,8 @@ public class LoginEndpointTests /// public LoginEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); _loginRequestFixture = new LoginRequestFixture(); } @@ -45,7 +45,7 @@ public class LoginEndpointTests LoginRequest request = _loginRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; LoginResponse expectedResponse = new(Guid.NewGuid(), "testUser", "jwt_token", true); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -57,13 +57,13 @@ public class LoginEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange LoginRequest request = _loginRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("Login.Failed", "Invalid username or password."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -87,14 +87,14 @@ public class LoginEndpointTests // Arrange LoginRequest request = _loginRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(new LoginResponse(Guid.NewGuid(), "testUser", "jwt_token", true))); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(q => q.Username == request.Username && q.Password == request.Password && @@ -111,14 +111,14 @@ public class LoginEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return ErrorOrFactory.From(new LoginResponse(Guid.NewGuid(), "testUser", "jwt_token", true)); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs index 415adac1..51cfc579 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -1,12 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -24,7 +23,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authe [ExcludeFromCodeCoverage] public class RecoverPasswordEndpointTests { - private readonly ISender _mockSender; + private readonly ICommandHandler> _mockHandler; private readonly RecoverPasswordEndpoint _sut; private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture; @@ -33,8 +32,8 @@ public class RecoverPasswordEndpointTests /// public RecoverPasswordEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); _recoverPasswordRequestFixture = new RecoverPasswordRequestFixture(); } @@ -45,7 +44,7 @@ public class RecoverPasswordEndpointTests RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; RecoverPasswordResponse expectedResponse = new(IsPasswordReset: true); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -57,13 +56,13 @@ public class RecoverPasswordEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("Recovery.Failed", "Invalid username or TOTP code."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -87,14 +86,14 @@ public class RecoverPasswordEndpointTests // Arrange RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(new RecoverPasswordResponse(true))); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(cmd => cmd.Username == request.Username && cmd.TotpCode == request.TotpCode), @@ -110,14 +109,14 @@ public class RecoverPasswordEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return ErrorOrFactory.From(new RecoverPasswordResponse(true)); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs index acee0fca..36a54655 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -1,12 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.ApplicationSetup.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -24,7 +23,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authe [ExcludeFromCodeCoverage] public class RegisterEndpointTests { - private readonly ISender _mockSender; + private readonly ICommandHandler> _mockHandler; private readonly RegisterEndpoint _sut; private readonly RegistrationRequestFixture _registrationRequestFixture; @@ -33,8 +32,8 @@ public class RegisterEndpointTests /// public RegisterEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); _registrationRequestFixture = new RegistrationRequestFixture(); } @@ -45,7 +44,7 @@ public class RegisterEndpointTests RegistrationRequest request = _registrationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; RegistrationResponse expectedResponse = new(Guid.NewGuid(), "testUser", "TOTP123"); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -58,13 +57,13 @@ public class RegisterEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange RegistrationRequest request = _registrationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("Registration.Failed", "Username is already taken."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -88,14 +87,14 @@ public class RegisterEndpointTests // Arrange RegistrationRequest request = _registrationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123"))); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(cmd => cmd.Username == request.Username && cmd.Password == request.Password && @@ -113,14 +112,14 @@ public class RegisterEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); return ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123")); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs index f2fd1324..11a20c0a 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.GetAuthorization; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authorization.GetAuthorization.Fixtures; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -27,7 +27,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Autho [ExcludeFromCodeCoverage] public class GetAuthorizationEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler> _mockHandler; private readonly GetAuthorizationEndpoint _sut; /// @@ -35,8 +35,8 @@ public class GetAuthorizationEndpointTests /// public GetAuthorizationEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); } [Fact] @@ -50,7 +50,7 @@ public class GetAuthorizationEndpointTests "Admin", new HashSet { AuthorizationPermission.CanViewUsers }); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -62,14 +62,14 @@ public class GetAuthorizationEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange GetAuthorizationRequest request = GetAuthorizationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Unauthorized("Authorization.Failed", "User is not authorized."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -95,7 +95,7 @@ public class GetAuthorizationEndpointTests GetAuthorizationRequest request = GetAuthorizationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(new AuthorizationResponse( request.UserId!.Value, string.Empty, @@ -106,7 +106,7 @@ public class GetAuthorizationEndpointTests await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(query => query.UserId == request.UserId), Arg.Is(cancellationToken)); @@ -121,8 +121,8 @@ public class GetAuthorizationEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>(Task.Run(async () => + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; @@ -132,7 +132,7 @@ public class GetAuthorizationEndpointTests string.Empty, new HashSet().ToHashSet() )); - }, callInfo.Arg()))); + }, callInfo.Arg())); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs index 37df1cf3..d44fca3f 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.GetUserPermissions; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -25,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Autho [ExcludeFromCodeCoverage] public class GetUserPermissionsEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler>> _mockHandler; private readonly GetUserPermissionsEndpoint _sut; /// @@ -33,8 +33,8 @@ public class GetUserPermissionsEndpointTests /// public GetUserPermissionsEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); } [Fact] @@ -48,7 +48,7 @@ public class GetUserPermissionsEndpointTests new PermissionResponse(Guid.NewGuid(), AuthorizationPermission.CanViewUsers), new PermissionResponse(Guid.NewGuid(), AuthorizationPermission.CanDeleteUsers) ]; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -60,13 +60,13 @@ public class GetUserPermissionsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange GetUserPermissionsRequest request = new(Guid.NewGuid()); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("User.Permissions.NotFound", "User permissions not found."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -92,16 +92,14 @@ public class GetUserPermissionsEndpointTests Guid userId = Guid.NewGuid(); GetUserPermissionsRequest request = new(userId); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(new ValueTask>>( - ErrorOrFactory.From(Array.Empty() as IEnumerable) - )); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(Array.Empty() as IEnumerable)); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(cmd => cmd.UserId == request.UserId), Arg.Is(cancellationToken)); } @@ -114,16 +112,14 @@ public class GetUserPermissionsEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(info => new ValueTask>>( - Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(Array.Empty() as IEnumerable); - }, info.Arg()) - )); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(Array.Empty() as IEnumerable); + }, info.Arg())); // Act Task operationTask = _sut.ExecuteAsync(new GetUserPermissionsRequest(Guid.NewGuid()), cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs index 121ba8b9..dfc6627d 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.GetUserRole; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -23,7 +23,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Autho [ExcludeFromCodeCoverage] public class GetUserRoleEndpointTests { - private readonly ISender _mockSender; + private readonly IQueryHandler> _mockHandler; private readonly GetUserRoleEndpoint _sut; /// @@ -31,8 +31,8 @@ public class GetUserRoleEndpointTests /// public GetUserRoleEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); } [Fact] @@ -42,8 +42,8 @@ public class GetUserRoleEndpointTests GetUserRoleRequest request = new(Guid.NewGuid()); CancellationToken cancellationToken = CancellationToken.None; RoleResponse expectedResponse = new(Guid.NewGuid(), "Admin"); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -54,13 +54,13 @@ public class GetUserRoleEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange GetUserRoleRequest request = new(Guid.NewGuid()); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("User.Role.NotFound", "User role not found."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -86,14 +86,14 @@ public class GetUserRoleEndpointTests Guid userId = Guid.NewGuid(); GetUserRoleRequest request = new(userId); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(new RoleResponse(Guid.NewGuid(), "Admin"))); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(new RoleResponse(Guid.NewGuid(), "Admin"))); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(cmd => cmd.UserId == request.UserId), Arg.Is(cancellationToken)); } @@ -106,16 +106,14 @@ public class GetUserRoleEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(info => new ValueTask>( - Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new RoleResponse(Guid.NewGuid(), "Admin")); - }, info.Arg()) - )); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(new RoleResponse(Guid.NewGuid(), "Admin")); + }, info.Arg())); // Act Task operationTask = _sut.ExecuteAsync(new GetUserRoleRequest(Guid.NewGuid()), cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs index d14f1a4d..9b4235c7 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs @@ -1,12 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FastEndpoints; +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.UpdateUserRoleAndPermissions; -using Mediator; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -26,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Autho [ExcludeFromCodeCoverage] public class UpdateUserRoleAndPermissionsEndpointTests { - private readonly ISender _mockSender; + private readonly ICommandHandler> _mockHandler; private readonly UpdateUserRoleAndPermissionsEndpoint _sut; /// @@ -34,8 +33,8 @@ public class UpdateUserRoleAndPermissionsEndpointTests /// public UpdateUserRoleAndPermissionsEndpointTests() { - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); } [Fact] @@ -53,7 +52,7 @@ public class UpdateUserRoleAndPermissionsEndpointTests "Admin", new HashSet { AuthorizationPermission.CanViewUsers } ); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(expectedResponse)); // Act @@ -65,7 +64,7 @@ public class UpdateUserRoleAndPermissionsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange UpdateUserRoleAndPermissionsRequest request = new( @@ -75,7 +74,7 @@ public class UpdateUserRoleAndPermissionsEndpointTests ); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("Authorization.Update.Failed", "Failed to update user role and permissions."); - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); // Act @@ -104,7 +103,7 @@ public class UpdateUserRoleAndPermissionsEndpointTests [Guid.NewGuid()] ); CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(new AuthorizationResponse( Guid.NewGuid(), "Admin", @@ -115,7 +114,7 @@ public class UpdateUserRoleAndPermissionsEndpointTests await _sut.ExecuteAsync(request, cancellationToken); // Assert - await _mockSender.Received(1).Send( + await _mockHandler.Received(1).HandleAsync( Arg.Is(cmd => cmd.UserId == request.UserId && cmd.RoleId == request.RoleId && @@ -131,20 +130,18 @@ public class UpdateUserRoleAndPermissionsEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(info => new ValueTask>( - Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new AuthorizationResponse( - Guid.NewGuid(), - "Admin", - new HashSet { AuthorizationPermission.CanViewUsers } - )); - }, info.Arg()) - )); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(new AuthorizationResponse( + Guid.NewGuid(), + "Admin", + new HashSet { AuthorizationPermission.CanViewUsers } + )); + }, info.Arg())); // Act Task operationTask = _sut.ExecuteAsync(