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/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index 2887a02b..4b6c6e71 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -1,7 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; -using Lumina.Application.Common.Behaviors; -using Mediator; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; @@ -25,44 +22,39 @@ public static class ApplicationLayerServices /// The updated . public static IServiceCollection AddApplicationLayerServices(this IServiceCollection services) { - // register Mediator + // register the Mediator publisher used for publishing domain events services.AddMediator(options => { options.ServiceLifetime = ServiceLifetime.Scoped; }); - // register the validation behavior - services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); - - // register fluent validators - services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly); - - Type[] handlers = + Type[] handlerContractTypes = [ typeof(CQRS.ICommandHandler<,>), typeof(CQRS.IQueryHandler<,>), typeof(Infrastructure.Validation.IValidator<>), ]; - IEnumerable types = Assembly.GetExecutingAssembly() - .GetTypes() - .Where(type => !type.IsInterface && !type.IsAbstract); + IEnumerable concreteTypes = Assembly.GetExecutingAssembly() + .GetTypes() + .Where(type => !type.IsInterface && !type.IsAbstract && !type.IsGenericTypeDefinition); - var registrations = types - .SelectMany(type => type.GetInterfaces(), - (implementation, service) => new { Service = service, Implmentation = implementation }) - .Where(type => type.Service.IsGenericType && handlers.Contains(type.Service.GetGenericTypeDefinition())); + 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 registrations) + foreach (var registration in handlerRegistrations) { - if (!services.Any(service => service.ServiceType == registration.Service)) - { - if (registration.Service.GetGenericTypeDefinition() == typeof(Infrastructure.Validation.IValidator<>)) - services.AddSingleton(registration.Service, registration.Implmentation); - else - services.AddScoped(registration.Service, registration.Implmentation); - } + if (services.Any(service => service.ServiceType == registration.Contract)) + continue; + + 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 index 275cc1a7..cb40c867 100644 --- a/src/Lumina.Application/Common/Infrastructure/Validation/AbstractValidator.cs +++ b/src/Lumina.Application/Common/Infrastructure/Validation/AbstractValidator.cs @@ -20,7 +20,7 @@ public abstract class AbstractValidator : IValidator /// 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. - protected IRuleBuilder RuleFor(Func propertySelector) + public IRuleBuilder RuleFor(Func propertySelector) { ValidationRule rule = new(propertySelector); _rules.Add(rule); @@ -33,7 +33,7 @@ public abstract class AbstractValidator : IValidator /// 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. - protected IRuleBuilder RuleForEach(Func?> collectionSelector) + public IRuleBuilder RuleForEach(Func?> collectionSelector) { ValidationRuleForEach rule = new(collectionSelector); _rules.Add(rule); diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs b/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs index 8da4fcfb..771dcf73 100644 --- a/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs +++ b/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs @@ -19,6 +19,13 @@ public interface IRuleBuilder /// 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. /// @@ -32,4 +39,11 @@ public interface IRuleBuilder /// 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/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 index bc9352f8..fc07a557 100644 --- a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs +++ b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs @@ -14,10 +14,28 @@ namespace Lumina.Application.Common.Infrastructure.Validation; 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 Error error = Error.Validation(); + 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. /// @@ -35,6 +53,25 @@ internal sealed class ValidationRule : IValidationRule 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; } @@ -56,7 +93,35 @@ internal sealed class ValidationRule : IValidationRuleThe current instance for method chaining. public IRuleBuilder WithError(Error error) { - this.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; } @@ -64,7 +129,7 @@ internal sealed class ValidationRule : IValidationRule /// The request instance to validate. - /// The if any predicate fails; empty if the rule passes. + /// 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. @@ -73,13 +138,19 @@ internal sealed class ValidationRule : IValidationRule predicate in _predicates) - { - if (!predicate(value)) - { - yield return error; - yield break; - } - } + // 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 index 560b2712..4a5e08cc 100644 --- a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs +++ b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs @@ -15,8 +15,13 @@ internal sealed class ValidationRuleForEach : IValidationRule?> _collectionSelector; private readonly List> _predicates = []; - private Error error = Error.Validation(); + 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. @@ -35,6 +40,21 @@ internal sealed class ValidationRuleForEach : IValidationRule 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; } @@ -56,7 +76,26 @@ internal sealed class ValidationRuleForEach : IValidationRuleThe current instance for method chaining. public IRuleBuilder WithError(Error error) { - this.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; } @@ -64,7 +103,7 @@ internal sealed class ValidationRuleForEach : IValidationRule /// The request instance to validate. - /// One per item that fails a predicate; empty if every item passes. + /// 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. @@ -77,14 +116,17 @@ internal sealed class ValidationRuleForEach : IValidationRule predicate in _predicates) - { - if (!predicate(item)) - { - yield return error; - break; - } - } + 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 index 42b96f5f..86912552 100644 --- a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs +++ b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs @@ -1,7 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using System; -using System.Collections.Generic; +using System.Collections; +using System.Text.RegularExpressions; #endregion namespace Lumina.Application.Common.Utilities; @@ -38,6 +39,33 @@ public static class ValidatorUtilities 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. /// @@ -50,13 +78,54 @@ public static class ValidatorUtilities 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 - /// or - /// to also reject empty values. + /// to also reject empty values. /// /// The type of the request being validated. /// The type of the property being validated. @@ -68,43 +137,27 @@ public static class ValidatorUtilities } /// - /// Defines a validation rule that ensures the string property is not empty or consisting only of white-space characters. + /// Defines a validation rule that ensures the property is not empty. /// /// - /// If the property is , this rule passes (use to check for missing values). + /// 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) + public static IRuleBuilder NotEmpty(this IRuleBuilder ruleBuilder) { - return ruleBuilder.Must(value => value is null || value.Trim().Length > 0); - } - - /// - /// Defines a validation rule that ensures the List property is not empty. - /// - /// - /// If the property is , this rule passes (use to check for missing values). - /// - /// The type of the request being validated. - /// The type of the items in the list being validated. - /// The rule builder instance. - /// The current instance for method chaining. - public static IRuleBuilder> NotEmpty(this IRuleBuilder> ruleBuilder) - { - return ruleBuilder.Must(value => value is null || value.Count > 0); - } - - /// - /// Defines a validation rule that ensures the property is not . - /// - /// The type of the request being validated. - /// The rule builder instance. - /// The current instance for method chaining. - public static IRuleBuilder NotEmpty(this IRuleBuilder ruleBuilder) - { - return ruleBuilder.Must(value => value != Guid.Empty); + 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 + }); } /// @@ -130,4 +183,144 @@ public static class ValidatorUtilities { 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/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/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..88e68f0e 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,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.ValidatePat /// /// Handler for the query to validate a file system path. /// -public class ValidatePathQueryHandler : IRequestHandler +public class ValidatePathQueryHandler : IQueryHandler { private readonly IPathService _pathService; @@ -27,13 +27,13 @@ public class ValidatePathQueryHandler : IRequestHandler /// 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. /// - public ValueTask Handle(ValidatePathQuery request, CancellationToken cancellationToken) + public Task HandleAsync(ValidatePathQuery query, CancellationToken cancellationToken) { - return ValueTask.FromResult(new PathValidResponse(_pathService.IsValidPath(request.Path!))); + return Task.FromResult(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/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 23264fd5..4f750cb6 100644 --- a/src/Lumina.Application/Lumina.Application.csproj +++ b/src/Lumina.Application/Lumina.Application.csproj @@ -20,8 +20,6 @@ - - runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 1e6e975e..19232202 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,6 +7,7 @@ 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.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; @@ -35,6 +35,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; +using System.Linq; using System.Reflection; #endregion @@ -55,8 +56,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(); 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/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/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/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/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..986aed6a 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,11 @@ #region ========================================================================= USING ===================================================================================== -using FastEndpoints; +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 +18,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 +34,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 +47,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); + PathValidResponse result = await _validatePathQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return TypedResults.Ok(result); } } 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 624f6344..824a6c6f 100644 --- a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj +++ b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj @@ -25,10 +25,6 @@ - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - @@ -62,9 +58,4 @@ - - - - $(NoWarn);CS0436 - 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/Setup/ValidatorTestExtensions.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs index f45abf46..bc7b3506 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs @@ -30,7 +30,7 @@ public static class ValidatorTestExtensions /// 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.Code == expectedError.Code); + Assert.DoesNotContain(errors, error => error.Description == expectedError.Description); } /// @@ -40,7 +40,7 @@ public static class ValidatorTestExtensions /// The error that should be present in the validation results. public static void ShouldHaveValidationError(this List errors, Error expectedError) { - Assert.Contains(errors, error => error.Code == expectedError.Code); + Assert.Contains(errors, error => error.Description == expectedError.Description); } /// 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..d275b576 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 @@ -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); @@ -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); @@ -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); @@ -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/AddRoleCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs index c7d0e932..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,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FluentValidation.TestHelper; using Lumina.Application.Common.Errors; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; using Lumina.Application.UnitTests.Common.Setup; 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..fed2d153 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,7 +53,8 @@ public class DeleteRoleCommandHandlerTests _sut = new DeleteRoleCommandHandler( _mockAuthorizationService, _mockCurrentUserService, - _mockUnitOfWork); + _mockUnitOfWork, + mockValidator); } [Fact] @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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..23be7d06 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,7 +56,8 @@ public class UpdateRoleCommandHandlerTests _sut = new UpdateRoleCommandHandler( _mockAuthorizationService, _mockCurrentUserService, - _mockUnitOfWork); + _mockUnitOfWork, + mockValidator); } [Fact] @@ -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); @@ -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); @@ -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); @@ -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); @@ -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/GetRolePermissionsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs index 2028d4e7..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,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using FluentValidation.TestHelper; using Lumina.Application.Common.Errors; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; using Lumina.Application.UnitTests.Common.Setup; 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..a31a75eb 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 @@ -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); @@ -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); @@ -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..c94df15f 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,7 +38,10 @@ 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(); } @@ -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); @@ -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); @@ -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); @@ -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..7c50efd7 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 @@ -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); @@ -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); @@ -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..947e5798 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 @@ -47,7 +47,7 @@ public class GetFileSystemQueryHandlerTests _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); @@ -63,7 +63,7 @@ public class GetFileSystemQueryHandlerTests _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); @@ -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); @@ -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..acf43b42 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,7 +38,10 @@ 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(); } @@ -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); @@ -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); @@ -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); @@ -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..98e23f0d 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,7 +38,10 @@ 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(); } @@ -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); @@ -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); @@ -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); @@ -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..07f922f1 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,7 +32,10 @@ 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] @@ -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); @@ -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); @@ -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..07b61504 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,7 +38,10 @@ 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(); } @@ -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); @@ -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); @@ -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..d4e952ff 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,7 +28,10 @@ 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] @@ -38,7 +42,7 @@ public class CheckPathExistsQueryHandlerTests _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); @@ -54,7 +58,7 @@ public class CheckPathExistsQueryHandlerTests _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); @@ -70,7 +74,7 @@ public class CheckPathExistsQueryHandlerTests _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); @@ -86,7 +90,7 @@ public class CheckPathExistsQueryHandlerTests _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); @@ -102,7 +106,7 @@ public class CheckPathExistsQueryHandlerTests _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); @@ -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..ed9701d2 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,7 +34,10 @@ 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(); } @@ -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); @@ -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); @@ -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..df6c5492 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,7 +31,10 @@ 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(); } @@ -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); @@ -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); @@ -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..a4c53773 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 @@ -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); @@ -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..6a84d5ae 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 @@ -37,7 +37,7 @@ public class ValidatePathQueryHandlerTests _mockPathService.IsValidPath(query.Path!).Returns(true); // Act - PathValidResponse result = await _sut.Handle(query, CancellationToken.None); + PathValidResponse result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsValid); @@ -52,7 +52,7 @@ public class ValidatePathQueryHandlerTests _mockPathService.IsValidPath(query.Path!).Returns(false); // Act - PathValidResponse result = await _sut.Handle(query, CancellationToken.None); + PathValidResponse result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsValid); @@ -67,7 +67,7 @@ public class ValidatePathQueryHandlerTests _mockPathService.IsValidPath(Arg.Any()).Returns(false); // Act - PathValidResponse result = await _sut.Handle(query, CancellationToken.None); + PathValidResponse result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsValid); @@ -82,7 +82,7 @@ public class ValidatePathQueryHandlerTests _mockPathService.IsValidPath(Arg.Any()).Returns(false); // Act - PathValidResponse result = await _sut.Handle(query, CancellationToken.None); + PathValidResponse result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.False(result.IsValid); 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..d1d9d66a 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,7 +29,10 @@ 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] @@ -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); @@ -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); @@ -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..ef8a419b 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,7 +68,8 @@ public class SetupApplicationCommandHandlerTests _mockTotpTokenGenerator, _mockQRCodeGenerator, _mockDateTimeProvider, - _mockDataSeedService); + _mockDataSeedService, + mockValidator); } [Fact] @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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..e0d4a9aa 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 @@ -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); @@ -63,7 +63,7 @@ public class CheckInitializationQueryHandlerTests .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); @@ -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..bb324d37 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,7 +49,10 @@ 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(); } @@ -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); @@ -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); @@ -98,7 +102,7 @@ public class AddBookCommandHandlerTests 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); @@ -115,7 +119,7 @@ public class AddBookCommandHandlerTests 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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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..bfcac22c 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,7 +32,10 @@ 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] @@ -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..25b6d0db 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,7 +31,10 @@ 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] @@ -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); @@ -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..b4ac20f6 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,7 +30,10 @@ 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] @@ -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..7728c402 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 @@ -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); @@ -61,7 +61,7 @@ public class GetPluginsQueryHandlerTests .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..ad1a3282 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,9 +40,13 @@ public class ChangePasswordCommandHandlerTests _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + IValidator mockValidator = Substitute.For>(); + mockValidator.Validate(Arg.Any()) + .Returns([]); _sut = new ChangePasswordCommandHandler( _mockUnitOfWork, - _mockHashService); + _mockHashService, + mockValidator); } [Fact] @@ -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); @@ -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); @@ -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); @@ -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); @@ -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..54dc7db1 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,11 +45,15 @@ 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] @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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..37bd475b 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,13 +52,17 @@ 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] @@ -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); @@ -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); @@ -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); @@ -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); @@ -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..efe68b28 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 @@ -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); @@ -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); @@ -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..1770a602 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,13 +51,17 @@ 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] @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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..1446f44f 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,10 +61,14 @@ 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] @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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..7258a553 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,7 +34,10 @@ 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] @@ -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); @@ -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); @@ -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); @@ -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); @@ -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..db9300ae 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,10 +51,14 @@ 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] @@ -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); @@ -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); @@ -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); @@ -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..96b1f97e 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,10 +49,14 @@ 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] @@ -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); @@ -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); @@ -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); @@ -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); @@ -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/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..019b85bb 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 @@ -65,7 +65,7 @@ public class GetPermissionsEndpointTests // 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/DeleteRole/DeleteRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs index 2294a13d..11bff369 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 @@ -57,7 +56,7 @@ public class DeleteRoleEndpointTests 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/GetRoles/GetRolesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs index cabeba76..1dec0f66 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 @@ -61,7 +61,7 @@ public class GetRolesEndpointTests // 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..0a032355 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 @@ -67,7 +66,7 @@ public class UpdateRoleEndpointTests 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..e577f527 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 @@ -66,7 +66,7 @@ public class GetDirectoriesEndpointTests 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 @@ -92,7 +92,7 @@ public class GetDirectoriesEndpointTests 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 @@ -117,14 +117,14 @@ public class GetDirectoriesEndpointTests // 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..e9e9b779 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 @@ -62,7 +62,7 @@ public class GetDrivesEndpointTests // 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 @@ -86,14 +86,14 @@ public class GetDrivesEndpointTests { // 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..df170ab2 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 @@ -75,14 +75,14 @@ public class GetFileSystemTypeEndpointTests { // 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..f3053458 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 @@ -68,7 +68,7 @@ public class GetFilesEndpointTests 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 @@ -94,7 +94,7 @@ public class GetFilesEndpointTests 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..41cee5d6 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 @@ -69,7 +69,7 @@ public class GetTreeFilesEndpointTests 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 @@ -95,7 +95,7 @@ public class GetTreeFilesEndpointTests 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..ad359faa 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 @@ -62,14 +62,14 @@ public class CheckPathExistsEndpointTests // 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..f5979ee7 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 @@ -65,7 +64,7 @@ public class CombinePathEndpointTests 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 @@ -91,7 +90,7 @@ public class CombinePathEndpointTests 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 @@ -116,14 +115,14 @@ public class CombinePathEndpointTests // 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..63fe5b00 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 @@ -67,7 +67,7 @@ public class GetPathParentEndpointTests 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 @@ -93,7 +93,7 @@ public class GetPathParentEndpointTests 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 @@ -118,14 +118,14 @@ public class GetPathParentEndpointTests // 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..69c8fd28 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 @@ -65,7 +65,7 @@ public class GetPathRootEndpointTests 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 @@ -91,7 +91,7 @@ public class GetPathRootEndpointTests 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 @@ -116,14 +116,14 @@ public class GetPathRootEndpointTests // 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..0390c563 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 @@ -58,14 +58,14 @@ public class GetPathSeparatorEndpointTests { // 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..f5082467 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 @@ -67,7 +66,7 @@ public class SplitPathEndpointTests 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 @@ -93,14 +92,14 @@ public class SplitPathEndpointTests // 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..327f7109 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,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== 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 NSubstitute; @@ -23,7 +23,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 +32,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 +44,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 @@ -61,14 +61,14 @@ public class ValidatePathEndpointTests // 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)); } @@ -82,14 +82,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()))); + }, 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..7778f1c9 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 @@ -65,7 +65,7 @@ public class GetThumbnailEndpointTests 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 @@ -91,7 +91,7 @@ public class GetThumbnailEndpointTests 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..04d038c1 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 @@ -55,14 +55,14 @@ public class CheckInitializationEndpointTests { // 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..70ec7c6d 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 @@ -66,7 +65,7 @@ public class SetupApplicationEndpointTests 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..69cff8d3 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 @@ -63,7 +62,7 @@ public class ChangePasswordEndpointTests 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..ed1f4389 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 @@ -60,7 +60,7 @@ public class GetUsersEndpointTests // 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..8168dcd7 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 @@ -63,7 +63,7 @@ public class LoginEndpointTests 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..66b276e8 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 @@ -63,7 +62,7 @@ public class RecoverPasswordEndpointTests 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..c3727d3d 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 @@ -64,7 +63,7 @@ public class RegisterEndpointTests 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..009fb74e 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 @@ -69,7 +69,7 @@ public class GetAuthorizationEndpointTests 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..90cff0dc 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 @@ -66,7 +66,7 @@ public class GetUserPermissionsEndpointTests 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..89985b68 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); @@ -60,7 +60,7 @@ public class GetUserRoleEndpointTests 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..1ebf4845 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 @@ -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(