mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Merge pull request #142 from BinaryAlley/refactor/replace-mediatr-and-fluentvalidation-with-custom-implementations
Refactor/replace mediatr and fluentvalidation with custom implementations
This commit is contained in:
347 files changed
+5673
-3429
No files matched your search
+134
@@ -0,0 +1,134 @@
|
||||
# Architecture Decision Record (ADR): 0011 - Replace MediatR with Custom CQRS Abstractions
|
||||
|
||||
## Status
|
||||
|
||||
**Accepted** (2026-08-13)
|
||||
|
||||
## Context
|
||||
|
||||
The solution uses MediatR as a lightweight mediator to encapsulate command and query handling across the application layer. Following MediatR's shift to a commercial licensing model starting with .NET 8, continued use introduces an unacceptable external dependency on a paid third-party library for functionality that is entirely implementable in-house.
|
||||
|
||||
Key constraints that shaped this decision:
|
||||
|
||||
1. **Licensing Change**: MediatR became a commercial product for .NET 8+ projects, requiring a paid license for continued use in production systems.
|
||||
|
||||
2. **Narrow Usage Scope**: MediatR is used for command and query dispatching, with a single pipeline behavior (automatic application validation) and no stream requests. Its notification publishing is used for domain event publishing, which is outside the scope of this ADR and is replaced separately (see ADR-0013).
|
||||
|
||||
3. **Zero Abstraction Value at Scale**: With only a validation pipeline behavior registered, the command and query dispatching provides no runtime value beyond a dispatch indirection that can be replaced by direct handler injection. It actually hurts performance by runtime dispatching of handlers via reflection.
|
||||
|
||||
4. **Ownership and Transparency**: A custom implementation is fully owned, inspectable, and carries no transitive dependency risk or future licensing exposure.
|
||||
|
||||
## Decision
|
||||
|
||||
Replace MediatR with minimal, hand-written CQRS abstractions placed in `Lumina.Application.Common.CQRS`. Handlers are resolved directly via the .NET dependency injection container - no mediator object, no runtime reflection dispatch.
|
||||
|
||||
### Core Abstractions
|
||||
|
||||
```csharp
|
||||
// src/Lumina.Application/Common/CQRS/ICommand.cs
|
||||
|
||||
/// <summary>
|
||||
/// Marker interface for command types handled by <see cref="ICommandHandler{TCommand, TResult}"/>.
|
||||
/// </summary>
|
||||
public interface ICommand
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a contract for handling commands in the application layer.
|
||||
/// Commands represent operations that modify application state.
|
||||
/// </summary>
|
||||
/// <typeparam name="TCommand">The type of command to handle.</typeparam>
|
||||
/// <typeparam name="TResult">The type of result returned after handling the command.</typeparam>
|
||||
public interface ICommandHandler<in TCommand, TResult> where TCommand : ICommand
|
||||
{
|
||||
Task<TResult> HandleAsync(TCommand command, CancellationToken cancellationToken = default);
|
||||
}
|
||||
```
|
||||
|
||||
```csharp
|
||||
// src/Lumina.Application/Common/CQRS/IQuery.cs
|
||||
|
||||
/// <summary>
|
||||
/// Marker interface for query types handled by <see cref="IQueryHandler{TQuery, TResult}"/>.
|
||||
/// </summary>
|
||||
public interface IQuery
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a contract for handling queries in the application layer.
|
||||
/// Queries represent read operations that do not modify application state.
|
||||
/// </summary>
|
||||
/// <typeparam name="TQuery">The type of query to handle.</typeparam>
|
||||
/// <typeparam name="TResult">The type of result returned after handling the query.</typeparam>
|
||||
public interface IQueryHandler<in TQuery, TResult> where TQuery : IQuery
|
||||
{
|
||||
Task<TResult> HandleAsync(TQuery query, CancellationToken cancellationToken = default);
|
||||
}
|
||||
```
|
||||
|
||||
### Usage at Call Site
|
||||
|
||||
Handlers are injected directly - no `ISender` or mediator intermediary:
|
||||
|
||||
```csharp
|
||||
// Before (MediatR)
|
||||
internal sealed record GetConfiguredNismsQuery : IRequest<ErrorOr<IEnumerable<NismResponse>>>;
|
||||
internal sealed class GetConfiguredNismsEndpoint : IGetConfiguredNismsEndpoint
|
||||
{
|
||||
private readonly ISender _sender;
|
||||
|
||||
public GetConfiguredNismsEndpoint(ISender sender)
|
||||
{
|
||||
_sender = sender;
|
||||
}
|
||||
|
||||
public async Task<ErrorOr<IEnumerable<NismResponse>>> ExecuteAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return await _sender.Send(new GetConfiguredNismsQuery(), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
// After (custom abstraction)
|
||||
internal sealed record GetConfiguredNismsQuery : IQuery;
|
||||
internal sealed class GetConfiguredNismsEndpoint : IGetConfiguredNismsEndpoint
|
||||
{
|
||||
private readonly IQueryHandler<GetConfiguredNismsQuery, ErrorOr<IEnumerable<NismResponse>>> _handler;
|
||||
|
||||
public GetConfiguredNismsEndpoint(IQueryHandler<GetConfiguredNismsQuery, ErrorOr<IEnumerable<NismResponse>>> handler)
|
||||
{
|
||||
_handler = handler;
|
||||
}
|
||||
|
||||
public async Task<ErrorOr<IEnumerable<NismResponse>>> ExecuteAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return await _handler.HandleAsync(new GetConfiguredNismsQuery(), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive Outcomes
|
||||
|
||||
| Aspect | Benefit |
|
||||
|---|---|
|
||||
| Licensing | Eliminates commercial dependency and associated cost/compliance risk |
|
||||
| Simplicity | Removes an indirection layer unused beyond basic dispatch |
|
||||
| Transparency | Full ownership of dispatch logic; no hidden reflection or dynamic proxy behavior |
|
||||
| Testability | Handlers are tested directly via their interface, no mock mediator required |
|
||||
| DI Alignment | Leverages the existing .NET DI container idioms already present in the solution |
|
||||
| Performance | No runtime reflection, other than the startup registration of application use case handlers |
|
||||
|
||||
### Risks and Mitigations
|
||||
|
||||
| Risk | Mitigation Strategy |
|
||||
|---|---|
|
||||
| Loss of pipeline behavior support | Application validation will be performed manually, as an orchestration step |
|
||||
| Handler resolution errors surfacing at runtime | Covered by existing integration test suite that exercises the DI container on startup |
|
||||
| Increased boilerplate per feature | Marginal - one interface injection vs. `ISender`; offset by elimination of `IRequest<T>` marker on every command/query |
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
No alternative libraries were evaluated. The sole driver for replacing MediatR was the licensing change, and the solution's usage is narrow enough that a first-party implementation is both sufficient and lower risk than adopting a different third-party mediator library.
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
# Architecture Decision Record (ADR): 0012 - Replace FluentValidation with Custom Validation Abstractions
|
||||
|
||||
## Status
|
||||
|
||||
**Accepted** (2026-08-13)
|
||||
|
||||
## Context
|
||||
|
||||
The solution uses FluentValidation to validate commands and queries at the application boundary. A review of its usage across the codebase reveals a deliberately constrained subset of its feature set:
|
||||
|
||||
1. **Narrow API Surface**: Only `RuleFor`, `Must`, `When`, and `WithMessage`-equivalent patterns are used. Advanced FluentValidation features - cascading rules, `RuleSets`, async validators, `SetValidator`, `Transform`, and the `AbstractValidator` inheritance tree beyond basic use - are absent throughout.
|
||||
|
||||
2. **`Error`-typed Results**: The solution uses `ErrorOr` as its result type. FluentValidation returns `ValidationResult` / `ValidationFailure`, requiring a translation layer on every usage site to produce `Error` values, with some information loss in the process. A first-party validator can return `ErrorOr.Error` directly, with full metadata, eliminating that friction.
|
||||
|
||||
3. **External Dependency Surface**: FluentValidation is a well-maintained library, but the danger of it going commercial, like other open source popular libraries in recent times, and the lack of usage of its advanced features mandates an in-house replacement.
|
||||
|
||||
4. **Placement in SharedKernel**: Validation logic is cross-cutting and lives in `Lumina.Application.Common.Infrastructure.Validation`. Owning the abstraction entirely means the validation model stays aligned with the domain's `Error` type without any adapter.
|
||||
|
||||
## Decision
|
||||
|
||||
Replace FluentValidation with a minimal, first-party validation framework placed in `Lumina.Application.Common.Infrastructure.Validation`. The API mirrors FluentValidation's familiar fluent surface (`RuleFor`, `Must`, `When`, `WithError`) to minimize migration friction.
|
||||
|
||||
### Core Abstractions
|
||||
|
||||
```csharp
|
||||
// IValidator.cs - public contract consumed by application handlers
|
||||
public interface IValidator<in TRequest>
|
||||
{
|
||||
List<Error> Validate(TRequest instance);
|
||||
}
|
||||
|
||||
// IValidationRule.cs - internal rule evaluation contract
|
||||
internal interface IValidationRule<in TRequest>
|
||||
{
|
||||
Error? Validate(TRequest instance);
|
||||
}
|
||||
|
||||
// IRuleBuilder.cs - fluent configuration surface
|
||||
public interface IRuleBuilder<TRequest, TProperty>
|
||||
{
|
||||
IRuleBuilder<TRequest, TProperty> Must(Func<TProperty, bool> predicate);
|
||||
IRuleBuilder<TRequest, TProperty> When(Func<TRequest, bool> condition);
|
||||
IRuleBuilder<TRequest, TProperty> WithError(Error error);
|
||||
}
|
||||
```
|
||||
|
||||
### Base Validator
|
||||
|
||||
```csharp
|
||||
// AbstractValidator.cs
|
||||
public abstract class AbstractValidator<TRequest> : IValidator<TRequest>
|
||||
{
|
||||
private readonly List<IValidationRule<TRequest>> _rules = [];
|
||||
|
||||
protected IRuleBuilder<TRequest, TProperty> RuleFor<TProperty>(
|
||||
Func<TRequest, TProperty> propertySelector)
|
||||
{
|
||||
ValidationRule<TRequest, TProperty> rule = new(propertySelector);
|
||||
_rules.Add(rule);
|
||||
return rule;
|
||||
}
|
||||
|
||||
public List<Error> Validate(TRequest instance)
|
||||
{
|
||||
List<Error> errors = [];
|
||||
foreach (IValidationRule<TRequest> rule in _rules)
|
||||
{
|
||||
Error? error = rule.Validate(instance);
|
||||
if (error.HasValue)
|
||||
errors.Add(error.Value);
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Concrete Rule Implementation
|
||||
|
||||
```csharp
|
||||
// ValidationRule.cs - internal sealed, not exposed to consumers
|
||||
internal sealed class ValidationRule<TRequest, TProperty>
|
||||
: IValidationRule<TRequest>, IRuleBuilder<TRequest, TProperty>
|
||||
{
|
||||
private readonly Func<TRequest, TProperty> _propertySelector;
|
||||
private readonly List<Func<TProperty, bool>> _predicates = [];
|
||||
private Error _error = Error.Validation();
|
||||
private Func<TRequest, bool>? _condition;
|
||||
|
||||
public ValidationRule(Func<TRequest, TProperty> propertySelector)
|
||||
=> _propertySelector = propertySelector;
|
||||
|
||||
public IRuleBuilder<TRequest, TProperty> Must(Func<TProperty, bool> predicate)
|
||||
{
|
||||
_predicates.Add(predicate);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IRuleBuilder<TRequest, TProperty> When(Func<TRequest, bool> condition)
|
||||
{
|
||||
_condition = condition;
|
||||
return this;
|
||||
}
|
||||
|
||||
public IRuleBuilder<TRequest, TProperty> WithError(Error error)
|
||||
{
|
||||
_error = error;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Error? Validate(TRequest instance)
|
||||
{
|
||||
if (_condition is not null && !_condition(instance))
|
||||
return null;
|
||||
|
||||
TProperty value = _propertySelector(instance);
|
||||
foreach (var predicate in _predicates)
|
||||
if (!predicate(value))
|
||||
return _error;
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Built-in Extension Methods
|
||||
|
||||
Common predicates are provided as extension methods on `IRuleBuilder<TRequest, TProperty>` via `ValidatorUtilities`, placed in `Lumina.Application.Common.Utilities`:
|
||||
|
||||
| Extension | Overloads | Behaviour |
|
||||
|---|---|---|
|
||||
| `NotEmpty()` | `string`, `List<TItem>` | Fails if `null`, empty, or whitespace-only |
|
||||
| `GreaterThan(value)` | `int`, `int?`, `TimeSpan` | Fails if property ≤ value; nullable variant passes on `null` |
|
||||
| `IsInEnum()` | `TEnum`, `TEnum?` | Fails if value is not a defined enum member; nullable variant passes on `null` |
|
||||
|
||||
### Usage Example
|
||||
|
||||
```csharp
|
||||
internal sealed class CreateSensorCommandValidator : AbstractValidator<CreateSensorCommand>
|
||||
{
|
||||
public CreateSensorCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.Name)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Sensor.NameRequired);
|
||||
|
||||
RuleFor(x => x.IntervalSeconds)
|
||||
.GreaterThan(0)
|
||||
.WithError(Errors.Sensor.InvalidInterval);
|
||||
|
||||
RuleFor(x => x.Type)
|
||||
.IsInEnum()
|
||||
.WithError(Errors.Sensor.InvalidType);
|
||||
|
||||
RuleFor(x => x.ThresholdOverride)
|
||||
.GreaterThan(0)
|
||||
.When(x => x.ThresholdOverride.HasValue)
|
||||
.WithError(Errors.Sensor.InvalidThreshold);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive Outcomes
|
||||
|
||||
| Aspect | Benefit |
|
||||
|---|---|
|
||||
| `Error` Alignment | Validators return `List<Error>` directly - no `ValidationResult` → `Error` translation layer at call sites |
|
||||
| Dependency Reduction | Removes FluentValidation NuGet package and all transitive dependencies |
|
||||
| API Ownership | Full control over rule semantics, error shape, and future extension |
|
||||
| Familiar Surface | `RuleFor` / `Must` / `When` / `WithError` pattern is intentionally close to FluentValidation, minimising cognitive load during migration |
|
||||
| Encapsulation | `IValidationRule` and `ValidationRule` are `internal`; consumers only interact with `IValidator` and `IRuleBuilder` |
|
||||
|
||||
### Risks and Mitigations
|
||||
|
||||
| Risk | Mitigation Strategy |
|
||||
|---|---|
|
||||
| Missing built-in rules surfacing post-migration | Audit all existing FluentValidation rule usages before removal; add corresponding `ValidatorUtilities` extensions as needed |
|
||||
| Async validation not supported | No async validators exist, because this pertains to application use cases validation concerns (user input, etc), not business rules validations or invariants, which might require asynchronous or IO operations |
|
||||
| Loss of FluentValidation test helpers (`TestValidate`) | Replace with direct `ValidatorTestExtensions.TestValidate` calls in unit tests |
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
No alternative third-party validation libraries were evaluated, as this decision was not about replacing the FluentValidation libary with another library. The solution's validation usage is sufficiently narrow (property-level predicates, conditional execution, typed error results) that the cost of adopting and adapting another external library exceeds the cost of ownership of a purpose-built implementation aligned with the `ErrorOr` result model already in use.
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
# Architecture Decision Record (ADR): 0013 - Replace Mediator Domain Event Publishing with a Custom Implementation
|
||||
|
||||
## Status
|
||||
|
||||
**Accepted** (2026-08-13)
|
||||
|
||||
## Context
|
||||
|
||||
Domain event publishing, the mechanism that fires the `IDomainEvent` objects raised by aggregates to their handlers, depends on the Mediator library (`Mediator.Abstractions` and `Mediator.SourceGenerator`).
|
||||
|
||||
1. **Event contract**: `IDomainEvent` implements Mediator's `INotification` marker interface.
|
||||
|
||||
2. **Handler registration**: Domain event handlers implements Mediator's `INotificationHandler<T>` and are registered by the source-generated `AddMediator` call.
|
||||
|
||||
3. **Publishing sites**: Mediator's `IPublisher` is used from `EventualConsistencyMiddleware` (queued events, published after the transaction commits), from `MediaLibraryScanningService` (scan start events), and from the scan jobs and `ScanFailurePublisher` (progress and failure events).
|
||||
|
||||
The remaining publish half carries the same third-party dependency and source-generated registration that ADR-0011 removed from the dispatch half.
|
||||
|
||||
## Decision
|
||||
|
||||
Replace Mediator's notification publishing with a first-party domain event publisher.
|
||||
|
||||
### New Abstractions (in `Lumina.Domain.Common.Events`)
|
||||
|
||||
- `IDomainEvent` no longer inherits `INotification`.
|
||||
- `IDomainEventPublisher` exposes `ValueTask PublishAsync(IDomainEvent domainEvent, CancellationToken cancellationToken = default)`.
|
||||
- `IDomainEventHandler<TDomainEvent>` exposes `ValueTask HandleAsync(TDomainEvent domainEvent, CancellationToken cancellationToken)`. The type parameter is invariant so handlers stay mockable by dynamic proxy libraries.
|
||||
|
||||
### Publisher Implementation (`DomainEventPublisher` in Infrastructure)
|
||||
|
||||
- Scoped, resolving handlers for the event's runtime type from the DI container.
|
||||
- Dispatches through a compiled delegate cached per event type in a static `ConcurrentDictionary`, built once via `MakeGenericMethod` over a generic dispatch helper. Handlers run sequentially in registration order, exceptions propagate, and events without handlers are no-ops.
|
||||
- Registered next to the existing `IDomainEventsQueue`.
|
||||
|
||||
### Registration (Application DI)
|
||||
|
||||
The existing assembly scan that registers `ICommandHandler<>`, `IQueryHandler<>`, and `IValidator<>` now also registers `IDomainEventHandler<>` as scoped, replacing the source-generated `AddMediator`.
|
||||
|
||||
### Consistency Guarantees Preserved
|
||||
|
||||
- Commit-before-publish ordering in `EventualConsistencyMiddleware` is unchanged (see ADR-0002).
|
||||
- Re-entrant publishing (a handler publishing another event) is safe: each publish resolves handlers fresh from the scoped provider.
|
||||
- Jobs publish from their own scopes, so handlers receive a fresh unit of work and `DbContext`.
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive Outcomes
|
||||
|
||||
| Aspect | Benefit |
|
||||
|---|---|
|
||||
| Dependency reduction | Removes `Mediator.Abstractions` and `Mediator.SourceGenerator` from the entire solution |
|
||||
| Transparency | Dispatch logic is fully owned and inspectable; no generated code |
|
||||
| Consistency | Domain event handlers join the same explicit registration scan as the CQRS handlers |
|
||||
| Single event contract | `IDomainEvent` remains the sole contract until a real cross-bounded-context consumer exists |
|
||||
|
||||
### Risks and Mitigations
|
||||
|
||||
| Risk | Mitigation Strategy |
|
||||
|---|---|
|
||||
| Handler resolution failures surface at runtime | Existing integration test suite exercises the DI container on startup |
|
||||
| Reflection-based dispatch per event type | Compiled delegate cache makes dispatch cheap after the first publish of each type |
|
||||
| Dynamic proxy cannot proxy generic interfaces | `IDomainEventHandler<TDomainEvent>` is deliberately invariant so handlers remain mockable in unit tests |
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
### 1. Domain versus Integration Event Split
|
||||
|
||||
Introduce `IIntegrationEvent` now, with a durable outbox, for inter-bounded-context propagation.
|
||||
|
||||
**Rejected**: there are no cross-bounded-context consumers today - every event lives in the `LibraryManagementBoundedContext` and is handled in-process. The outbox machinery (durability, retries, idempotency) is speculative until the first real consumer appears, and forcing every existing event into one of two buckets would produce classification with no basis. The seam is documented on `IDomainEvent` itself so the split stays cheap to introduce later.
|
||||
|
||||
### 2. Keeping Mediator for Publishing
|
||||
|
||||
Keep the Mediator library for the domain event publishing half.
|
||||
|
||||
**Rejected**: for the same reason ADR-0011 rejected it for command and query dispatching - an external dependency, with source-generated registration, for functionality that is fully implementable in-house.
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a validation behavior in the Mediator pipeline for handling requests and responses.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type representing a request. It should implement <see cref="IRequest{TResponse}"/>.</typeparam>
|
||||
/// <typeparam name="TResponse">The type representing a response. It should implement <see cref="IErrorOr"/> interface.</typeparam>
|
||||
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
|
||||
where TResponse : IErrorOr
|
||||
{
|
||||
private readonly IValidator<TRequest>? _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ValidationBehavior{TRequest, TResponse}"/> class.
|
||||
/// </summary>
|
||||
/// <param name="validator">The validator used in this behavior pipeline for the Mediator commands and queries.</param>
|
||||
public ValidationBehavior(IValidator<TRequest>? validator = null)
|
||||
{
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pipeline handler. Perform any additional behavior and await the <paramref name="next"/> delegate as necessary.
|
||||
/// </summary>
|
||||
/// <param name="request">Incoming request.</param>
|
||||
/// <param name="next">Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask<TResponse> Handle(TRequest request, MessageHandlerDelegate<TRequest, TResponse> 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<Error> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Lumina.Application.Common.CQRS;
|
||||
|
||||
/// <summary>
|
||||
/// Marker interface for command types handled by <see cref="ICommandHandler{TCommand, TResult}"/>.
|
||||
/// </summary>
|
||||
public interface ICommand
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.CQRS;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a contract for handling commands in the application layer.
|
||||
/// Commands represent operations that modify application state.
|
||||
/// </summary>
|
||||
/// <typeparam name="TCommand">The type of command to handle.</typeparam>
|
||||
/// <typeparam name="TResult">The type of result returned after handling the command.</typeparam>
|
||||
public interface ICommandHandler<in TCommand, TResult> where TCommand : ICommand
|
||||
{
|
||||
/// <summary>
|
||||
/// Handles the specified command and returns a result.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to handle.</param>
|
||||
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
|
||||
/// <returns>A task that represents the asynchronous operation, containing the result of the command execution.</returns>
|
||||
Task<TResult> HandleAsync(TCommand command, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Lumina.Application.Common.CQRS;
|
||||
|
||||
/// <summary>
|
||||
/// Marker interface for query types handled by <see cref="IQueryHandler{TQuery, TResult}"/>.
|
||||
/// </summary>
|
||||
public interface IQuery
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.CQRS;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a contract for handling queries in the application layer.
|
||||
/// Queries represent read-only operations that retrieve data without modifying application state.
|
||||
/// </summary>
|
||||
/// <typeparam name="TQuery">The type of query to handle.</typeparam>
|
||||
/// <typeparam name="TResult">The type of result returned after handling the query.</typeparam>
|
||||
public interface IQueryHandler<in TQuery, TResult> where TQuery : IQuery
|
||||
{
|
||||
/// <summary>
|
||||
/// Handles the specified query and returns a result.
|
||||
/// </summary>
|
||||
/// <param name="query">The query to handle.</param>
|
||||
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
|
||||
/// <returns>A task that represents the asynchronous operation, containing the result of the query execution.</returns>
|
||||
Task<TResult> HandleAsync(TQuery query, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Application.Common.Behaviors;
|
||||
using Mediator;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DependencyInjection;
|
||||
@@ -21,17 +23,33 @@ public static class ApplicationLayerServices
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
public static IServiceCollection AddApplicationLayerServices(this IServiceCollection services)
|
||||
{
|
||||
// register Mediator
|
||||
services.AddMediator(options =>
|
||||
Type[] handlerContractTypes =
|
||||
[
|
||||
typeof(CQRS.ICommandHandler<,>),
|
||||
typeof(CQRS.IQueryHandler<,>),
|
||||
typeof(Infrastructure.Validation.IValidator<>),
|
||||
typeof(IDomainEventHandler<>),
|
||||
];
|
||||
|
||||
IEnumerable<Type> concreteTypes = Assembly.GetExecutingAssembly()
|
||||
.GetTypes()
|
||||
.Where(type => !type.IsInterface && !type.IsAbstract && !type.IsGenericTypeDefinition);
|
||||
|
||||
var handlerRegistrations = concreteTypes
|
||||
.SelectMany(implementation => implementation.GetInterfaces(),
|
||||
(implementation, contract) => new { Contract = contract, Implementation = implementation })
|
||||
.Where(registration => registration.Contract.IsGenericType && handlerContractTypes.Contains(registration.Contract.GetGenericTypeDefinition()));
|
||||
|
||||
foreach (var registration in handlerRegistrations)
|
||||
{
|
||||
options.ServiceLifetime = ServiceLifetime.Scoped;
|
||||
});
|
||||
if (services.Any(service => service.ServiceType == registration.Contract))
|
||||
continue;
|
||||
|
||||
// register the validation behavior
|
||||
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
|
||||
|
||||
// register fluent validators
|
||||
services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly);
|
||||
if (registration.Contract.GetGenericTypeDefinition() == typeof(Infrastructure.Validation.IValidator<>))
|
||||
services.AddSingleton(registration.Contract, registration.Implementation);
|
||||
else
|
||||
services.AddScoped(registration.Contract, registration.Implementation);
|
||||
}
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure.Validation;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for creating validators for commands and queries.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type of the request (command or query) to be validated.</typeparam>
|
||||
public abstract class AbstractValidator<TRequest> : IValidator<TRequest>
|
||||
{
|
||||
private readonly List<IValidationRule<TRequest>> _rules = [];
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule for a specific property on the request being validated.
|
||||
/// </summary>
|
||||
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
|
||||
/// <param name="propertySelector">A function that selects the property to validate from the request instance.</param>
|
||||
/// <returns>An <see cref="IRuleBuilder{TRequest, TProperty}"/> instance to configure the rule fluently.</returns>
|
||||
public IRuleBuilder<TRequest, TProperty> RuleFor<TProperty>(Func<TRequest, TProperty> propertySelector)
|
||||
{
|
||||
ValidationRule<TRequest, TProperty> rule = new(propertySelector);
|
||||
_rules.Add(rule);
|
||||
return rule;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that is evaluated against each item within a collection property on the request being validated.
|
||||
/// </summary>
|
||||
/// <typeparam name="TItem">The type of the items in the collection being validated.</typeparam>
|
||||
/// <param name="collectionSelector">A function that selects the collection to validate from the request instance.</param>
|
||||
/// <returns>An <see cref="IRuleBuilder{TRequest, TItem}"/> instance to configure the per-item rule fluently.</returns>
|
||||
public IRuleBuilder<TRequest, TItem> RuleForEach<TItem>(Func<TRequest, IEnumerable<TItem>?> collectionSelector)
|
||||
{
|
||||
ValidationRuleForEach<TRequest, TItem> rule = new(collectionSelector);
|
||||
_rules.Add(rule);
|
||||
return rule;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates the specified request instance against all defined rules.
|
||||
/// </summary>
|
||||
/// <param name="instance">The request instance to validate.</param>
|
||||
/// <returns>A list of validation errors. If the instance is valid, the list will be empty.</returns>
|
||||
public List<Error> Validate(TRequest instance)
|
||||
{
|
||||
List<Error> errors = [];
|
||||
|
||||
foreach (IValidationRule<TRequest> rule in _rules)
|
||||
errors.AddRange(rule.Validate(instance));
|
||||
|
||||
return errors;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure.Validation;
|
||||
|
||||
/// <summary>
|
||||
/// Provides a fluent API for building validation rules for commands and queries.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type of the request (command or query) being validated.</typeparam>
|
||||
/// <typeparam name="TProperty">The type of the specific property on the request that the rule applies to.</typeparam>
|
||||
public interface IRuleBuilder<TRequest, TProperty>
|
||||
{
|
||||
/// <summary>
|
||||
/// Specifies a condition that the property must satisfy to be considered valid.
|
||||
/// </summary>
|
||||
/// <param name="predicate">A function to test the property value.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
IRuleBuilder<TRequest, TProperty> Must(Func<TProperty, bool> predicate);
|
||||
|
||||
/// <summary>
|
||||
/// Specifies a condition that both the request instance and the property value must satisfy to be considered valid.
|
||||
/// </summary>
|
||||
/// <param name="predicate">A function to test the request instance together with the property value.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
IRuleBuilder<TRequest, TProperty> Must(Func<TRequest, TProperty, bool> predicate);
|
||||
|
||||
/// <summary>
|
||||
/// Specifies a condition that must be met for the validation rule to be executed.
|
||||
/// </summary>
|
||||
/// <param name="condition">A function evaluating the request instance.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
IRuleBuilder<TRequest, TProperty> When(Func<TRequest, bool> condition);
|
||||
|
||||
/// <summary>
|
||||
/// Specifies a custom <see cref="Error"/> object to be returned when the validation fails.
|
||||
/// </summary>
|
||||
/// <param name="error">The specific error to return upon failure.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
IRuleBuilder<TRequest, TProperty> WithError(Error error);
|
||||
|
||||
/// <summary>
|
||||
/// Defines nested validation rules for the complex property being validated.
|
||||
/// </summary>
|
||||
/// <param name="configure">An action used to configure the inline validator for the property.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
IRuleBuilder<TRequest, TProperty> ChildRules(Action<AbstractValidator<TProperty>> configure);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure.Validation;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for triggering commands and queries validator evaluation.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type of the request (command or query) being evaluated.</typeparam>
|
||||
internal interface IValidationRule<in TRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Evaluates the validation rule against the specified request instance.
|
||||
/// </summary>
|
||||
/// <param name="instance">The request instance to validate.</param>
|
||||
/// <returns>The <see cref="Error"/>s produced by this rule; empty if the rule passes.</returns>
|
||||
IEnumerable<Error> Validate(TRequest instance);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure.Validation;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for validating requests of commands and queries.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type of the request (command or query) to be validated.</typeparam>
|
||||
public interface IValidator<in TRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Validates the specified request instance against the defined rules.
|
||||
/// </summary>
|
||||
/// <param name="instance">The request instance to validate.</param>
|
||||
/// <returns>A list of validation errors. If the instance is valid, the list will be empty.</returns>
|
||||
List<Error> Validate(TRequest instance);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure.Validation;
|
||||
|
||||
/// <summary>
|
||||
/// Concrete <see cref="AbstractValidator{TRequest}"/> used to declare validation rules inline for nested complex properties.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type of the request (command or query) to be validated.</typeparam>
|
||||
public class InlineValidator<TRequest> : AbstractValidator<TRequest>
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure.Validation;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule for commands and queries that evaluates a specific property of a request.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type of the request (command or query) being validated.</typeparam>
|
||||
/// <typeparam name="TProperty">The type of the specific property on the request that the rule applies to.</typeparam>
|
||||
internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TRequest>, IRuleBuilder<TRequest, TProperty>
|
||||
{
|
||||
private readonly Func<TRequest, TProperty> _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<Func<TProperty, bool>> _predicates = [];
|
||||
private readonly List<Error> _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<Func<TRequest, TProperty, bool>> _instanceAwarePredicates = [];
|
||||
private readonly List<Error> _instanceAwarePredicateErrors = [];
|
||||
|
||||
private Error currentError = Error.Validation();
|
||||
private Func<TRequest, bool>? 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<TProperty>? _childValidator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ValidationRule{TRequest, TProperty}"/> class.
|
||||
/// </summary>
|
||||
/// <param name="propertySelector">A function that extracts the property value from the request instance.</param>
|
||||
public ValidationRule(Func<TRequest, TProperty> propertySelector)
|
||||
{
|
||||
_propertySelector = propertySelector;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a condition that the property must satisfy to be considered valid.
|
||||
/// </summary>
|
||||
/// <param name="predicate">A function to test the property value.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public IRuleBuilder<TRequest, TProperty> Must(Func<TProperty, bool> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a condition that the request instance together with the property must satisfy to be considered valid.
|
||||
/// </summary>
|
||||
/// <param name="predicate">A function to test the request instance together with the property value.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public IRuleBuilder<TRequest, TProperty> Must(Func<TRequest, TProperty, bool> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Specifies a condition that must be met for the validation rule to be executed.
|
||||
/// </summary>
|
||||
/// <param name="condition">A function evaluating the request instance.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public IRuleBuilder<TRequest, TProperty> When(Func<TRequest, bool> condition)
|
||||
{
|
||||
this.condition = condition;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Specifies a custom <see cref="Error"/> object to be returned when the validation fails.
|
||||
/// </summary>
|
||||
/// <param name="error">The specific error to return upon failure.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public IRuleBuilder<TRequest, TProperty> WithError(Error error)
|
||||
{
|
||||
// Callers might pass in an error created with the wrong factory (e.g. Error.NotFound()) by mistake.
|
||||
// Rebuilding it as Error.Validation() here guarantees every error surfaced by this class is
|
||||
// consistently typed as a validation error, regardless of what the caller supplied.
|
||||
Error validationError = Error.Validation(description: error.Description);
|
||||
currentError = validationError;
|
||||
|
||||
// WithError() is meant to apply to the predicate that was *just* added via Must(), not to all
|
||||
// predicates registered so far. Since Must() can target either parallel-list pair, we use the
|
||||
// flag set by the last Must() call to figure out which list's last slot to overwrite.
|
||||
if (lastAddedPredicateIsInstanceAware && _instanceAwarePredicateErrors.Count > 0)
|
||||
_instanceAwarePredicateErrors[^1] = validationError;
|
||||
else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0)
|
||||
_predicateErrors[^1] = validationError;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines nested validation rules for the complex property being validated.
|
||||
/// </summary>
|
||||
/// <param name="configure">An action used to configure the inline validator for the property.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public IRuleBuilder<TRequest, TProperty> ChildRules(Action<AbstractValidator<TProperty>> 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<TProperty> childValidator = new();
|
||||
configure(childValidator);
|
||||
_childValidator = childValidator;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates all configured predicates against the specified request instance.
|
||||
/// </summary>
|
||||
/// <param name="instance">The request instance to validate.</param>
|
||||
/// <returns>The <see cref="Error"/> of every predicate that fails; empty if the rule passes.</returns>
|
||||
public IEnumerable<Error> Validate(TRequest instance)
|
||||
{
|
||||
// evaluate the condition first, if it returns false, skip validation entirely.
|
||||
if (condition is not null && !condition(instance))
|
||||
yield break;
|
||||
|
||||
TProperty value = _propertySelector(instance);
|
||||
|
||||
// Deliberately does NOT stop at the first failure: every failing predicate contributes its own error,
|
||||
// so a caller sees the full set of problems for // this property in one pass instead of having to fix
|
||||
// and resubmit one error at a time.
|
||||
for (int index = 0; index < _predicates.Count; index++)
|
||||
if (!_predicates[index](value))
|
||||
yield return _predicateErrors[index];
|
||||
|
||||
for (int index = 0; index < _instanceAwarePredicates.Count; index++)
|
||||
if (!_instanceAwarePredicates[index](instance, value))
|
||||
yield return _instanceAwarePredicateErrors[index];
|
||||
|
||||
if (_childValidator is not null && value is not null)
|
||||
foreach (Error childError in _childValidator.Validate(value))
|
||||
yield return childError;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure.Validation;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule for commands and queries that evaluates each item within a collection property of a request.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type of the request (command or query) being validated.</typeparam>
|
||||
/// <typeparam name="TItem">The type of the items in the collection that the rule applies to.</typeparam>
|
||||
internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<TRequest>, IRuleBuilder<TRequest, TItem>
|
||||
{
|
||||
private readonly Func<TRequest, IEnumerable<TItem>?> _collectionSelector;
|
||||
private readonly List<Func<TItem, bool>> _predicates = [];
|
||||
private readonly List<Error> _predicateErrors = [];
|
||||
private readonly List<Func<TRequest, TItem, bool>> _instanceAwarePredicates = [];
|
||||
private readonly List<Error> _instanceAwarePredicateErrors = [];
|
||||
private Error currentError = Error.Validation();
|
||||
private Func<TRequest, bool>? condition;
|
||||
private bool lastAddedPredicateIsInstanceAware;
|
||||
private AbstractValidator<TItem>? _childValidator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ValidationRuleForEach{TRequest, TItem}"/> class.
|
||||
/// </summary>
|
||||
/// <param name="collectionSelector">A function that extracts the collection to iterate from the request instance.</param>
|
||||
public ValidationRuleForEach(Func<TRequest, IEnumerable<TItem>?> collectionSelector)
|
||||
{
|
||||
_collectionSelector = collectionSelector;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a condition that each item in the collection must satisfy to be considered valid.
|
||||
/// </summary>
|
||||
/// <param name="predicate">A function to test each item value.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
|
||||
public IRuleBuilder<TRequest, TItem> Must(Func<TItem, bool> predicate)
|
||||
{
|
||||
_predicates.Add(predicate);
|
||||
_predicateErrors.Add(currentError);
|
||||
lastAddedPredicateIsInstanceAware = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a condition that the request instance together with each item must satisfy to be considered valid.
|
||||
/// </summary>
|
||||
/// <param name="predicate">A function to test the request instance together with each item value.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
|
||||
public IRuleBuilder<TRequest, TItem> Must(Func<TRequest, TItem, bool> predicate)
|
||||
{
|
||||
_instanceAwarePredicates.Add(predicate);
|
||||
_instanceAwarePredicateErrors.Add(currentError);
|
||||
lastAddedPredicateIsInstanceAware = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Specifies a condition that must be met for the validation rule to be executed.
|
||||
/// </summary>
|
||||
/// <param name="condition">A function evaluating the request instance.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
|
||||
public IRuleBuilder<TRequest, TItem> When(Func<TRequest, bool> condition)
|
||||
{
|
||||
this.condition = condition;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Specifies a custom <see cref="Error"/> object to be returned when the validation fails.
|
||||
/// </summary>
|
||||
/// <param name="error">The specific error to return upon failure.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
|
||||
public IRuleBuilder<TRequest, TItem> WithError(Error error)
|
||||
{
|
||||
// validation rules always produce validation errors, regardless of the error type of the source error
|
||||
Error validationError = Error.Validation(description: error.Description);
|
||||
currentError = validationError;
|
||||
if (lastAddedPredicateIsInstanceAware && _instanceAwarePredicateErrors.Count > 0)
|
||||
_instanceAwarePredicateErrors[^1] = validationError;
|
||||
else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0)
|
||||
_predicateErrors[^1] = validationError;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines nested validation rules for each item of the collection being validated.
|
||||
/// </summary>
|
||||
/// <param name="configure">An action used to configure the inline validator for each item.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
|
||||
public IRuleBuilder<TRequest, TItem> ChildRules(Action<AbstractValidator<TItem>> configure)
|
||||
{
|
||||
InlineValidator<TItem> childValidator = new();
|
||||
configure(childValidator);
|
||||
_childValidator = childValidator;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates all configured predicates against each item in the collection.
|
||||
/// </summary>
|
||||
/// <param name="instance">The request instance to validate.</param>
|
||||
/// <returns>One <see cref="Error"/> per failing predicate, per item; empty if every item passes.</returns>
|
||||
public IEnumerable<Error> Validate(TRequest instance)
|
||||
{
|
||||
// evaluate the condition first, if it returns false, skip validation entirely.
|
||||
if (condition is not null && !condition(instance))
|
||||
yield break;
|
||||
|
||||
IEnumerable<TItem>? collection = _collectionSelector(instance);
|
||||
if (collection is null)
|
||||
yield break;
|
||||
|
||||
foreach (TItem item in collection)
|
||||
{
|
||||
for (int index = 0; index < _predicates.Count; index++)
|
||||
if (!_predicates[index](item))
|
||||
yield return _predicateErrors[index];
|
||||
|
||||
for (int index = 0; index < _instanceAwarePredicates.Count; index++)
|
||||
if (!_instanceAwarePredicates[index](instance, item))
|
||||
yield return _instanceAwarePredicateErrors[index];
|
||||
|
||||
if (_childValidator is not null && item is not null)
|
||||
foreach (Error childError in _childValidator.Validate(item))
|
||||
yield return childError;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Text.RegularExpressions;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Utilities;
|
||||
|
||||
/// <summary>
|
||||
/// Validator extension methods for the <see cref="IRuleBuilder{TRequest, TProperty}"/> to define common validation rules.
|
||||
/// </summary>
|
||||
public static class ValidatorUtilities
|
||||
{
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the integer property is greater than the specified value.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="valueToCompare">The value that the property must be greater than.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, int> GreaterThan<TRequest>(this IRuleBuilder<TRequest, int> ruleBuilder, int valueToCompare)
|
||||
{
|
||||
return ruleBuilder.Must(value => value > valueToCompare);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the nullable integer property is greater than the specified value.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If the property is <see langword="null"/>, this rule passes (use <see cref="NotNull{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to check for missing values).
|
||||
/// </remarks>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="valueToCompare">The value that the property must be greater than.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, int?> GreaterThan<TRequest>(this IRuleBuilder<TRequest, int?> ruleBuilder, int valueToCompare)
|
||||
{
|
||||
return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the decimal property is greater than the specified value.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="valueToCompare">The value that the property must be greater than.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, decimal> GreaterThan<TRequest>(this IRuleBuilder<TRequest, decimal> ruleBuilder, decimal valueToCompare)
|
||||
{
|
||||
return ruleBuilder.Must(value => value > valueToCompare);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the nullable decimal property is greater than the specified value.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If the property is <see langword="null"/>, this rule passes (use <see cref="NotNull{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to check for missing values).
|
||||
/// </remarks>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="valueToCompare">The value that the property must be greater than.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, decimal?> GreaterThan<TRequest>(this IRuleBuilder<TRequest, decimal?> ruleBuilder, decimal valueToCompare)
|
||||
{
|
||||
return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the time span property is greater than the specified value.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="valueToCompare">The value that the property must be greater than.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, TimeSpan> GreaterThan<TRequest>(this IRuleBuilder<TRequest, TimeSpan> ruleBuilder, TimeSpan valueToCompare)
|
||||
{
|
||||
return ruleBuilder.Must(value => value > valueToCompare);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the integer property is greater than or equal to the specified value.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="valueToCompare">The value that the property must be greater than or equal to.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, int> GreaterThanOrEqualTo<TRequest>(this IRuleBuilder<TRequest, int> ruleBuilder, int valueToCompare)
|
||||
{
|
||||
return ruleBuilder.Must(value => value >= valueToCompare);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the nullable integer property is greater than or equal to the specified value.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If the property is <see langword="null"/>, this rule passes.
|
||||
/// </remarks>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="valueToCompare">The value that the property must be greater than or equal to.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, int?> GreaterThanOrEqualTo<TRequest>(this IRuleBuilder<TRequest, int?> ruleBuilder, int valueToCompare)
|
||||
{
|
||||
return ruleBuilder.Must(value => !value.HasValue || value.Value >= valueToCompare);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the nullable decimal property is greater than or equal to the specified value.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If the property is <see langword="null"/>, this rule passes.
|
||||
/// </remarks>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="valueToCompare">The value that the property must be greater than or equal to.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, decimal?> GreaterThanOrEqualTo<TRequest>(this IRuleBuilder<TRequest, decimal?> ruleBuilder, decimal valueToCompare)
|
||||
{
|
||||
return ruleBuilder.Must(value => !value.HasValue || value.Value >= valueToCompare);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the property is not <see langword="null"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This rule checks reference/nullable-value nullness only. Combine with
|
||||
/// <see cref="NotEmpty{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to also reject empty values.
|
||||
/// </remarks>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, TProperty> NotNull<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder)
|
||||
{
|
||||
return ruleBuilder.Must(value => value is not null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the property is not empty.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This rule is type-aware: a <see cref="string"/> is checked for white-space only content, a <see cref="Guid"/>
|
||||
/// is checked against <see cref="Guid.Empty"/>, and any <see cref="IEnumerable"/> is checked for having at least
|
||||
/// one item. If the property is <see langword="null"/>, this rule fails.
|
||||
/// </remarks>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, TProperty> NotEmpty<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder)
|
||||
{
|
||||
return ruleBuilder.Must(value => value switch
|
||||
{
|
||||
null => false,
|
||||
string stringValue => stringValue.Trim().Length > 0,
|
||||
Guid guidValue => guidValue != Guid.Empty,
|
||||
IEnumerable enumerable => enumerable.GetEnumerator().MoveNext(),
|
||||
_ => true
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the value is a defined member of the specified enumeration type.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <typeparam name="TEnum">The type of the enumeration.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, TEnum> IsInEnum<TRequest, TEnum>(this IRuleBuilder<TRequest, TEnum> ruleBuilder) where TEnum : struct, Enum
|
||||
{
|
||||
return ruleBuilder.Must(value => Enum.IsDefined(value));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures a nullable enum value is either <see langword="null"/> or a defined member of the specified enumeration type.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <typeparam name="TEnum">The type of the enumeration.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, TEnum?> IsInEnum<TRequest, TEnum>(this IRuleBuilder<TRequest, TEnum?> ruleBuilder) where TEnum : struct, Enum
|
||||
{
|
||||
return ruleBuilder.Must(value => value.HasValue && Enum.IsDefined(value.Value));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the string property does not exceed the specified maximum length.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If the property is <see langword="null"/> or not a string, this rule passes.
|
||||
/// </remarks>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="maximumLength">The maximum allowed length of the property.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, TProperty> MaximumLength<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, int maximumLength)
|
||||
{
|
||||
return ruleBuilder.Must(value => value is not string stringValue || stringValue.Length <= maximumLength);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the string property is at least the specified minimum length.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If the property is <see langword="null"/> or not a string, this rule fails.
|
||||
/// </remarks>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="minimumLength">The minimum allowed length of the property.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, TProperty> MinimumLength<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, int minimumLength)
|
||||
{
|
||||
return ruleBuilder.Must(value => value is string stringValue && stringValue.Length >= minimumLength);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the string property has exactly the specified length.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If the property is <see langword="null"/> or not a string, this rule fails.
|
||||
/// </remarks>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="length">The exact allowed length of the property.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, TProperty> Length<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, int length)
|
||||
{
|
||||
return ruleBuilder.Must(value => value is string stringValue && stringValue.Length == length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the string property length is within the specified inclusive range.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If the property is <see langword="null"/> or not a string, this rule fails.
|
||||
/// </remarks>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="minimumLength">The minimum allowed length of the property.</param>
|
||||
/// <param name="maximumLength">The maximum allowed length of the property.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, TProperty> Length<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, int minimumLength, int maximumLength)
|
||||
{
|
||||
return ruleBuilder.Must(value => value is string stringValue && stringValue.Length >= minimumLength && stringValue.Length <= maximumLength);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the string property matches the specified regular expression pattern.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If the property is <see langword="null"/> or not a string, this rule fails (use
|
||||
/// <see cref="When{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty}, Func{TRequest, bool})"/> to skip optional properties).
|
||||
/// </remarks>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="regexPattern">The regular expression pattern the property must match.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, TProperty> Matches<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, string regexPattern)
|
||||
{
|
||||
return ruleBuilder.Must(value => value is string stringValue && Regex.IsMatch(stringValue, regexPattern));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the string property matches the regular expression pattern selected from the request instance.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If the property is <see langword="null"/> or not a string, this rule fails.
|
||||
/// </remarks>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="regexPatternSelector">A function that selects the regular expression pattern to match against from the request instance.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, TProperty> Matches<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, Func<TRequest, string> regexPatternSelector)
|
||||
{
|
||||
return ruleBuilder.Must((instance, value) => value is string stringValue && Regex.IsMatch(stringValue, regexPatternSelector(instance)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the integer property is within the specified inclusive range.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="minimumValue">The minimum allowed value of the property.</param>
|
||||
/// <param name="maximumValue">The maximum allowed value of the property.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, int> InclusiveBetween<TRequest>(this IRuleBuilder<TRequest, int> ruleBuilder, int minimumValue, int maximumValue)
|
||||
{
|
||||
return ruleBuilder.Must(value => value >= minimumValue && value <= maximumValue);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the nullable integer property is within the specified inclusive range.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If the property is <see langword="null"/>, this rule passes (use <see cref="NotNull{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to check for missing values).
|
||||
/// </remarks>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="minimumValue">The minimum allowed value of the property.</param>
|
||||
/// <param name="maximumValue">The maximum allowed value of the property.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, int?> InclusiveBetween<TRequest>(this IRuleBuilder<TRequest, int?> ruleBuilder, int minimumValue, int maximumValue)
|
||||
{
|
||||
return ruleBuilder.Must(value => !value.HasValue || (value.Value >= minimumValue && value.Value <= maximumValue));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the property is equal to another property of the request.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <param name="comparisonSelector">A function that selects the property the validated property must equal.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, TProperty> Equal<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, Func<TRequest, TProperty> comparisonSelector)
|
||||
{
|
||||
return ruleBuilder.Must((instance, value) => Equals(value, comparisonSelector(instance)));
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -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
|
||||
/// <summary>
|
||||
/// Query for retrieving the list of authorization permissions.
|
||||
/// </summary>
|
||||
public record GetPermissionsQuery : IRequest<ErrorOr<IEnumerable<PermissionResponse>>>;
|
||||
public record GetPermissionsQuery : IQuery;
|
||||
+4
-4
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the query to retrieve the list of authorization permissions.
|
||||
/// </summary>
|
||||
public class GetPermissionsQueryHandler : IRequestHandler<GetPermissionsQuery, ErrorOr<IEnumerable<PermissionResponse>>>
|
||||
public class GetPermissionsQueryHandler : IQueryHandler<GetPermissionsQuery, ErrorOr<IEnumerable<PermissionResponse>>>
|
||||
{
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
@@ -41,12 +41,12 @@ public class GetPermissionsQueryHandler : IRequestHandler<GetPermissionsQuery, E
|
||||
/// <summary>
|
||||
/// Handles the query to retrieve the list of authorization permissions.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="query">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="PermissionResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<IEnumerable<PermissionResponse>>> Handle(GetPermissionsQuery request, CancellationToken cancellationToken)
|
||||
public async Task<ErrorOr<IEnumerable<PermissionResponse>>> 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);
|
||||
|
||||
+2
-4
@@ -1,7 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
@@ -18,4 +16,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
|
||||
public record AddRoleCommand(
|
||||
string RoleName,
|
||||
List<Guid> Permissions
|
||||
) : IRequest<ErrorOr<RolePermissionsResponse>>;
|
||||
) : ICommand;
|
||||
+15
-6
@@ -1,14 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -19,11 +21,12 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
|
||||
/// <summary>
|
||||
/// Handler for the command to add an authorization role.
|
||||
/// </summary>
|
||||
public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, ErrorOr<RolePermissionsResponse>>
|
||||
public class AddRoleCommandHandler : ICommandHandler<AddRoleCommand, ErrorOr<RolePermissionsResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<AddRoleCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddRoleCommandHandler"/> class.
|
||||
@@ -31,11 +34,13 @@ public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, ErrorOr<Rol
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public AddRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public AddRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<AddRoleCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -46,8 +51,12 @@ public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, ErrorOr<Rol
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="RoleResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<RolePermissionsResponse>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
|
||||
public async Task<ErrorOr<RolePermissionsResponse>> HandleAsync(AddRoleCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(request);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// only admins can create authorization roles
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
||||
if (!isAdmin)
|
||||
@@ -59,13 +68,13 @@ public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, ErrorOr<Rol
|
||||
RoleEntity newRole = new()
|
||||
{
|
||||
RoleName = request.RoleName,
|
||||
RolePermissions = request.Permissions.Select(permissionId => new RolePermissionEntity()
|
||||
RolePermissions = [.. request.Permissions.Select(permissionId => new RolePermissionEntity()
|
||||
{
|
||||
PermissionId = permissionId,
|
||||
Permission = null!,
|
||||
Role = null!,
|
||||
RoleId = default
|
||||
}).ToList()
|
||||
})]
|
||||
};
|
||||
// save the new role in the repository
|
||||
ErrorOr<Created> insertRoleResult = await roleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
+9
-7
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
@@ -17,14 +18,15 @@ public class AddRoleCommandValidator : AbstractValidator<AddRoleCommand>
|
||||
public AddRoleCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.RoleName)
|
||||
.NotNull().WithMessage(Errors.Authorization.RoleNameCannotBeNull.Description)
|
||||
.NotEmpty().WithMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description);
|
||||
.NotNull().WithError(Errors.Authorization.RoleNameCannotBeNull)
|
||||
.NotEmpty().WithError(Errors.Authorization.RoleNameCannotBeEmpty);
|
||||
|
||||
RuleFor(x => x.Permissions)
|
||||
.NotNull().WithMessage(Errors.Authorization.PermissionsListCannotBeNull.Description)
|
||||
.NotEmpty().WithMessage(Errors.Authorization.PermissionsListCannotBeEmpty.Description);
|
||||
.NotNull().WithError(Errors.Authorization.PermissionsListCannotBeNull)
|
||||
.NotEmpty().WithError(Errors.Authorization.PermissionsListCannotBeEmpty);
|
||||
|
||||
RuleForEach(x => x.Permissions)
|
||||
.NotEmpty().WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description);
|
||||
.NotEmpty().WithError(Errors.Authorization.PermissionIdCannotBeEmpty)
|
||||
.Must(id => id != Guid.Empty).WithError(Errors.Authorization.PermissionIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -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<ErrorOr<Deleted>>;
|
||||
) : ICommand;
|
||||
+15
-7
@@ -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;
|
||||
/// <summary>
|
||||
/// Handler for the command to delete an authorization role.
|
||||
/// </summary>
|
||||
public class DeleteRoleCommandHandler : IRequestHandler<DeleteRoleCommand, ErrorOr<Deleted>>
|
||||
public class DeleteRoleCommandHandler : ICommandHandler<DeleteRoleCommand, ErrorOr<Deleted>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<DeleteRoleCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteRoleCommandHandler"/> class.
|
||||
@@ -33,21 +35,27 @@ public class DeleteRoleCommandHandler : IRequestHandler<DeleteRoleCommand, Error
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public DeleteRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public DeleteRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<DeleteRoleCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to delete an authorization role.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="command">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async ValueTask<ErrorOr<Deleted>> Handle(DeleteRoleCommand request, CancellationToken cancellationToken)
|
||||
public async Task<ErrorOr<Deleted>> HandleAsync(DeleteRoleCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> 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<DeleteRoleCommand, Error
|
||||
|
||||
// check if a role with the requested Id exists
|
||||
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
|
||||
ErrorOr<RoleEntity?> getExistingRoleResult = await roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
|
||||
ErrorOr<RoleEntity?> 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<DeleteRoleCommand, Error
|
||||
else if (getExistingRoleResult.Value.RoleName == "Admin")
|
||||
return Errors.Authorization.AdminRoleCannotBeDeleted;
|
||||
// delete the role and its permissions
|
||||
ErrorOr<Deleted> deleteRoleResult = await roleRepository.DeleteByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
|
||||
ErrorOr<Deleted> deleteRoleResult = await roleRepository.DeleteByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
|
||||
if (deleteRoleResult.IsError)
|
||||
return deleteRoleResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
+5
-4
@@ -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<DeleteRoleCommand>
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -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<Guid> Permissions
|
||||
) : IRequest<ErrorOr<RolePermissionsResponse>>;
|
||||
) : ICommand;
|
||||
+18
-9
@@ -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;
|
||||
/// <summary>
|
||||
/// Handler for the command to update an authorization role.
|
||||
/// </summary>
|
||||
public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, ErrorOr<RolePermissionsResponse>>
|
||||
public class UpdateRoleCommandHandler : ICommandHandler<UpdateRoleCommand, ErrorOr<RolePermissionsResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<UpdateRoleCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateRoleCommandHandler"/> class.
|
||||
@@ -31,23 +34,29 @@ public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, Error
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public UpdateRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public UpdateRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<UpdateRoleCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to update an authorization role.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="command">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully updated <see cref="RoleResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<RolePermissionsResponse>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
|
||||
public async Task<ErrorOr<RolePermissionsResponse>> HandleAsync(UpdateRoleCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> 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<UpdateRoleCommand, Error
|
||||
// update the role and its permissions
|
||||
RoleEntity newRole = new()
|
||||
{
|
||||
Id = request.RoleId,
|
||||
RoleName = request.RoleName,
|
||||
RolePermissions = request.Permissions.Select(permissionId => 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<UpdateRoleCommand, Error
|
||||
return updateRoleResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// retrieve the updated authorization role from the persistence medium and return it
|
||||
ErrorOr<RoleEntity?> getRoleResult = await roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
|
||||
ErrorOr<RoleEntity?> getRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
|
||||
if (getRoleResult.IsError)
|
||||
return getRoleResult.Errors;
|
||||
if (getRoleResult.Value is null)
|
||||
|
||||
+15
-13
@@ -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<UpdateRoleCommand>
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -1,7 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
@@ -15,4 +13,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermi
|
||||
[DebuggerDisplay("RoleId: {RoleId}")]
|
||||
public record GetRolePermissionsQuery(
|
||||
Guid RoleId
|
||||
) : IRequest<ErrorOr<RolePermissionsResponse>>;
|
||||
) : IQuery;
|
||||
+13
-4
@@ -1,14 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -18,11 +20,12 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermi
|
||||
/// <summary>
|
||||
/// Handler for the query to retrieve the list of authorization permissions for a role.
|
||||
/// </summary>
|
||||
public class GetRolePermissionsQueryHandler : IRequestHandler<GetRolePermissionsQuery, ErrorOr<RolePermissionsResponse>>
|
||||
public class GetRolePermissionsQueryHandler : IQueryHandler<GetRolePermissionsQuery, ErrorOr<RolePermissionsResponse>>
|
||||
{
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IRoleRepository _roleRepository;
|
||||
private readonly IValidator<GetRolePermissionsQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRolePermissionsQueryHandler"/> class.
|
||||
@@ -30,11 +33,13 @@ public class GetRolePermissionsQueryHandler : IRequestHandler<GetRolePermissions
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public GetRolePermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetRolePermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<GetRolePermissionsQuery> validator)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_roleRepository = unitOfWork.GetRepository<IRoleRepository>();
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -45,8 +50,12 @@ public class GetRolePermissionsQueryHandler : IRequestHandler<GetRolePermissions
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="RoleResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<RolePermissionsResponse>> Handle(GetRolePermissionsQuery request, CancellationToken cancellationToken)
|
||||
public async Task<ErrorOr<RolePermissionsResponse>> HandleAsync(GetRolePermissionsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(request);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// only admins can see the list of authorization roles
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
||||
if (!isAdmin)
|
||||
|
||||
+4
-3
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
@@ -17,7 +18,7 @@ public class GetRolePermissionsQueryValidator : AbstractValidator<GetRolePermiss
|
||||
public GetRolePermissionsQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.RoleId)
|
||||
.NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description);
|
||||
.NotEmpty().WithError(Errors.Authorization.RoleIdCannotBeEmpty)
|
||||
.Must(id => id != Guid.Empty).WithError(Errors.Authorization.RoleIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -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;
|
||||
/// <summary>
|
||||
/// Query for retrieving the list of authorization roles.
|
||||
/// </summary>
|
||||
public record GetRolesQuery() : IRequest<ErrorOr<IEnumerable<RoleResponse>>>;
|
||||
public record GetRolesQuery() : IQuery;
|
||||
+4
-4
@@ -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;
|
||||
/// <summary>
|
||||
/// Handler for the query to retrieve the list of authorization roles.
|
||||
/// </summary>
|
||||
public class GetRolesQueryHandler : IRequestHandler<GetRolesQuery, ErrorOr<IEnumerable<RoleResponse>>>
|
||||
public class GetRolesQueryHandler : IQueryHandler<GetRolesQuery, ErrorOr<IEnumerable<RoleResponse>>>
|
||||
{
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
@@ -41,12 +41,12 @@ public class GetRolesQueryHandler : IRequestHandler<GetRolesQuery, ErrorOr<IEnum
|
||||
/// <summary>
|
||||
/// Handles the query to retrieve the list of authorization roles.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="query">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="RoleResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<IEnumerable<RoleResponse>>> Handle(GetRolesQuery request, CancellationToken cancellationToken)
|
||||
public async Task<ErrorOr<IEnumerable<RoleResponse>>> 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);
|
||||
|
||||
+2
-5
@@ -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<ErrorOr<IEnumerable<DirectoryResponse>>>;
|
||||
) : IQuery;
|
||||
+15
-7
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the query to get all directories.
|
||||
/// </summary>
|
||||
public class GetDirectoriesQueryHandler : IRequestHandler<GetDirectoriesQuery, ErrorOr<IEnumerable<DirectoryResponse>>>
|
||||
public class GetDirectoriesQueryHandler : IQueryHandler<GetDirectoriesQuery, ErrorOr<IEnumerable<DirectoryResponse>>>
|
||||
{
|
||||
private readonly IDirectoryService _directoryService;
|
||||
private readonly IValidator<GetDirectoriesQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDirectoriesQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="directoryService">Injected service for handling directories.</param>
|
||||
public GetDirectoriesQueryHandler(IDirectoryService directoryService)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetDirectoriesQueryHandler(IDirectoryService directoryService, IValidator<GetDirectoriesQuery> validator)
|
||||
{
|
||||
_directoryService = directoryService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of directories at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="request">The query containing the requested path.</param>
|
||||
/// <param name="query">The query containing the requested path.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="DirectoryResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<DirectoryResponse>>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken)
|
||||
public Task<ErrorOr<IEnumerable<DirectoryResponse>>> HandleAsync(GetDirectoriesQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<Directory>> getSubdirectoriesResult = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements);
|
||||
return ValueTask.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return Task.FromResult<ErrorOr<IEnumerable<DirectoryResponse>>>(validationResult);
|
||||
|
||||
ErrorOr<IEnumerable<Directory>> getSubdirectoriesResult = _directoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements);
|
||||
return Task.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -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<GetDirectoriesQuer
|
||||
/// </summary>
|
||||
public GetDirectoriesQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
|
||||
RuleFor(query => query.Path)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -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;
|
||||
/// <summary>
|
||||
/// Query for retrieving the list of drives.
|
||||
/// </summary>
|
||||
public record GetDrivesQuery() : IRequest<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>;
|
||||
public record GetDrivesQuery() : IQuery;
|
||||
+5
-5
@@ -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;
|
||||
/// <summary>
|
||||
/// Handler for the query to get all drives.
|
||||
/// </summary>
|
||||
public class GetDrivesQueryHandler : IRequestHandler<GetDrivesQuery, ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>
|
||||
public class GetDrivesQueryHandler : IQueryHandler<GetDrivesQuery, ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>
|
||||
{
|
||||
private readonly IDriveService _driveService;
|
||||
|
||||
@@ -31,14 +31,14 @@ public class GetDrivesQueryHandler : IRequestHandler<GetDrivesQuery, ErrorOr<IEn
|
||||
/// <summary>
|
||||
/// Gets the list of file system drives.
|
||||
/// </summary>
|
||||
/// <param name="request">The query containing the requested path.</param>
|
||||
/// <param name="query">The query containing the requested path.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="FileSystemTreeNodeResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetDrivesQuery request, CancellationToken cancellationToken)
|
||||
public Task<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> HandleAsync(GetDrivesQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<FileSystemItem>> 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));
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -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
|
||||
/// <summary>
|
||||
/// Query for retrieving the file system type.
|
||||
/// </summary>
|
||||
public record GetFileSystemQuery() : IRequest<FileSystemTypeResponse>;
|
||||
public record GetFileSystemQuery() : IQuery;
|
||||
+5
-5
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the query to get the file system type.
|
||||
/// </summary>
|
||||
public class GetFileSystemQueryHandler : IRequestHandler<GetFileSystemQuery, FileSystemTypeResponse>
|
||||
public class GetFileSystemQueryHandler : IQueryHandler<GetFileSystemQuery, FileSystemTypeResponse>
|
||||
{
|
||||
private readonly IPlatformContext _platformContext;
|
||||
|
||||
@@ -27,11 +27,11 @@ public class GetFileSystemQueryHandler : IRequestHandler<GetFileSystemQuery, Fil
|
||||
/// <summary>
|
||||
/// Gets the type of the file system.
|
||||
/// </summary>
|
||||
/// <param name="request">The query to be handled.</param>
|
||||
/// <param name="query">The query to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The type of the file system.</returns>
|
||||
public ValueTask<FileSystemTypeResponse> Handle(GetFileSystemQuery request, CancellationToken cancellationToken)
|
||||
public Task<FileSystemTypeResponse> HandleAsync(GetFileSystemQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
return ValueTask.FromResult(new FileSystemTypeResponse(_platformContext.Platform));
|
||||
return Task.FromResult(new FileSystemTypeResponse(_platformContext.Platform));
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -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<ErrorOr<IEnumerable<FileResponse>>>;
|
||||
) : IQuery;
|
||||
+15
-7
@@ -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;
|
||||
/// <summary>
|
||||
/// Handler for the query to get all files.
|
||||
/// </summary>
|
||||
public class GetFilesQueryHandler : IRequestHandler<GetFilesQuery, ErrorOr<IEnumerable<FileResponse>>>
|
||||
public class GetFilesQueryHandler : IQueryHandler<GetFilesQuery, ErrorOr<IEnumerable<FileResponse>>>
|
||||
{
|
||||
private readonly IFileService _fileService;
|
||||
private readonly IValidator<GetFilesQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFilesQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="fileService">Injected service for handling files.</param>
|
||||
public GetFilesQueryHandler(IFileService fileService)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetFilesQueryHandler(IFileService fileService, IValidator<GetFilesQuery> validator)
|
||||
{
|
||||
_fileService = fileService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of files at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="request">The query containing the requested path.</param>
|
||||
/// <param name="query">The query containing the requested path.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="FileResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<FileResponse>>> Handle(GetFilesQuery request, CancellationToken cancellationToken)
|
||||
public Task<ErrorOr<IEnumerable<FileResponse>>> HandleAsync(GetFilesQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<File>> getFilesResult = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements);
|
||||
return ValueTask.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return Task.FromResult<ErrorOr<IEnumerable<FileResponse>>>(validationResult);
|
||||
|
||||
ErrorOr<IEnumerable<File>> getFilesResult = _fileService.GetFiles(query.Path!, query.IncludeHiddenElements);
|
||||
return Task.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -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<GetFilesQuery>
|
||||
/// </summary>
|
||||
public GetFilesQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
|
||||
RuleFor(query => query.Path)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -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<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>;
|
||||
) : IQuery;
|
||||
+15
-7
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the query to get all files.
|
||||
/// </summary>
|
||||
public class GetTreeFilesQueryHandler : IRequestHandler<GetTreeFilesQuery, ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>
|
||||
public class GetTreeFilesQueryHandler : IQueryHandler<GetTreeFilesQuery, ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>
|
||||
{
|
||||
private readonly IFileService _fileService;
|
||||
private readonly IValidator<GetTreeFilesQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTreeFilesQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="fileService">Injected service for handling files.</param>
|
||||
public GetTreeFilesQueryHandler(IFileService fileService)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetTreeFilesQueryHandler(IFileService fileService, IValidator<GetTreeFilesQuery> validator)
|
||||
{
|
||||
_fileService = fileService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of files at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="request">The query containing the requested path.</param>
|
||||
/// <param name="query">The query containing the requested path.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="FileSystemTreeNodeResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetTreeFilesQuery request, CancellationToken cancellationToken)
|
||||
public Task<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> HandleAsync(GetTreeFilesQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<File>> getFilesResult = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements);
|
||||
return ValueTask.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors));
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return Task.FromResult<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>(validationResult);
|
||||
|
||||
ErrorOr<IEnumerable<File>> getFilesResult = _fileService.GetFiles(query.Path!, query.IncludeHiddenElements);
|
||||
return Task.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors));
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -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<GetTreeFilesQuery>
|
||||
/// </summary>
|
||||
public GetTreeFilesQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
|
||||
RuleFor(query => query.Path)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -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<ErrorOr<PathSegmentResponse>>;
|
||||
) : ICommand;
|
||||
+16
-7
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the command to split a file system path.
|
||||
/// </summary>
|
||||
public class CombinePathCommandHandler : IRequestHandler<CombinePathCommand, ErrorOr<PathSegmentResponse>>
|
||||
public class CombinePathCommandHandler : ICommandHandler<CombinePathCommand, ErrorOr<PathSegmentResponse>>
|
||||
{
|
||||
private readonly IPathService _pathService;
|
||||
private readonly IValidator<CombinePathCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SplitPathCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="pathService">Injected service for handling file system paths.</param>
|
||||
public CombinePathCommandHandler(IPathService pathService)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public CombinePathCommandHandler(IPathService pathService, IValidator<CombinePathCommand> validator)
|
||||
{
|
||||
_pathService = pathService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Combines two file system paths.
|
||||
/// </summary>
|
||||
/// <param name="request">The command containing the requested paths.</param>
|
||||
/// <param name="command">The command containing the requested paths.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a <see cref="PathSegmentResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<PathSegmentResponse>> Handle(CombinePathCommand request, CancellationToken cancellationToken)
|
||||
public Task<ErrorOr<PathSegmentResponse>> HandleAsync(CombinePathCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<string> combinePathResult = _pathService.CombinePath(request.OriginalPath!, request.NewPath!);
|
||||
return ValueTask.FromResult(combinePathResult.Match(values => ErrorOrFactory.From(new PathSegmentResponse(combinePathResult.Value)), errors => errors));
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return Task.FromResult<ErrorOr<PathSegmentResponse>>(validationResult);
|
||||
|
||||
ErrorOr<string> combinePathResult = _pathService.CombinePath(command.OriginalPath!, command.NewPath!);
|
||||
return Task.FromResult(combinePathResult.Match(values => ErrorOrFactory.From(new PathSegmentResponse(combinePathResult.Value)), errors => errors));
|
||||
}
|
||||
}
|
||||
+9
-3
@@ -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<CombinePathCommand>
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -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<ErrorOr<IEnumerable<PathSegmentResponse>>>;
|
||||
) : ICommand;
|
||||
+15
-7
@@ -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;
|
||||
/// <summary>
|
||||
/// Handler for the command to split a file system path.
|
||||
/// </summary>
|
||||
public class SplitPathCommandHandler : IRequestHandler<SplitPathCommand, ErrorOr<IEnumerable<PathSegmentResponse>>>
|
||||
public class SplitPathCommandHandler : ICommandHandler<SplitPathCommand, ErrorOr<IEnumerable<PathSegmentResponse>>>
|
||||
{
|
||||
private readonly IPathService _pathService;
|
||||
private readonly IValidator<SplitPathCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SplitPathCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="pathService">Injected service for handling file system paths.</param>
|
||||
public SplitPathCommandHandler(IPathService pathService)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public SplitPathCommandHandler(IPathService pathService, IValidator<SplitPathCommand> validator)
|
||||
{
|
||||
_pathService = pathService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path components of the specified path.
|
||||
/// </summary>
|
||||
/// <param name="request">The command containing the requested path.</param>
|
||||
/// <param name="command">The command containing the requested path.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="PathSegmentResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>> Handle(SplitPathCommand request, CancellationToken cancellationToken)
|
||||
public Task<ErrorOr<IEnumerable<PathSegmentResponse>>> HandleAsync(SplitPathCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<PathSegment>> parsePathResult = _pathService.ParsePath(request.Path!);
|
||||
return ValueTask.FromResult(parsePathResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return Task.FromResult<ErrorOr<IEnumerable<PathSegmentResponse>>>(validationResult);
|
||||
|
||||
ErrorOr<IEnumerable<PathSegment>> parsePathResult = _pathService.ParsePath(command.Path!);
|
||||
return Task.FromResult(parsePathResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -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<SplitPathCommand>
|
||||
/// </summary>
|
||||
public SplitPathCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
|
||||
RuleFor(command => command.Path)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -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<ErrorOr<PathExistsResponse>>;
|
||||
) : IQuery;
|
||||
+15
-6
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the query to check the existence a file system path.
|
||||
/// </summary>
|
||||
public class CheckPathExistsQueryHandler : IRequestHandler<CheckPathExistsQuery, ErrorOr<PathExistsResponse>>
|
||||
public class CheckPathExistsQueryHandler : IQueryHandler<CheckPathExistsQuery, ErrorOr<PathExistsResponse>>
|
||||
{
|
||||
private readonly IPathService _pathService;
|
||||
private readonly IValidator<CheckPathExistsQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CheckPathExistsQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="pathService">Injected service for managing file system paths.</param>
|
||||
public CheckPathExistsQueryHandler(IPathService pathService)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public CheckPathExistsQueryHandler(IPathService pathService, IValidator<CheckPathExistsQuery> validator)
|
||||
{
|
||||
_pathService = pathService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks the existence of the specified file system path.
|
||||
/// </summary>
|
||||
/// <param name="request">The query containing the request.</param>
|
||||
/// <param name="query">The query containing the request.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either <see langword="true"/> if the specified path exists, <see langword="false"/> if it doesn't, or an error message.
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<PathExistsResponse>> Handle(CheckPathExistsQuery request, CancellationToken cancellationToken)
|
||||
public Task<ErrorOr<PathExistsResponse>> HandleAsync(CheckPathExistsQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
return ValueTask.FromResult(ErrorOrFactory.From(new PathExistsResponse(_pathService.Exists(request.Path!, request.IncludeHiddenElements))));
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return Task.FromResult<ErrorOr<PathExistsResponse>>(validationResult);
|
||||
|
||||
return Task.FromResult(ErrorOrFactory.From(new PathExistsResponse(_pathService.Exists(query.Path!, query.IncludeHiddenElements))));
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -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<CheckPathExistsQu
|
||||
/// </summary>
|
||||
public CheckPathExistsQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
|
||||
RuleFor(query => query.Path)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -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<ErrorOr<IEnumerable<PathSegmentResponse>>>;
|
||||
) : IQuery;
|
||||
+15
-7
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the query to get the parent of a file system path.
|
||||
/// </summary>
|
||||
public class GetPathParentQueryHandler : IRequestHandler<GetPathParentQuery, ErrorOr<IEnumerable<PathSegmentResponse>>>
|
||||
public class GetPathParentQueryHandler : IQueryHandler<GetPathParentQuery, ErrorOr<IEnumerable<PathSegmentResponse>>>
|
||||
{
|
||||
private readonly IPathService _pathService;
|
||||
private readonly IValidator<GetPathParentQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPathParentQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="pathService">Injected service for managing file system paths.</param>
|
||||
public GetPathParentQueryHandler(IPathService pathService)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetPathParentQueryHandler(IPathService pathService, IValidator<GetPathParentQuery> validator)
|
||||
{
|
||||
_pathService = pathService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the parent of the specified file system path.
|
||||
/// </summary>
|
||||
/// <param name="request">The query containing the requested path.</param>
|
||||
/// <param name="query">The query containing the requested path.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="PathSegmentResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>> Handle(GetPathParentQuery request, CancellationToken cancellationToken)
|
||||
public Task<ErrorOr<IEnumerable<PathSegmentResponse>>> HandleAsync(GetPathParentQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<PathSegment>> goUpOneLevelResult = _pathService.GoUpOneLevel(request.Path!);
|
||||
return ValueTask.FromResult(goUpOneLevelResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return Task.FromResult<ErrorOr<IEnumerable<PathSegmentResponse>>>(validationResult);
|
||||
|
||||
ErrorOr<IEnumerable<PathSegment>> goUpOneLevelResult = _pathService.GoUpOneLevel(query.Path!);
|
||||
return Task.FromResult(goUpOneLevelResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -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<GetPathParentQuery>
|
||||
/// </summary>
|
||||
public GetPathParentQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
|
||||
RuleFor(query => query.Path)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -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<ErrorOr<PathSegmentResponse>>;
|
||||
) : IQuery;
|
||||
+16
-7
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the query to get the root of a file system path.
|
||||
/// </summary>
|
||||
public class GetPathRootQueryHandler : IRequestHandler<GetPathRootQuery, ErrorOr<PathSegmentResponse>>
|
||||
public class GetPathRootQueryHandler : IQueryHandler<GetPathRootQuery, ErrorOr<PathSegmentResponse>>
|
||||
{
|
||||
private readonly IPathService _pathService;
|
||||
private readonly IValidator<GetPathRootQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPathRootQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="pathService">Injected service for managing file system paths.</param>
|
||||
public GetPathRootQueryHandler(IPathService pathService)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetPathRootQueryHandler(IPathService pathService, IValidator<GetPathRootQuery> validator)
|
||||
{
|
||||
_pathService = pathService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the root of the specified file system path.
|
||||
/// </summary>
|
||||
/// <param name="request">The query containing the requested path.</param>
|
||||
/// <param name="query">The query containing the requested path.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the root of the specified path, or an error.</returns>
|
||||
public ValueTask<ErrorOr<PathSegmentResponse>> Handle(GetPathRootQuery request, CancellationToken cancellationToken)
|
||||
public Task<ErrorOr<PathSegmentResponse>> HandleAsync(GetPathRootQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<PathSegment> getPathRootResult = _pathService.GetPathRoot(request.Path!);
|
||||
return ValueTask.FromResult(getPathRootResult.Match(values => ErrorOrFactory.From(values.ToResponse()), errors => errors));
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return Task.FromResult<ErrorOr<PathSegmentResponse>>(validationResult);
|
||||
|
||||
ErrorOr<PathSegment> getPathRootResult = _pathService.GetPathRoot(query.Path!);
|
||||
return Task.FromResult(getPathRootResult.Match(values => ErrorOrFactory.From(values.ToResponse()), errors => errors));
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -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<GetPathRootQuery>
|
||||
/// </summary>
|
||||
public GetPathRootQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
|
||||
RuleFor(query => query.Path)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -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
|
||||
/// <summary>
|
||||
/// Query for retrieving the file system path separator.
|
||||
/// </summary>
|
||||
public record GetPathSeparatorQuery() : IRequest<PathSeparatorResponse>;
|
||||
public record GetPathSeparatorQuery() : IQuery;
|
||||
+5
-5
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the query to get the path separator character of a file system path.
|
||||
/// </summary>
|
||||
public class GetPathSeparatorQueryHandler : IRequestHandler<GetPathSeparatorQuery, PathSeparatorResponse>
|
||||
public class GetPathSeparatorQueryHandler : IQueryHandler<GetPathSeparatorQuery, PathSeparatorResponse>
|
||||
{
|
||||
private readonly IPathService _pathService;
|
||||
|
||||
@@ -27,11 +27,11 @@ public class GetPathSeparatorQueryHandler : IRequestHandler<GetPathSeparatorQuer
|
||||
/// <summary>
|
||||
/// Gets the path separator character of a file system path.
|
||||
/// </summary>
|
||||
/// <param name="request">The query containing the request.</param>
|
||||
/// <param name="query">The query containing the request.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The file system path separator character.</returns>
|
||||
public ValueTask<PathSeparatorResponse> Handle(GetPathSeparatorQuery request, CancellationToken cancellationToken)
|
||||
public Task<PathSeparatorResponse> HandleAsync(GetPathSeparatorQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
return ValueTask.FromResult(new PathSeparatorResponse(_pathService.PathSeparator.ToString()));
|
||||
return Task.FromResult(new PathSeparatorResponse(_pathService.PathSeparator.ToString()));
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -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<PathValidResponse>;
|
||||
) : IQuery;
|
||||
+17
-7
@@ -1,7 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Mediator;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -11,29 +14,36 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePat
|
||||
/// <summary>
|
||||
/// Handler for the query to validate a file system path.
|
||||
/// </summary>
|
||||
public class ValidatePathQueryHandler : IRequestHandler<ValidatePathQuery, PathValidResponse>
|
||||
public class ValidatePathQueryHandler : IQueryHandler<ValidatePathQuery, ErrorOr<PathValidResponse>>
|
||||
{
|
||||
private readonly IPathService _pathService;
|
||||
private readonly IValidator<ValidatePathQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ValidatePathQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="pathService">Injected service for managing file system paths.</param>
|
||||
public ValidatePathQueryHandler(IPathService pathService)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public ValidatePathQueryHandler(IPathService pathService, IValidator<ValidatePathQuery> validator)
|
||||
{
|
||||
_pathService = pathService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates the specified file system path.
|
||||
/// </summary>
|
||||
/// <param name="request">The query containing the request.</param>
|
||||
/// <param name="query">The query containing the request.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// <see langword="true"/> if the specified path is valid, <see langword="false"/> otherwise.
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either <see langword="true"/> if the specified path is valid, <see langword="false"/> if it isn't, or an error message.
|
||||
/// </returns>
|
||||
public ValueTask<PathValidResponse> Handle(ValidatePathQuery request, CancellationToken cancellationToken)
|
||||
public Task<ErrorOr<PathValidResponse>> HandleAsync(ValidatePathQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
return ValueTask.FromResult(new PathValidResponse(_pathService.IsValidPath(request.Path!)));
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return Task.FromResult<ErrorOr<PathValidResponse>>(validationResult);
|
||||
|
||||
return Task.FromResult(ErrorOrFactory.From(new PathValidResponse(_pathService.IsValidPath(query.Path!))));
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -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<ValidatePathQuery>
|
||||
/// </summary>
|
||||
public ValidatePathQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
|
||||
RuleFor(query => query.Path)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -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<ErrorOr<ThumbnailResponse>>;
|
||||
) : IQuery;
|
||||
+15
-6
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the query to get the file thumbnail.
|
||||
/// </summary>
|
||||
public class GetThumbnailQueryHandler : IRequestHandler<GetThumbnailQuery, ErrorOr<ThumbnailResponse>>
|
||||
public class GetThumbnailQueryHandler : IQueryHandler<GetThumbnailQuery, ErrorOr<ThumbnailResponse>>
|
||||
{
|
||||
private readonly IThumbnailService _thumbnailsService;
|
||||
private readonly IValidator<GetThumbnailQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetThumbnailQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="thumbnailsService">Injected service for handling thumbnails.</param>
|
||||
public GetThumbnailQueryHandler(IThumbnailService thumbnailsService)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetThumbnailQueryHandler(IThumbnailService thumbnailsService, IValidator<GetThumbnailQuery> validator)
|
||||
{
|
||||
_thumbnailsService = thumbnailsService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the thumbnail for a file located at the specified path, with the specified quality.
|
||||
/// </summary>
|
||||
/// <param name="request">The query to be handled.</param>
|
||||
/// <param name="query">The query to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{T}"/> containing either a thumbnail, or an error.</returns>
|
||||
public async ValueTask<ErrorOr<ThumbnailResponse>> Handle(GetThumbnailQuery request, CancellationToken cancellationToken)
|
||||
public async Task<ErrorOr<ThumbnailResponse>> HandleAsync(GetThumbnailQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<Thumbnail> getThumbnailResult = await _thumbnailsService.GetThumbnailAsync(request.Path!, request.Quality, cancellationToken);
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
ErrorOr<Thumbnail> getThumbnailResult = await _thumbnailsService.GetThumbnailAsync(query.Path!, query.Quality, cancellationToken);
|
||||
return await ValueTask.FromResult(getThumbnailResult.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors));
|
||||
}
|
||||
}
|
||||
+9
-3
@@ -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<GetThumbnailQuery>
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -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<ErrorOr<RegistrationResponse>>;
|
||||
) : ICommand;
|
||||
+18
-9
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the command to perform the initial application setup.
|
||||
/// </summary>
|
||||
public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCommand, ErrorOr<RegistrationResponse>>
|
||||
public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCommand, ErrorOr<RegistrationResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IPasswordHashService _hashService;
|
||||
@@ -31,6 +32,7 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
|
||||
private readonly IQRCodeGenerator _qRCodeGenerator;
|
||||
private readonly IDateTimeProvider _dateTimeProvider;
|
||||
private readonly IDataSeedService _dataSeedService;
|
||||
private readonly IValidator<SetupApplicationCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetupApplicationCommandHandler"/> class.
|
||||
@@ -42,6 +44,7 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
|
||||
/// <param name="qRCodeGenerator">Injected service for generating QR codes.</param>
|
||||
/// <param name="dateTimeProvider">Injected service for time related concerns.</param>
|
||||
/// <param name="dataSeedService">Injected service for the initial persistence medium data seed.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public SetupApplicationCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
IPasswordHashService hashService,
|
||||
@@ -49,7 +52,8 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
|
||||
ITotpTokenGenerator totpTokenGenerator,
|
||||
IQRCodeGenerator qRCodeGenerator,
|
||||
IDateTimeProvider dateTimeProvider,
|
||||
IDataSeedService dataSeedService)
|
||||
IDataSeedService dataSeedService,
|
||||
IValidator<SetupApplicationCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_hashService = hashService;
|
||||
@@ -58,18 +62,23 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
|
||||
_qRCodeGenerator = qRCodeGenerator;
|
||||
_dateTimeProvider = dateTimeProvider;
|
||||
_dataSeedService = dataSeedService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to perform the initial application setup.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="command">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="RegistrationResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<RegistrationResponse>> Handle(SetupApplicationCommand request, CancellationToken cancellationToken)
|
||||
public async Task<ErrorOr<RegistrationResponse>> HandleAsync(SetupApplicationCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> 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<IUserRepository>();
|
||||
ErrorOr<IEnumerable<UserEntity>> selectUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
@@ -83,8 +92,8 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = id,
|
||||
Username = request.Username!,
|
||||
Password = Uri.EscapeDataString(_hashService.HashString(request.Password!)),
|
||||
Username = command.Username!,
|
||||
Password = Uri.EscapeDataString(_hashService.HashString(command.Password!)),
|
||||
CreatedOnUtc = _dateTimeProvider.UtcNow,
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
@@ -93,12 +102,12 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
|
||||
LibraryScans = [],
|
||||
};
|
||||
// if the user enabled two factor auth, include a QR with the totp secret
|
||||
if (request.Use2fa)
|
||||
if (command.Use2fa)
|
||||
{
|
||||
// generate a TOTP secret
|
||||
byte[] secret = _totpTokenGenerator.GenerateSecret();
|
||||
// convert the secret into a QR code for the user to scan
|
||||
totpSecret = _qRCodeGenerator.GenerateQrCodeDataUri(request.Username!, secret);
|
||||
totpSecret = _qRCodeGenerator.GenerateQrCodeDataUri(command.Username!, secret);
|
||||
// store the TOTP secret in the repository, encrypted
|
||||
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
|
||||
}
|
||||
|
||||
+19
-6
@@ -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.Maintenance.ApplicationSetup.Commands.SetupApplication;
|
||||
@@ -15,10 +16,22 @@ public class SetupApplicationCommandValidator : AbstractValidator<SetupApplicati
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -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
|
||||
/// <summary>
|
||||
/// Query for checking the initialization of the application.
|
||||
/// </summary>
|
||||
public record CheckInitializationQuery() : IRequest<InitializationResponse>;
|
||||
public record CheckInitializationQuery() : IQuery;
|
||||
+4
-4
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the query to check the initialization of the application.
|
||||
/// </summary>
|
||||
public class CheckInitializationQueryHandler : IRequestHandler<CheckInitializationQuery, InitializationResponse>
|
||||
public class CheckInitializationQueryHandler : IQueryHandler<CheckInitializationQuery, InitializationResponse>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
@@ -31,12 +31,12 @@ public class CheckInitializationQueryHandler : IRequestHandler<CheckInitializati
|
||||
/// <summary>
|
||||
/// Checks the initialization status of the application.
|
||||
/// </summary>
|
||||
/// <param name="request">The query containing the request.</param>
|
||||
/// <param name="query">The query containing the request.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// <see langword="true"/> if the application is initialized (the admin account is created), <see langword="false"/> otherwise.
|
||||
/// </returns>
|
||||
public async ValueTask<InitializationResponse> Handle(CheckInitializationQuery request, CancellationToken cancellationToken)
|
||||
public async Task<InitializationResponse> HandleAsync(CheckInitializationQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
||||
// if the repository reports an error, or there are no users, the application has not been initialized
|
||||
|
||||
+2
-4
@@ -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<ErrorOr<LibraryResponse>>;
|
||||
) : ICommand;
|
||||
+25
-16
@@ -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;
|
||||
/// <summary>
|
||||
/// Handler for the command to add a media library.
|
||||
/// </summary>
|
||||
public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, ErrorOr<LibraryResponse>>
|
||||
public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, ErrorOr<LibraryResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IEnvironmentContext _environmentContext;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IValidator<AddLibraryCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddLibraryCommandHandler"/> class.
|
||||
@@ -45,30 +48,36 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public AddLibraryCommandHandler(
|
||||
IAuthorizationService authorizationService,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IEnvironmentContext environmentContext,
|
||||
IUnitOfWork unitOfWork)
|
||||
IUnitOfWork unitOfWork,
|
||||
IValidator<AddLibraryCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_environmentContext = environmentContext;
|
||||
_authorizationService = authorizationService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to add a media library.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="LibraryResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<LibraryResponse>> Handle(AddLibraryCommand request, CancellationToken cancellationToken)
|
||||
public async Task<ErrorOr<LibraryResponse>> HandleAsync(AddLibraryCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> 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<AddLibraryCommand, Error
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// make sure the file is an actual supported image
|
||||
if (request.CoverImage is not null)
|
||||
if (command.CoverImage is not null)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(request.CoverImage);
|
||||
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
|
||||
@@ -92,15 +101,15 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
|
||||
// create a domain library object
|
||||
ErrorOr<Library> createLibraryResult = Library.Create(
|
||||
UserId.Create(_currentUserService.UserId!.Value),
|
||||
request.Title!,
|
||||
Enum.Parse<LibraryType>(request.LibraryType!),
|
||||
request.ContentLocations!,
|
||||
request.CoverImage,
|
||||
request.IsEnabled,
|
||||
request.IsLocked,
|
||||
request.DownloadMetadataFromWeb,
|
||||
request.ShouldSaveMetadataInMediaDirectories,
|
||||
request.ShouldSkipUnchangedDirectoriesDuringScan,
|
||||
command.Title!,
|
||||
Enum.Parse<LibraryType>(command.LibraryType!),
|
||||
command.ContentLocations!,
|
||||
command.CoverImage,
|
||||
command.IsEnabled,
|
||||
command.IsLocked,
|
||||
command.DownloadMetadataFromWeb,
|
||||
command.ShouldSaveMetadataInMediaDirectories,
|
||||
command.ShouldSkipUnchangedDirectoriesDuringScan,
|
||||
[]
|
||||
);
|
||||
|
||||
|
||||
+22
-14
@@ -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<AddLibraryCommand>
|
||||
/// </summary>
|
||||
public AddLibraryCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.LibraryType)
|
||||
.NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description)
|
||||
.Must(x => Enum.TryParse<LibraryType>(x, out _))
|
||||
.WithMessage(Errors.Library.UnknownLibraryType.Description);
|
||||
RuleFor(command => command.LibraryType)
|
||||
.NotNull()
|
||||
.WithError(Errors.Library.LibraryTypeCannotBeNull)
|
||||
.Must(libraryType => Enum.TryParse<LibraryType>(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);
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -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
|
||||
/// <summary>
|
||||
/// Command for canceling the previously started scan of all media libraries.
|
||||
/// </summary>
|
||||
public record CancelLibrariesScanCommand : IRequest<ErrorOr<Success>>;
|
||||
public record CancelLibrariesScanCommand : ICommand;
|
||||
+4
-4
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the command for canceling the scan of all media libraries.
|
||||
/// </summary>
|
||||
public class CancelLibrariesScanCommandHandler : IRequestHandler<CancelLibrariesScanCommand, ErrorOr<Success>>
|
||||
public class CancelLibrariesScanCommandHandler : ICommandHandler<CancelLibrariesScanCommand, ErrorOr<Success>>
|
||||
{
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
@@ -51,10 +51,10 @@ public class CancelLibrariesScanCommandHandler : IRequestHandler<CancelLibraries
|
||||
/// <summary>
|
||||
/// Handles the command for canceling the scan of all media libraries.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async ValueTask<ErrorOr<Success>> Handle(CancelLibrariesScanCommand request, CancellationToken cancellationToken)
|
||||
public async Task<ErrorOr<Success>> HandleAsync(CancelLibrariesScanCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
|
||||
|
||||
+2
-3
@@ -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<ErrorOr<Success>>;
|
||||
) : ICommand;
|
||||
+16
-6
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the command for canceling the scan of a media library.
|
||||
/// </summary>
|
||||
public class CancelLibraryScanCommandHandler : IRequestHandler<CancelLibraryScanCommand, ErrorOr<Success>>
|
||||
public class CancelLibraryScanCommandHandler : ICommandHandler<CancelLibraryScanCommand, ErrorOr<Success>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<CancelLibraryScanCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CancelLibraryScanCommandHandler"/> class.
|
||||
@@ -35,30 +38,37 @@ public class CancelLibraryScanCommandHandler : IRequestHandler<CancelLibraryScan
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public CancelLibraryScanCommandHandler(
|
||||
IAuthorizationService authorizationService,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IUnitOfWork unitOfWork)
|
||||
IUnitOfWork unitOfWork,
|
||||
IValidator<CancelLibraryScanCommand> validator)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_unitOfWork = unitOfWork;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command for canceling the scan of a media library.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async ValueTask<ErrorOr<Success>> Handle(CancelLibraryScanCommand request, CancellationToken cancellationToken)
|
||||
public async Task<ErrorOr<Success>> HandleAsync(CancelLibraryScanCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
|
||||
// get the library scan from the repository
|
||||
ErrorOr<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(request.ScanId, cancellationToken).ConfigureAwait(false);
|
||||
ErrorOr<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryScansResult.IsError)
|
||||
return getLibraryScansResult.Errors;
|
||||
if (getLibraryScansResult.Value is null)
|
||||
|
||||
+13
-7
@@ -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<CancelLibrary
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -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<ErrorOr<Deleted>>;
|
||||
) : ICommand;
|
||||
+17
-7
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the command to delete a library by its Id.
|
||||
/// </summary>
|
||||
public class DeleteLibraryCommandHandler : IRequestHandler<DeleteLibraryCommand, ErrorOr<Deleted>>
|
||||
public class DeleteLibraryCommandHandler : ICommandHandler<DeleteLibraryCommand, ErrorOr<Deleted>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<DeleteLibraryCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteLibraryCommandHandler"/> class.
|
||||
@@ -35,29 +38,36 @@ public class DeleteLibraryCommandHandler : IRequestHandler<DeleteLibraryCommand,
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public DeleteLibraryCommandHandler(
|
||||
IAuthorizationService authorizationService,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IUnitOfWork unitOfWork)
|
||||
IUnitOfWork unitOfWork,
|
||||
IValidator<DeleteLibraryCommand> validator)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_unitOfWork = unitOfWork;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to delete a library by its Id.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async ValueTask<ErrorOr<Deleted>> Handle(DeleteLibraryCommand request, CancellationToken cancellationToken)
|
||||
public async Task<ErrorOr<Deleted>> HandleAsync(DeleteLibraryCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// get the library with the specified id from the repository
|
||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
|
||||
ErrorOr<LibraryEntity?> 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<DeleteLibraryCommand,
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
// perform the deletion
|
||||
ErrorOr<Deleted> deletePersistenceLibraryResult = await libraryRepository.DeleteByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
|
||||
ErrorOr<Deleted> deletePersistenceLibraryResult = await libraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (deletePersistenceLibraryResult.IsError)
|
||||
return deletePersistenceLibraryResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
+7
-4
@@ -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<DeleteLibraryComm
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -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
|
||||
/// <summary>
|
||||
/// Command for initiating the scan of all media libraries.
|
||||
/// </summary>
|
||||
public record ScanLibrariesCommand() : IRequest<ErrorOr<IEnumerable<MediaLibraryScanResponse>>>;
|
||||
public record ScanLibrariesCommand() : ICommand;
|
||||
+4
-4
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the command for initiating the scan of all media libraries.
|
||||
/// </summary>
|
||||
public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand, ErrorOr<IEnumerable<MediaLibraryScanResponse>>>
|
||||
public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand, ErrorOr<IEnumerable<MediaLibraryScanResponse>>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
@@ -54,10 +54,10 @@ public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand,
|
||||
/// <summary>
|
||||
/// Handles the command for initiating the scan of all media libraries.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async ValueTask<ErrorOr<IEnumerable<MediaLibraryScanResponse>>> Handle(ScanLibrariesCommand request, CancellationToken cancellationToken)
|
||||
public async Task<ErrorOr<IEnumerable<MediaLibraryScanResponse>>> HandleAsync(ScanLibrariesCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
|
||||
+2
-4
@@ -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;
|
||||
/// <param name="Id">The unique identifier of the library to scan.</param>
|
||||
public record ScanLibraryCommand(
|
||||
Guid Id
|
||||
) : IRequest<ErrorOr<MediaLibraryScanResponse>>;
|
||||
) : ICommand;
|
||||
+17
-8
@@ -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;
|
||||
/// <summary>
|
||||
/// Handler for the command for initiating the scan of a media library.
|
||||
/// </summary>
|
||||
public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, ErrorOr<MediaLibraryScanResponse>>
|
||||
public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, ErrorOr<MediaLibraryScanResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<ScanLibraryCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScanLibraryCommandHandler"/> class.
|
||||
@@ -42,31 +44,38 @@ public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, Err
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public ScanLibraryCommandHandler(
|
||||
IAuthorizationService authorizationService,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IUnitOfWork unitOfWork)
|
||||
IUnitOfWork unitOfWork,
|
||||
IValidator<ScanLibraryCommand> validator)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_unitOfWork = unitOfWork;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command for initiating the scan of a media library.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async ValueTask<ErrorOr<MediaLibraryScanResponse>> Handle(ScanLibraryCommand request, CancellationToken cancellationToken)
|
||||
public async Task<ErrorOr<MediaLibraryScanResponse>> HandleAsync(ScanLibraryCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
|
||||
// get the media library from the persistence medium
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError)
|
||||
return getLibraryResult.Errors;
|
||||
|
||||
@@ -91,7 +100,7 @@ public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, Err
|
||||
return domainLibraryResult.Errors;
|
||||
|
||||
// get the past month's scans for this library
|
||||
ErrorOr<IEnumerable<LibraryScanEntity>> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
|
||||
ErrorOr<IEnumerable<LibraryScanEntity>> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (pastLibraryScansResult.IsError)
|
||||
return pastLibraryScansResult.Errors;
|
||||
|
||||
@@ -103,7 +112,7 @@ public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, Err
|
||||
|
||||
// queue the media library scan
|
||||
ErrorOr<LibraryScan> libraryScanResult = LibraryScan.Create(
|
||||
LibraryId.Create(request.Id),
|
||||
LibraryId.Create(command.Id),
|
||||
UserId.Create(_currentUserService.UserId!.Value),
|
||||
[.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)]
|
||||
);
|
||||
|
||||
+7
-4
@@ -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<ScanLibraryCommand>
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -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<ErrorOr<LibraryResponse>>;
|
||||
) : ICommand;
|
||||
+29
-19
@@ -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
|
||||
/// <summary>
|
||||
/// Handler for the command to update a media library.
|
||||
/// </summary>
|
||||
public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand, ErrorOr<LibraryResponse>>
|
||||
public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand, ErrorOr<LibraryResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IEnvironmentContext _environmentContext;
|
||||
private readonly IValidator<UpdateLibraryCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateLibraryCommandHandler"/> class.
|
||||
@@ -48,34 +51,41 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public UpdateLibraryCommandHandler(
|
||||
IAuthorizationService authorizationService,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IEnvironmentContext environmentContext,
|
||||
IUnitOfWork unitOfWork)
|
||||
IUnitOfWork unitOfWork,
|
||||
IValidator<UpdateLibraryCommand> validator)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_unitOfWork = unitOfWork;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_environmentContext = environmentContext;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to update a media library.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully updated <see cref="LibraryResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<LibraryResponse>> Handle(UpdateLibraryCommand request, CancellationToken cancellationToken)
|
||||
public async Task<ErrorOr<LibraryResponse>> HandleAsync(UpdateLibraryCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> 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<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(request.CoverImage);
|
||||
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
|
||||
@@ -88,7 +98,7 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
|
||||
|
||||
// get a library repository and retrieve the library to update
|
||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
|
||||
ErrorOr<LibraryEntity?> 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<UpdateLibraryCommand,
|
||||
|
||||
// create a domain library object
|
||||
ErrorOr<Library> createLibraryResult = Library.Create(
|
||||
LibraryId.Create(request.Id),
|
||||
UserId.Create(request.OwnerId),
|
||||
request.Title!,
|
||||
Enum.Parse<LibraryType>(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<LibraryType>(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)
|
||||
|
||||
+33
-21
@@ -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<UpdateLibraryComm
|
||||
/// </summary>
|
||||
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<LibraryType>(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>(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);
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -6,7 +6,7 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
|
||||
using Mediator;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Threading;
|
||||
@@ -16,9 +16,9 @@ using System.Threading.Tasks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the event raised when a media library is deleted.
|
||||
/// Handler for the domain event raised when a media library is deleted.
|
||||
/// </summary>
|
||||
public class LibraryDeletedDomainEventHandler : INotificationHandler<LibraryDeletedDomainEvent>
|
||||
public class LibraryDeletedDomainEventHandler : IDomainEventHandler<LibraryDeletedDomainEvent>
|
||||
{
|
||||
private readonly IEnvironmentContext _environmentContext;
|
||||
private readonly IPathService _pathService;
|
||||
@@ -42,7 +42,7 @@ public class LibraryDeletedDomainEventHandler : INotificationHandler<LibraryDele
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public ValueTask Handle(LibraryDeletedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
public ValueTask HandleAsync(LibraryDeletedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
// delete the media library directory in the internal location for media library files
|
||||
ErrorOr<string> libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value);
|
||||
|
||||
+4
-4
@@ -5,12 +5,12 @@ using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Errors;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -23,9 +23,9 @@ using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the event raised when a media library is created or updated.
|
||||
/// Handler for the domain event raised when a media library is created or updated.
|
||||
/// </summary>
|
||||
public class LibrarySavedDomainEventHandler : INotificationHandler<LibrarySavedDomainEvent>
|
||||
public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDomainEvent>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IEnvironmentContext _environmentContext;
|
||||
@@ -56,7 +56,7 @@ public class LibrarySavedDomainEventHandler : INotificationHandler<LibrarySavedD
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask Handle(LibrarySavedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
public async ValueTask HandleAsync(LibrarySavedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
if (domainEvent.Library.CoverImage is not null)
|
||||
{
|
||||
|
||||
+4
-4
@@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.SharedKernel.Common.Errors;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
@@ -13,7 +14,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Mediator;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -21,9 +21,9 @@ using System.Threading.Tasks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the event raised when a media library scan is cancelled.
|
||||
/// Handler for the domain event raised when a media library scan is cancelled.
|
||||
/// </summary>
|
||||
public class LibraryScanCancelledDomainEventHandler : INotificationHandler<LibraryScanCancelledDomainEvent>
|
||||
public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<LibraryScanCancelledDomainEvent>
|
||||
{
|
||||
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||
@@ -56,7 +56,7 @@ public class LibraryScanCancelledDomainEventHandler : INotificationHandler<Libra
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask Handle(LibraryScanCancelledDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
public async ValueTask HandleAsync(LibraryScanCancelledDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
// get the library scan from the repository
|
||||
ErrorOr<LibraryScanEntity?> getLibraryScansResult = await _libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
+4
-4
@@ -6,12 +6,12 @@ using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Progress;
|
||||
using Lumina.Domain.SharedKernel.Common.Errors;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
using Mediator;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -19,9 +19,9 @@ using System.Threading.Tasks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the event raised when a media library scan has failed.
|
||||
/// Handler for the domain event raised when a media library scan has failed.
|
||||
/// </summary>
|
||||
public class LibraryScanFailedDomainEventHandler : INotificationHandler<LibraryScanFailedDomainEvent>
|
||||
public class LibraryScanFailedDomainEventHandler : IDomainEventHandler<LibraryScanFailedDomainEvent>
|
||||
{
|
||||
private readonly IMediaLibraryScanProgressNotifier _debouncedLibraryScanProgressNotifier;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||
@@ -52,7 +52,7 @@ public class LibraryScanFailedDomainEventHandler : INotificationHandler<LibraryS
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask Handle(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
public async ValueTask HandleAsync(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository = _unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
||||
|
||||
+4
-4
@@ -6,12 +6,12 @@ using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Progress;
|
||||
using Lumina.Domain.SharedKernel.Common.Errors;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
using Mediator;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -19,9 +19,9 @@ using System.Threading.Tasks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the event raised when a media library scan is finished.
|
||||
/// Handler for the domain event raised when a media library scan is finished.
|
||||
/// </summary>
|
||||
public class LibraryScanFinishedDomainEventHandler : INotificationHandler<LibraryScanFinishedDomainEvent>
|
||||
public class LibraryScanFinishedDomainEventHandler : IDomainEventHandler<LibraryScanFinishedDomainEvent>
|
||||
{
|
||||
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||
@@ -52,7 +52,7 @@ public class LibraryScanFinishedDomainEventHandler : INotificationHandler<Librar
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask Handle(LibraryScanFinishedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
public async ValueTask HandleAsync(LibraryScanFinishedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
|
||||
|
||||
+4
-4
@@ -1,8 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Progress;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
using Mediator;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -10,9 +10,9 @@ using System.Threading.Tasks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the event raised when a media library's scan progress changes.
|
||||
/// Handler for the domain event raised when a media library's scan progress changes.
|
||||
/// </summary>
|
||||
public class LibraryScanJobProgressChangedDomainEventHandler : INotificationHandler<LibraryScanJobProgressChangedDomainEvent>
|
||||
public class LibraryScanJobProgressChangedDomainEventHandler : IDomainEventHandler<LibraryScanJobProgressChangedDomainEvent>
|
||||
{
|
||||
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
||||
private readonly IMediaLibraryScanProgressNotifier _debouncedLibraryScanProgressNotifier;
|
||||
@@ -35,7 +35,7 @@ public class LibraryScanJobProgressChangedDomainEventHandler : INotificationHand
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask Handle(LibraryScanJobProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
public async ValueTask HandleAsync(LibraryScanJobProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
_mediaLibrariesScanProgressTracker.UpdateScanJobProgress(domainEvent.LibraryId, domainEvent.MediaLibraryScanCompositeId, domainEvent.Progress);
|
||||
// notify SignalR clients that the library scan progress changed
|
||||
|
||||
+4
-4
@@ -1,8 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Progress;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
using Mediator;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -10,9 +10,9 @@ using System.Threading.Tasks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the event raised when a media library's scan progress changes.
|
||||
/// Handler for the domain event raised when a media library's scan progress changes.
|
||||
/// </summary>
|
||||
public class LibraryScanProgressChangedDomainEventHandler : INotificationHandler<LibraryScanProgressChangedDomainEvent>
|
||||
public class LibraryScanProgressChangedDomainEventHandler : IDomainEventHandler<LibraryScanProgressChangedDomainEvent>
|
||||
{
|
||||
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
||||
private readonly IMediaLibraryScanProgressNotifier _debouncedLibraryScanProgressNotifier;
|
||||
@@ -35,7 +35,7 @@ public class LibraryScanProgressChangedDomainEventHandler : INotificationHandler
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask Handle(LibraryScanProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
public async ValueTask HandleAsync(LibraryScanProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
_mediaLibrariesScanProgressTracker.UpdateScanProgress(domainEvent.LibraryId, domainEvent.MediaLibraryScanCompositeId);
|
||||
// notify SignalR clients that the library scan progress changed
|
||||
|
||||
Loaded 100 of 347 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user