From 8fe90a4dde826dacaf45a2af727680f001e4b7e8 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 13 Aug 2026 14:18:41 -0700 Subject: [PATCH 1/2] Defines base implementation for Result, with samples. --- .../Common/Primitives/ConflictError.cs | 10 + .../Common/Primitives/Created.cs | 6 + .../Common/Primitives/Deleted.cs | 6 + src/Lumina.Domain/Common/Primitives/Error.cs | 136 ++++++++++ .../Common/Primitives/FailureError.cs | 10 + .../Common/Primitives/ForbiddenError.cs | 10 + .../Common/Primitives/InternalError.cs | 10 + .../Primitives/InvalidOperationError.cs | 10 + .../Common/Primitives/NotFoundError.cs | 10 + .../Common/Primitives/NotImplementedError.cs | 10 + .../Primitives/ResourceUnavailableError.cs | 10 + src/Lumina.Domain/Common/Primitives/Result.cs | 237 ++++++++++++++++++ .../Common/Primitives/Results.cs | 27 ++ .../Common/Primitives/Success.cs | 6 + .../Common/Primitives/TimeoutError.cs | 10 + .../Common/Primitives/UnauthorizedError.cs | 10 + .../Common/Primitives/Updated.cs | 6 + .../Common/Primitives/ValidationError.cs | 10 + .../BookLibraryAggregate/Book.cs | 9 +- .../Controllers/Plugins/PluginsController.cs | 2 - 20 files changed, 538 insertions(+), 7 deletions(-) create mode 100644 src/Lumina.Domain/Common/Primitives/ConflictError.cs create mode 100644 src/Lumina.Domain/Common/Primitives/Created.cs create mode 100644 src/Lumina.Domain/Common/Primitives/Deleted.cs create mode 100644 src/Lumina.Domain/Common/Primitives/Error.cs create mode 100644 src/Lumina.Domain/Common/Primitives/FailureError.cs create mode 100644 src/Lumina.Domain/Common/Primitives/ForbiddenError.cs create mode 100644 src/Lumina.Domain/Common/Primitives/InternalError.cs create mode 100644 src/Lumina.Domain/Common/Primitives/InvalidOperationError.cs create mode 100644 src/Lumina.Domain/Common/Primitives/NotFoundError.cs create mode 100644 src/Lumina.Domain/Common/Primitives/NotImplementedError.cs create mode 100644 src/Lumina.Domain/Common/Primitives/ResourceUnavailableError.cs create mode 100644 src/Lumina.Domain/Common/Primitives/Result.cs create mode 100644 src/Lumina.Domain/Common/Primitives/Results.cs create mode 100644 src/Lumina.Domain/Common/Primitives/Success.cs create mode 100644 src/Lumina.Domain/Common/Primitives/TimeoutError.cs create mode 100644 src/Lumina.Domain/Common/Primitives/UnauthorizedError.cs create mode 100644 src/Lumina.Domain/Common/Primitives/Updated.cs create mode 100644 src/Lumina.Domain/Common/Primitives/ValidationError.cs diff --git a/src/Lumina.Domain/Common/Primitives/ConflictError.cs b/src/Lumina.Domain/Common/Primitives/ConflictError.cs new file mode 100644 index 00000000..8a999742 --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/ConflictError.cs @@ -0,0 +1,10 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Error representing that the operation could not be completed due to a conflict with the current state. +/// +public record ConflictError(string Code, string Description) : Error +{ + public override string Code { get; } = Code; + public override string Description { get; } = Description; +} diff --git a/src/Lumina.Domain/Common/Primitives/Created.cs b/src/Lumina.Domain/Common/Primitives/Created.cs new file mode 100644 index 00000000..e5b184b4 --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/Created.cs @@ -0,0 +1,6 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Represents a successful creation operation result. +/// +public readonly record struct Created; diff --git a/src/Lumina.Domain/Common/Primitives/Deleted.cs b/src/Lumina.Domain/Common/Primitives/Deleted.cs new file mode 100644 index 00000000..49ec7ae6 --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/Deleted.cs @@ -0,0 +1,6 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Represents a successful deletion operation result. +/// +public readonly record struct Deleted; diff --git a/src/Lumina.Domain/Common/Primitives/Error.cs b/src/Lumina.Domain/Common/Primitives/Error.cs new file mode 100644 index 00000000..97eb1dba --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/Error.cs @@ -0,0 +1,136 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Represents an error that can be implicitly converted to a Results. +/// +public abstract record Error +{ + /// + /// Gets the error code that uniquely identifies this error type. + /// + public abstract string Code { get; } + + /// + /// Gets the human-readable description of the error. + /// + public abstract string Description { get; } + + /// + /// Returns a string representation of the error. + /// + /// A formatted string containing the error code and description. + public override string ToString() + { + return $"{Code}: {Description}"; + } + + /// + /// Creates a new NotFoundError with the specified description. + /// + /// The human-readable description of the error. + /// A new NotFoundError instance with code "NotFound". + public static NotFoundError NotFound(string description) + { + return new("NotFound", description); + } + + /// + /// Creates a new InvalidOperationError with the specified description. + /// + /// The human-readable description of the error. + /// A new InvalidOperationError instance with code "InvalidOperation". + public static InvalidOperationError InvalidOperation(string description) + { + return new("InvalidOperation", description); + } + + /// + /// Creates a new ForbiddenError with the specified description. + /// + /// The human-readable description of the error. + /// A new ForbiddenError instance with code "Forbidden". + public static ForbiddenError Forbidden(string description) + { + return new("Forbidden", description); + } + + /// + /// Creates a new FailureError with the specified description. + /// + /// The human-readable description of the error. + /// A new FailureError instance with code "Failure". + public static FailureError Failure(string description) + { + return new("Failure", description); + } + + /// + /// Creates a new ValidationError with the specified description. + /// + /// The human-readable description of the error. + /// A new ValidationError instance with code "Validation". + public static ValidationError Validation(string description) + { + return new("Validation", description); + } + + /// + /// Creates a new ConflictError with the specified description. + /// + /// The human-readable description of the error. + /// A new ConflictError instance with code "Conflict". + public static ConflictError Conflict(string description) + { + return new("Conflict", description); + } + + /// + /// Creates a new TimeoutError with the specified description. + /// + /// The human-readable description of the error. + /// A new TimeoutError instance with code "Timeout". + public static TimeoutError Timeout(string description) + { + return new("Timeout", description); + } + + /// + /// Creates a new UnauthorizedError with the specified description. + /// + /// The human-readable description of the error. + /// A new UnauthorizedError instance with code "Unauthorized". + public static UnauthorizedError Unauthorized(string description) + { + return new("Unauthorized", description); + } + + /// + /// Creates a new InternalError with the specified description. + /// + /// The human-readable description of the error. + /// A new InternalError instance with code "Internal". + public static InternalError Internal(string description) + { + return new("Internal", description); + } + + /// + /// Creates a new ResourceUnavailableError with the specified description. + /// + /// The human-readable description of the error. + /// A new ResourceUnavailableError instance with code "ResourceUnavailable". + public static ResourceUnavailableError ResourceUnavailable(string description) + { + return new("ResourceUnavailable", description); + } + + /// + /// Creates a new NotImplementedError with the specified description. + /// + /// The human-readable description of the error. + /// A new NotImplementedError instance with code "NotImplemented". + public static NotImplementedError NotImplemented(string description) + { + return new("NotImplemented", description); + } +} diff --git a/src/Lumina.Domain/Common/Primitives/FailureError.cs b/src/Lumina.Domain/Common/Primitives/FailureError.cs new file mode 100644 index 00000000..548d18aa --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/FailureError.cs @@ -0,0 +1,10 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Error representing that some operation failing. +/// +public record FailureError(string Code, string Description) : Error +{ + public override string Code { get; } = Code; + public override string Description { get; } = Description; +} diff --git a/src/Lumina.Domain/Common/Primitives/ForbiddenError.cs b/src/Lumina.Domain/Common/Primitives/ForbiddenError.cs new file mode 100644 index 00000000..c96bdf2a --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/ForbiddenError.cs @@ -0,0 +1,10 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Error representing that the operation is not allowed due to insufficient permissions or restrictions. +/// +public record ForbiddenError(string Code, string Description) : Error +{ + public override string Code { get; } = Code; + public override string Description { get; } = Description; +} diff --git a/src/Lumina.Domain/Common/Primitives/InternalError.cs b/src/Lumina.Domain/Common/Primitives/InternalError.cs new file mode 100644 index 00000000..0446e119 --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/InternalError.cs @@ -0,0 +1,10 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Error representing that an unexpected internal error occurred. +/// +public record InternalError(string Code, string Description) : Error +{ + public override string Code { get; } = Code; + public override string Description { get; } = Description; +} diff --git a/src/Lumina.Domain/Common/Primitives/InvalidOperationError.cs b/src/Lumina.Domain/Common/Primitives/InvalidOperationError.cs new file mode 100644 index 00000000..7992af5e --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/InvalidOperationError.cs @@ -0,0 +1,10 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Error representing that the operation is invalid in the current state or context. +/// +public record InvalidOperationError(string Code, string Description) : Error +{ + public override string Code { get; } = Code; + public override string Description { get; } = Description; +} diff --git a/src/Lumina.Domain/Common/Primitives/NotFoundError.cs b/src/Lumina.Domain/Common/Primitives/NotFoundError.cs new file mode 100644 index 00000000..e9724789 --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/NotFoundError.cs @@ -0,0 +1,10 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Error representing that the requested resource or entity was not found. +/// +public record NotFoundError(string Code, string Description) : Error +{ + public override string Code { get; } = Code; + public override string Description { get; } = Description; +} diff --git a/src/Lumina.Domain/Common/Primitives/NotImplementedError.cs b/src/Lumina.Domain/Common/Primitives/NotImplementedError.cs new file mode 100644 index 00000000..5798c3d8 --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/NotImplementedError.cs @@ -0,0 +1,10 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Error representing that the requested functionality is not implemented. +/// +public record NotImplementedError(string Code, string Description) : Error +{ + public override string Code { get; } = Code; + public override string Description { get; } = Description; +} diff --git a/src/Lumina.Domain/Common/Primitives/ResourceUnavailableError.cs b/src/Lumina.Domain/Common/Primitives/ResourceUnavailableError.cs new file mode 100644 index 00000000..4f08be8d --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/ResourceUnavailableError.cs @@ -0,0 +1,10 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Error representing that the required resource is currently unavailable. +/// +public record ResourceUnavailableError(string Code, string Description) : Error +{ + public override string Code { get; } = Code; + public override string Description { get; } = Description; +} diff --git a/src/Lumina.Domain/Common/Primitives/Result.cs b/src/Lumina.Domain/Common/Primitives/Result.cs new file mode 100644 index 00000000..b7a28bc9 --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/Result.cs @@ -0,0 +1,237 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Primitive struct for explicitly handling success and failure cases in a functional manner. +/// +/// The type of the success value. +public readonly struct Result : IEquatable> +{ + private readonly TValue? _value; + private readonly List? _errors; + + /// + /// Gets a value indicating whether this result represents a success. + /// + public bool IsSuccess { get; } + + /// + /// Gets a value indicating whether this result represents a failure. + /// + public bool IsFailure => !IsSuccess; + + /// + /// Gets the success value. Only valid when IsSuccess is true. + /// + public TValue Value => IsSuccess ? _value! : throw new InvalidOperationException("Cannot access Value of a failed result."); + + /// + /// Gets the list of errors. Only valid when IsFailure is true. + /// + public List Errors => IsFailure + ? _errors ?? [] + : throw new InvalidOperationException("Cannot access Errors of a successful result."); + + /// + /// Returns the first error, if present. + /// + public Error FirstError => Errors[0]; + + /// + /// Initializes a new instance of the structure. + /// + /// The success value. + /// The list of errors. + /// Whether this represents a success or failure. + private Result(TValue? value, List? errors, bool isSuccess) + { + _value = value; + _errors = errors; + IsSuccess = isSuccess; + } + + /// + /// Creates a successful result with the specified value. + /// + /// The success value. + /// A successful result containing the specified value. + public static Result Success(TValue value) + { + return new Result(value, default, true); + } + + /// + /// Creates a failed result with the specified errors. + /// + /// The errors value. + /// A failed result containing the specified error. + public static Result Failure(List errors) + { + return new Result(default, errors, false); + } + + /// + /// Creates a failed result with the specified errors. + /// + /// The errors value. + /// A failed result containing the specified error. + public static Result Failure(params Error[] errors) + { + return new(default, [.. errors], false); + } + + /// + /// Custom implementation operator for converting to a . + /// + /// The value to be converted. + public static implicit operator Result(TValue value) + { + return Success(value); + } + + /// + /// Custom implementation operator for converting to a failed . + /// + /// The error to be converted. + public static implicit operator Result(Error error) + { + return Failure(error); + } + + /// + /// Custom implementation operator for converting to a failed . + /// + /// The errors to be converted. + public static implicit operator Result(List errors) + { + return Failure(errors); + } + + /// + /// Maps the success value to a new type using the provided function. + /// + /// The type of the new success value. + /// The function to transform the success value. + /// A new result with the transformed value, or the original errors. + public Result Map(Func mapper) + { + return IsSuccess + ? Result.Success(mapper(Value)) + : Result.Failure(Errors); + } + + /// + /// Chains another operation that returns a Result, allowing for monadic composition. + /// + /// The type of the new success value. + /// The function that returns a new Results. + /// The result of the chained operation, or the original error. + public Result Bind(Func> binder) + { + return IsSuccess ? binder(Value) : Result.Failure(Errors); + } + + /// + /// Executes an action if the result is successful, otherwise does nothing. + /// + /// The action to execute on success. + /// The original result for chaining. + public Result OnSuccess(Action action) + { + if (IsSuccess) + action(Value); + return this; + } + + /// + /// Executes an action if the result is a failure, otherwise does nothing. + /// + /// The action to execute on failure. + /// The original result for chaining. + public Result OnFailure(Action> action) + { + if (IsFailure) + action(Errors); + return this; + } + + /// + /// Matches the result and executes the appropriate function. + /// + /// The type of the result. + /// Function to execute on success. + /// Function to execute on failure. + /// The result of the executed function. + public TResult Match(Func onSuccess, Func, TResult> onFailure) + { + return IsSuccess ? onSuccess(Value) : onFailure(Errors); + } + + /// + /// Determines whether the specified Result is equal to the current Results. + /// + /// The Result to compare with the current Results. + /// true if the specified Result is equal to the current Result; otherwise, false. + public bool Equals(Result other) + { + if (IsSuccess != other.IsSuccess) + return false; + + return IsSuccess + ? EqualityComparer.Default.Equals(Value, other.Value) + : Errors.SequenceEqual(other.Errors); + } + + /// + /// Determines whether the specified object is equal to the current Results. + /// + /// The object to compare with the current Results. + /// true if the specified object is equal to the current Result; otherwise, false. + public override bool Equals(object? obj) + { + return obj is Result other && Equals(other); + } + + /// + /// Determines whether two specified Result instances are equal. + /// + /// The first Result to compare. + /// The second Result to compare. + /// true if the two Result instances are equal; otherwise, false. + public static bool operator ==(Result left, Result right) + { + return left.Equals(right); + } + + /// + /// Determines whether two specified Result instances are not equal. + /// + /// The first Result to compare. + /// The second Result to compare. + /// true if the two Result instances are not equal; otherwise, false. + public static bool operator !=(Result left, Result right) + { + return !(left == right); + } + + /// + /// Returns the hash code for this Results. + /// + /// A 32-bit signed integer hash code. + public override int GetHashCode() + { + return IsSuccess + ? HashCode.Combine(IsSuccess, Value) + : HashCode.Combine(IsSuccess, Errors); + } + + /// + /// Customized ToString() method. + /// + /// Custom string value showing relevant data for current result. + public override string ToString() + { + return IsSuccess + ? $"Success: {Value?.ToString()}" + : $"Failure: [{string.Join(", ", Errors.Select(error => error.ToString()))}]"; + } +} diff --git a/src/Lumina.Domain/Common/Primitives/Results.cs b/src/Lumina.Domain/Common/Primitives/Results.cs new file mode 100644 index 00000000..eae5de3c --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/Results.cs @@ -0,0 +1,27 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Provides predefined success results for operations that don't return meaningful data. +/// +public static class Results +{ + /// + /// Represents a successful operation. + /// + public static Success Success { get; } = new(); + + /// + /// Represents a successful creation operation. + /// + public static Created Created { get; } = new(); + + /// + /// Represents a successful update operation. + /// + public static Updated Updated { get; } = new(); + + /// + /// Represents a successful deletion operation. + /// + public static Deleted Deleted { get; } = new(); +} diff --git a/src/Lumina.Domain/Common/Primitives/Success.cs b/src/Lumina.Domain/Common/Primitives/Success.cs new file mode 100644 index 00000000..b505ba31 --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/Success.cs @@ -0,0 +1,6 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Represents a successful operation result. +/// +public readonly record struct Success; diff --git a/src/Lumina.Domain/Common/Primitives/TimeoutError.cs b/src/Lumina.Domain/Common/Primitives/TimeoutError.cs new file mode 100644 index 00000000..610b06c0 --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/TimeoutError.cs @@ -0,0 +1,10 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Error representing that the operation timed out before completion. +/// +public record TimeoutError(string Code, string Description) : Error +{ + public override string Code { get; } = Code; + public override string Description { get; } = Description; +} diff --git a/src/Lumina.Domain/Common/Primitives/UnauthorizedError.cs b/src/Lumina.Domain/Common/Primitives/UnauthorizedError.cs new file mode 100644 index 00000000..686ad165 --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/UnauthorizedError.cs @@ -0,0 +1,10 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Error representing that authentication is required or has failed. +/// +public record UnauthorizedError(string Code, string Description) : Error +{ + public override string Code { get; } = Code; + public override string Description { get; } = Description; +} diff --git a/src/Lumina.Domain/Common/Primitives/Updated.cs b/src/Lumina.Domain/Common/Primitives/Updated.cs new file mode 100644 index 00000000..073fdc9a --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/Updated.cs @@ -0,0 +1,6 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Represents a successful update operation result. +/// +public readonly record struct Updated; diff --git a/src/Lumina.Domain/Common/Primitives/ValidationError.cs b/src/Lumina.Domain/Common/Primitives/ValidationError.cs new file mode 100644 index 00000000..3a5d1de7 --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/ValidationError.cs @@ -0,0 +1,10 @@ +namespace Lumina.Domain.Common.Primitives; + +/// +/// Error representing that the input or data failed validation rules. +/// +public record ValidationError(string Code, string Description) : Error +{ + public override string Code { get; } = Code; + public override string Description { get; } = Description; +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs index 5cf9e804..c6b1a436 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; @@ -233,9 +232,9 @@ public sealed class Book : AggregateRoot /// The list of objects representing the unique identifiers of the media contributors of the book. /// The list of ratings for the book. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( LibraryId libraryId, string path, WrittenContentMetadata metadata, @@ -309,9 +308,9 @@ public sealed class Book : AggregateRoot /// The list of objects representing the unique identifiers of the media contributors of the book. /// The list of ratings for the book. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( BookId id, LibraryId libraryId, string path, diff --git a/src/Lumina.Presentation.Web/Controllers/Plugins/PluginsController.cs b/src/Lumina.Presentation.Web/Controllers/Plugins/PluginsController.cs index 6c103c82..4bfaff8b 100644 --- a/src/Lumina.Presentation.Web/Controllers/Plugins/PluginsController.cs +++ b/src/Lumina.Presentation.Web/Controllers/Plugins/PluginsController.cs @@ -45,10 +45,8 @@ public class PluginsController : Controller // load the settings of the loaded plugins, so that the settings forms can be rendered on the server Dictionary settingsByPluginId = []; foreach (PluginModel plugin in plugins) - { if (plugin.LoadStatus == PluginLoadStatus.Loaded) settingsByPluginId[plugin.Id] = await _apiHttpClient.GetAsync($"plugins/{plugin.Id}/settings", cancellationToken).ConfigureAwait(false); - } ViewData["pluginSettings"] = settingsByPluginId; return View(plugins); From 3b772d68caa8dabad216035b3d388e458305880f Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 14 Aug 2026 03:04:28 -0700 Subject: [PATCH 2/2] Replaces ErrorOr library with a custom implementation. --- .../Authorization/IPermissionRepository.cs | 6 +- .../Authorization/IRoleRepository.cs | 6 +- .../Repositories/Books/IBookRepository.cs | 18 +- .../Actions/IDeleteAllRepositoryAction.cs | 6 +- .../Actions/IDeleteByIdRepositoryAction.cs | 6 +- .../Common/Actions/IGetAllRepositoryAction.cs | 6 +- .../Actions/IGetByIdRepositoryAction.cs | 6 +- .../Actions/IInsertRangeRepositoryAction.cs | 6 +- .../Common/Actions/IInsertRepositoryAction.cs | 6 +- .../Common/Actions/IUpdateRepositoryAction.cs | 6 +- .../IDirectoryScanFingerprintRepository.cs | 10 +- .../MediaLibrary/ILibraryRepository.cs | 10 +- .../MediaLibrary/ILibraryScanRepository.cs | 10 +- .../ILibraryScanSnapshotRepository.cs | 14 +- .../ILibraryScanStagingResultsRepository.cs | 22 +- ...MetadataProviderConfigurationRepository.cs | 14 +- .../Repositories/Plugins/IPluginRepository.cs | 10 +- .../Repositories/Users/IUserRepository.cs | 6 +- .../DataAccess/Seed/IDataSeedService.cs | 18 +- .../Common/Errors/Errors.Authentication.cs | 2 +- .../Common/Errors/Errors.Authorization.cs | 2 +- .../Common/Errors/Errors.Persistence.cs | 2 +- .../Authorization/IAuthorizationService.cs | 6 +- .../Validation/AbstractValidator.cs | 2 +- .../Infrastructure/Validation/IRuleBuilder.cs | 2 +- .../Validation/IValidationRule.cs | 2 +- .../Infrastructure/Validation/IValidator.cs | 2 +- .../Validation/ValidationRule.cs | 2 +- .../Validation/ValidationRuleForEach.cs | 2 +- .../Common/Metadata/GenreDtoMapping.cs | 10 +- .../Common/Metadata/GenreEntityMapping.cs | 10 +- .../Mapping/Common/Metadata/TagDtoMapping.cs | 10 +- .../Common/Metadata/TagEntityMapping.cs | 10 +- .../FileSystemTreeNodeResponseMapping.cs | 6 +- .../Management/LibraryEntityMapping.cs | 10 +- .../Management/LibraryScanEntityMapping.cs | 10 +- .../BookLibrary/Books/BookEntityMapping.cs | 60 ++-- .../Books/BookMetadataDtoMapping.cs | 44 +-- .../Common/BookRatingDtoMapping.cs | 12 +- .../Common/BookRatingEntityMapping.cs | 12 +- .../BookLibrary/Common/IsbnDtoMapping.cs | 10 +- .../BookLibrary/Common/IsbnEntityMapping.cs | 10 +- .../GetPermissionsQueryHandler.cs | 12 +- .../Commands/AddRole/AddRoleCommandHandler.cs | 16 +- .../DeleteRole/DeleteRoleCommandHandler.cs | 16 +- .../UpdateRole/UpdateRoleCommandHandler.cs | 16 +- .../GetRolePermissionsQueryHandler.cs | 12 +- .../Queries/GetRoles/GetRolesQueryHandler.cs | 12 +- .../GetDirectoriesQueryHandler.cs | 14 +- .../GetDirectoriesQueryValidator.cs | 2 +- .../GetDrives/GetDrivesQueryHandler.cs | 12 +- .../Queries/GetFiles/GetFilesQueryHandler.cs | 14 +- .../GetFiles/GetFilesQueryValidator.cs | 2 +- .../GetTreeFiles/GetTreeFilesQueryHandler.cs | 14 +- .../GetTreeFilesQueryValidator.cs | 2 +- .../CombinePath/CombinePathCommandHandler.cs | 14 +- .../CombinePathCommandValidator.cs | 2 +- .../SplitPath/SplitPathCommandHandler.cs | 14 +- .../SplitPath/SplitPathCommandValidator.cs | 2 +- .../CheckPathExistsQueryHandler.cs | 12 +- .../CheckPathExistsQueryValidator.cs | 2 +- .../GetPathParentQueryHandler.cs | 14 +- .../GetPathParentQueryValidator.cs | 2 +- .../GetPathRoot/GetPathRootQueryHandler.cs | 14 +- .../GetPathRoot/GetPathRootQueryValidator.cs | 2 +- .../ValidatePath/ValidatePathQueryHandler.cs | 12 +- .../ValidatePathQueryValidator.cs | 2 +- .../GetThumbnail/GetThumbnailQueryHandler.cs | 12 +- .../GetThumbnailQueryValidator.cs | 2 +- .../SetupApplicationCommandHandler.cs | 32 +- .../CheckInitializationQueryHandler.cs | 6 +- .../AddLibrary/AddLibraryCommandHandler.cs | 30 +- .../AddLibrary/AddLibraryCommandValidator.cs | 2 +- .../CancelLibrariesScanCommandHandler.cs | 26 +- .../CancelLibraryScanCommandHandler.cs | 26 +- .../CancelLibraryScanCommandValidator.cs | 2 +- .../DeleteLibraryCommandHandler.cs | 26 +- .../DeleteLibraryCommandValidator.cs | 2 +- .../ScanLibrariesCommandHandler.cs | 40 +-- .../ScanLibrary/ScanLibraryCommandHandler.cs | 40 +-- .../ScanLibraryCommandValidator.cs | 2 +- .../UpdateLibraryCommandHandler.cs | 34 +- .../UpdateLibraryCommandValidator.cs | 2 +- .../LibraryDeletedDomainEventHandler.cs | 30 +- .../Events/LibrarySavedDomainEventHandler.cs | 104 +++--- .../LibraryScanCancelledDomainEventHandler.cs | 20 +- .../LibraryScanFailedDomainEventHandler.cs | 24 +- .../LibraryScanFinishedDomainEventHandler.cs | 20 +- .../LibraryScanQueuedDomainEventHandler.cs | 14 +- .../LibraryScanStartedDomainEventHandler.cs | 6 +- .../GetEnabledLibrariesQueryHandler.cs | 16 +- .../GetLibraries/GetLibrariesQueryHandler.cs | 16 +- .../GetLibrary/GetLibraryQueryHandler.cs | 14 +- .../GetLibrary/GetLibraryQueryValidator.cs | 2 +- .../GetLibraryScanProgressQueryHandler.cs | 18 +- .../GetLibraryScanProgressQueryValidator.cs | 2 +- .../GetRunningLibraryScansQueryHandler.cs | 24 +- .../Commands/AddBook/AddBookCommandHandler.cs | 50 +-- .../AddBook/AddBookCommandValidator.cs | 2 +- .../Queries/GetBooks/GetBooksQueryHandler.cs | 12 +- ...rLibraryMetadataProvidersCommandHandler.cs | 16 +- ...ibraryMetadataProvidersCommandValidator.cs | 2 +- ...ryMetadataProviderEnabledCommandHandler.cs | 20 +- ...MetadataProviderEnabledCommandValidator.cs | 2 +- .../UpdatePluginSettingsCommandHandler.cs | 12 +- .../UpdatePluginSettingsCommandValidator.cs | 2 +- ...GetLibraryMetadataProvidersQueryHandler.cs | 16 +- .../GetPluginSettingsQueryHandler.cs | 14 +- .../GetPlugins/GetPluginsQueryHandler.cs | 12 +- .../ChangePasswordCommandHandler.cs | 16 +- .../RecoverPasswordCommandHandler.cs | 16 +- .../RegisterUserCommandHandler.cs | 16 +- .../Queries/GetUsers/GetUsersQueryHandler.cs | 12 +- .../LoginUser/LoginUserQueryHandler.cs | 12 +- ...ateUserRoleAndPermissionsCommandHandler.cs | 30 +- ...eUserRoleAndPermissionsCommandValidator.cs | 2 +- .../GetAuthorizationQueryHandler.cs | 16 +- .../GetAuthorizationQueryValidator.cs | 2 +- .../GetUserPermissionsQueryHandler.cs | 14 +- .../GetUserPermissionsQueryValidator.cs | 2 +- .../GetUserRole/GetUserRoleQueryHandler.cs | 14 +- .../GetUserRole/GetUserRoleQueryValidator.cs | 2 +- .../Authorization/PermissionRepository.cs | 14 +- .../Authorization/RolePermissionRepository.cs | 8 +- .../Authorization/RoleRepository.cs | 26 +- .../Authorization/UserRoleRepository.cs | 8 +- .../Core/Repositories/Books/BookRepository.cs | 36 +- .../DirectoryScanFingerprintRepository.cs | 10 +- .../Libraries/LibraryRepository.cs | 32 +- .../Libraries/LibraryScanRepository.cs | 24 +- .../Libraries/LibraryScanResultRepository.cs | 8 +- .../LibraryScanSnapshotRepository.cs | 14 +- .../LibraryScanStagingResultsRepository.cs | 26 +- ...MetadataProviderConfigurationRepository.cs | 14 +- .../Repositories/Plugins/PluginRepository.cs | 20 +- .../Core/Repositories/Users/UserRepository.cs | 24 +- .../Core/Seed/DataSeedService.cs | 50 +-- .../Common/Enums/Primitives/ErrorType.cs | 42 +++ .../Lumina.Domain.SharedKernel.csproj | 4 - .../Errors/Errors.FileSystemManagement.cs | 4 +- .../Common/Errors/Errors.Library.cs | 4 +- .../Common/Errors/Errors.LibraryScanning.cs | 4 +- .../Common/Errors/Errors.MediaContributor.cs | 4 +- .../Common/Errors/Errors.Metadata.cs | 4 +- .../Common/Errors/Errors.Permission.cs | 4 +- .../Common/Errors/Errors.Plugins.cs | 4 +- .../Common/Errors/Errors.Thumbnails.cs | 4 +- .../Common/Errors/Errors.Users.cs | 4 +- .../Common/Errors/Errors.WrittenContent.cs | 4 +- .../EventualConsistencyException.cs | 2 +- .../Common/Primitives/ConflictError.cs | 18 + src/Lumina.Domain/Common/Primitives/Error.cs | 121 ++++--- .../Common/Primitives/FailureError.cs | 18 + .../Common/Primitives/ForbiddenError.cs | 18 + .../Common/Primitives/InternalError.cs | 18 + .../Primitives/InvalidOperationError.cs | 18 + .../Common/Primitives/NotFoundError.cs | 18 + .../Common/Primitives/NotImplementedError.cs | 18 + .../Primitives/ResourceUnavailableError.cs | 18 + .../{Results.cs => Result.Markers.cs} | 15 +- src/Lumina.Domain/Common/Primitives/Result.cs | 6 + .../Common/Primitives/TimeoutError.cs | 18 + .../Common/Primitives/UnauthorizedError.cs | 18 + .../Common/Primitives/UnexpectedError.cs | 28 ++ .../Common/Primitives/ValidationError.cs | 18 + .../Common/ValueObjects/Metadata/Genre.cs | 9 +- .../ValueObjects/Metadata/LanguageInfo.cs | 16 +- .../ValueObjects/Metadata/ReleaseInfo.cs | 14 +- .../Common/ValueObjects/Metadata/Tag.cs | 10 +- .../ValueObjects/AudioMetadata.cs | 6 +- .../Entities/Directory.cs | 34 +- .../Entities/File.cs | 36 +- .../Entities/UnixRootItem.cs | 14 +- .../Entities/WindowsRootItem.cs | 22 +- .../FileSystemItem.cs | 16 +- .../Services/DirectoryProviderService.cs | 72 ++-- .../Services/DirectoryService.cs | 194 +++++------ .../Services/DriveService.cs | 22 +- .../Services/FileProviderService.cs | 64 ++-- .../Services/FileService.cs | 205 ++++++------ .../FileSystemStructureSeedService.cs | 28 +- .../Services/FileTypeService.cs | 12 +- .../Services/IDirectoryProviderService.cs | 42 +-- .../Services/IDirectoryService.cs | 34 +- .../Services/IDriveService.cs | 6 +- .../Services/IFileProviderService.cs | 46 +-- .../Services/IFileService.cs | 30 +- .../IFileSystemStructureSeedService.cs | 6 +- .../Services/IFileTypeService.cs | 10 +- .../Services/IPathService.cs | 18 +- .../Services/IThumbnailService.cs | 10 +- .../Services/PathService.cs | 48 +-- .../Services/ThumbnailService.cs | 24 +- .../Strategies/Path/IPathStrategy.cs | 18 +- .../Strategies/Path/UnixPathStrategy.cs | 32 +- .../Strategies/Path/WindowsPathStrategy.cs | 36 +- .../ValueObjects/FileSystemPathId.cs | 8 +- .../ValueObjects/PathSegment.cs | 8 +- .../ValueObjects/StreamInfo.cs | 10 +- .../LibraryAggregate/Library.cs | 22 +- .../LibraryScanAggregate/LibraryScan.cs | 32 +- .../Services/IMediaLibraryScanningService.cs | 10 +- .../Services/MediaLibraryScanningService.cs | 14 +- .../IMediaLibrariesScanProgressTracker.cs | 22 +- .../MediaLibrariesScanProgressTracker.cs | 41 ++- .../MediaLibraryScanJobProgress.cs | 8 +- .../ValueObjects/MediaLibraryScanProgress.cs | 9 +- .../MediaContributor.cs | 5 +- .../ValueObjects/ContributorName.cs | 3 +- .../UserAggregate/User.cs | 10 +- .../MovieLibraryAggregate/Movie.cs | 6 +- .../ValueObjects/VideoMetadata.cs | 7 +- .../Entities/BookSeries.cs | 20 +- .../ValueObjects/BookLibraryId.cs | 6 +- .../ValueObjects/BookRating.cs | 9 +- .../BookLibraryAggregate/ValueObjects/Isbn.cs | 6 +- .../ValueObjects/WrittenContentMetadata.cs | 6 +- src/Lumina.Domain/Lumina.Domain.csproj | 1 - .../Common/Errors/Errors.Configuration.cs | 2 +- .../Common/Errors/Errors.LibraryScanning.cs | 2 +- .../Common/Validation/ValidationOptions.cs | 2 +- .../Authorization/AuthorizationService.cs | 20 +- .../Policies/Over18/Over18Policy.cs | 6 +- .../Jobs/Common/MediaLibraryScanDiffJob.cs | 20 +- .../Jobs/Common/MediaLibraryScanHashJob.cs | 28 +- .../MediaLibraryScanMetadataEnrichmentJob.cs | 40 +-- .../Common/MediaLibraryScanResultsSaveJob.cs | 36 +- .../Books/BooksFileSystemDiscoveryJob.cs | 46 +-- ...bouncedMediaLibraryScanProgressNotifier.cs | 14 +- .../Core/Plugins/PluginDetectionSyncJob.cs | 6 +- .../Core/Plugins/PluginSettingsStore.cs | 6 +- .../GetPermissions/GetPermissionsEndpoint.cs | 8 +- .../Roles/AddRole/AddRoleEndpoint.cs | 8 +- .../Roles/DeleteRole/DeleteRoleEndpoint.cs | 8 +- .../GetRolePermissionsEndpoint.cs | 8 +- .../Roles/GetRoles/GetRolesEndpoint.cs | 8 +- .../Roles/UpdateRole/UpdateRoleEndpoint.cs | 8 +- .../Core/Endpoints/Common/BaseEndpoint.cs | 3 +- .../GetDirectories/GetDirectoriesEndpoint.cs | 19 +- .../Drives/GetDrives/GetDrivesEndpoint.cs | 10 +- .../FileSystem/GetType/GetTypeEndpoint.cs | 6 +- .../Files/GetFiles/GetFilesEndpoint.cs | 11 +- .../GetTreeFiles/GetTreeFilesEndpoint.cs | 11 +- .../CheckPathExistsEndpoint.cs | 11 +- .../Path/CombinePath/CombinePathEndpoint.cs | 8 +- .../GetPathParent/GetPathParentEndpoint.cs | 11 +- .../Path/GetPathRoot/GetPathRootEndpoint.cs | 11 +- .../Path/SplitPath/SplitPathEndpoint.cs | 8 +- .../Path/ValidatePath/ValidatePathEndpoint.cs | 11 +- .../GetThumbnail/GetThumbnailEndpoint.cs | 11 +- .../AddLibrary/AddLibraryEndpoint.cs | 8 +- .../CancelLibrariesScanEndpoint.cs | 10 +- .../CancelLibraryScanEndpoint.cs | 9 +- .../DeleteLibrary/DeleteLibraryEndpoint.cs | 12 +- .../GetEnabledLibrariesEndpoint.cs | 10 +- .../GetLibraries/GetLibrariesEndpoint.cs | 10 +- .../GetLibrary/GetLibraryEndpoint.cs | 11 +- .../GetLibraryScanProgressEndpoint.cs | 11 +- .../GetRunningLibraryScansEndpoint.cs | 11 +- .../ScanLibraries/ScanLibrariesEndpoint.cs | 8 +- .../ScanLibrary/ScanLibraryEndpoint.cs | 8 +- .../UpdateLibrary/UpdateLibraryEndpoint.cs | 8 +- .../Books/AddBook/AddBookEndpoint.cs | 8 +- .../Books/GetBook/GetBookEndpoint.cs | 2 +- .../Books/GetBooks/GetBooksEndpoint.cs | 11 +- .../SetupApplicationEndpoint.cs | 14 +- .../GetLibraryMetadataProvidersEndpoint.cs | 11 +- .../GetPluginSettingsEndpoint.cs | 11 +- .../Plugins/GetPlugins/GetPluginsEndpoint.cs | 10 +- ...ReorderLibraryMetadataProvidersEndpoint.cs | 8 +- ...tLibraryMetadataProviderEnabledEndpoint.cs | 8 +- .../UpdatePluginSettingsEndpoint.cs | 8 +- .../ChangePassword/ChangePasswordEndpoint.cs | 8 +- .../GetUsers/GetUsersEndpoint.cs | 10 +- .../Authentication/Login/LoginEndpoint.cs | 14 +- .../RecoverPasswordEndpoint.cs | 8 +- .../Register/RegisterEndpoint.cs | 8 +- .../GetAuthorizationEndpoint.cs | 11 +- .../GetUserPermissionsEndpoint.cs | 11 +- .../GetUserRole/GetUserRoleEndpoint.cs | 12 +- .../UpdateUserRoleAndPermissionsEndpoint.cs | 8 +- src/Lumina.Presentation.Api/Program.cs | 6 +- .../Common/Converters/BookJsonConverter.cs | 34 +- .../BookLibrary/Books/AddBookEndpointTests.cs | 4 +- .../Common/Metadata/GenreDtoMappingTests.cs | 32 +- .../Metadata/GenreEntityMappingTests.cs | 20 +- .../Common/Metadata/GenreMappingTests.cs | 10 +- .../Common/Metadata/TagDtoMappingTests.cs | 32 +- .../Common/Metadata/TagEntityMappingTests.cs | 20 +- .../Common/Metadata/TagMappingTests.cs | 12 +- .../FileSystemTreeNodeResponseMappingTests.cs | 12 +- .../FileSystem/UnixRootItemMappingTests.cs | 8 +- .../FileSystem/WindowsRootItemMappingTests.cs | 12 +- .../Paths/PathSegmentMappingTests.cs | 12 +- .../Management/LibraryMappingTests.cs | 16 +- .../Books/BookEntityMappingTests.cs | 10 +- .../Books/BookMetadataDtoMappingTests.cs | 10 +- .../Common/BookRatingDtoMappingTests.cs | 32 +- .../Common/BookRatingEntityMappingTests.cs | 16 +- .../BookLibrary/Common/IsbnDtoMappingTests.cs | 36 +- .../Common/IsbnEntityMappingTests.cs | 20 +- .../Common/Setup/ValidatorTestExtensions.cs | 2 +- .../GetPermissionsQueryHandlerTests.cs | 22 +- .../AddRole/AddRoleCommandHandlerTests.cs | 22 +- .../AddRole/AddRoleCommandValidatorTests.cs | 2 +- .../DeleteRoleCommandHandlerTests.cs | 26 +- .../DeleteRoleCommandValidatorTests.cs | 2 +- .../UpdateRoleCommandHandlerTests.cs | 22 +- .../UpdateRoleCommandValidatorTests.cs | 2 +- .../GetRolePermissionsQueryHandlerTests.cs | 18 +- .../GetRolePermissionsQueryValidatorTests.cs | 2 +- .../GetRoles/GetRolesQueryHandlerTests.cs | 16 +- .../Directories/Fixtures/DirectoryFixture.cs | 15 +- .../GetDirectoriesQueryHandlerTests.cs | 36 +- .../GetDirectoriesQueryValidatorTests.cs | 4 +- .../GetDrives/GetDrivesQueryHandlerTests.cs | 24 +- .../Fixtures/UnixRootItemFixture.cs | 8 +- .../Fixtures/WindowsRootItemFixture.cs | 8 +- .../Files/Fixtures/FileFixture.cs | 9 +- .../GetFiles/GetFilesQueryHandlerTests.cs | 34 +- .../GetFiles/GetFilesQueryValidatorTests.cs | 4 +- .../GetTreeFilesQueryHandlerTests.cs | 36 +- .../GetTreeFilesQueryValidatorTests.cs | 4 +- .../Fixtures/FileSystemPathIdFixture.cs | 6 +- .../CombinePathCommandHandlerTests.cs | 20 +- .../CombinePathCommandValidatorTests.cs | 4 +- .../SplitPath/SplitPathCommandHandlerTests.cs | 24 +- .../SplitPathCommandValidatorTests.cs | 4 +- .../Pahs/Fixtures/PathSegmentFixture.cs | 6 +- .../CheckPathExistsQueryHandlerTests.cs | 28 +- .../CheckPathExistsQueryValidatorTests.cs | 4 +- .../GetPathParentQueryHandlerTests.cs | 20 +- .../GetPathParentQueryValidatorTests.cs | 4 +- .../GetPathRootQueryHandlerTests.cs | 20 +- .../GetPathRootQueryValidatorTests.cs | 4 +- .../ValidatePathQueryHandlerTests.cs | 25 +- .../ValidatePathQueryValidatorTests.cs | 4 +- .../GetThumbnailQueryHandlerTests.cs | 16 +- .../GetThumbnailQueryValidatorTests.cs | 4 +- .../SetupApplicationCommandHandlerTests.cs | 74 +++-- .../SetupApplicationCommandValidatorTests.cs | 2 +- .../CheckInitializationQueryHandlerTests.cs | 6 +- .../Fixtures/DomainLibraryFixture.cs | 8 +- .../AddBook/AddBookCommandHandlerTests.cs | 40 +-- .../AddBook/AddBookCommandValidatorTests.cs | 60 ++-- .../Commands/AddBook/Fixtures/BookFixture.cs | 19 +- ...aryMetadataProvidersCommandHandlerTests.cs | 6 +- ...adataProviderEnabledCommandHandlerTests.cs | 10 +- ...UpdatePluginSettingsCommandHandlerTests.cs | 6 +- .../GetPlugins/GetPluginsQueryHandlerTests.cs | 11 +- .../ChangePasswordCommandHandlerTests.cs | 30 +- .../ChangePasswordCommandValidatorTests.cs | 2 +- .../RecoverPasswordCommandHandlerTests.cs | 48 +-- .../RecoverPasswordCommandValidatorTests.cs | 2 +- .../RegisterUserCommandHandlerTests.cs | 30 +- .../RegisterUserCommandValidatorTests.cs | 2 +- .../GetUsers/GetUsersQueryHandlerTests.cs | 16 +- .../LoginUser/LoginUserQueryHandlerTests.cs | 60 ++-- .../LoginUser/LoginUserQueryValidatorTests.cs | 2 +- ...erRoleAndPermissionsCommandHandlerTests.cs | 46 +-- ...RoleAndPermissionsCommandValidatorTests.cs | 4 +- .../GetAuthorizationQueryHandlerTests.cs | 32 +- .../GetAuthorizationQueryValidatorTests.cs | 4 +- .../GetUserPermissionsQueryHandlerTests.cs | 18 +- .../GetUserPermissionsQueryValidatorTests.cs | 4 +- .../GetUserRoleQueryHandlerTests.cs | 22 +- .../GetUserRoleQueryValidatorTests.cs | 4 +- .../PermissionRepositoryTests.cs | 30 +- .../RolePermissionRepositoryTests.cs | 6 +- .../Authorization/RoleRepositoryTests.cs | 63 ++-- .../Authorization/UserRoleRepositoryTests.cs | 10 +- .../Repositories/Books/BookRepositoryTests.cs | 60 ++-- ...ataProviderConfigurationRepositoryTests.cs | 19 +- .../Plugins/PluginRepositoryTests.cs | 25 +- .../Repositories/Users/UserRepositoryTests.cs | 60 ++-- .../Core/Seed/DataSeedServiceTests.cs | 62 ++-- .../Fixtures/BookFixture.cs | 8 +- .../Entities/DirectoryTests.cs | 47 ++- .../Entities/FileTests.cs | 53 ++- .../Entities/Fixtures/DirectoryFixture.cs | 11 +- .../Entities/Fixtures/FileFixture.cs | 9 +- .../Entities/UnixRootItemTests.cs | 34 +- .../Entities/WindowsRootItemTests.cs | 46 +-- .../FileSystemItemTests.cs | 17 +- .../Services/DirectoryProviderServiceTests.cs | 164 +++++----- .../Services/DirectoryServiceTests.cs | 235 ++++++++------ .../Services/DriveServiceTests.cs | 12 +- .../Services/FileProviderServiceTests.cs | 167 +++++----- .../Services/FileServiceTests.cs | 307 +++++++++--------- .../Services/FileTypeServiceTests.cs | 40 +-- .../Services/PathServiceTests.cs | 82 ++--- .../Services/ThumbnailServiceTests.cs | 44 +-- .../Strategies/Path/UnixPathStrategyTests.cs | 80 ++--- .../Path/WindowsPathStrategyTests.cs | 128 ++++---- .../ValueObjects/FileSystemPathIdTests.cs | 12 +- .../Fixtures/FileSystemPathIdFixture.cs | 6 +- .../Fixtures/PathSegmentFixture.cs | 8 +- .../Fixtures/StreamInfoFixture.cs | 7 +- .../ValueObjects/PathSegmentTests.cs | 12 +- .../ValueObjects/StreamInfoTests.cs | 19 +- .../Validation/ValidationOptionsTests.cs | 2 +- .../CommonSettingsDtoValidatorTests.cs | 2 +- .../DatabaseSettingsDtoValidatorTests.cs | 2 +- .../EncryptionSettingsDtoValidatorTests.cs | 2 +- .../JwtSettingsDtoValidatorTests.cs | 2 +- .../MediaSettingsDtoValidatorTests.cs | 2 +- .../AuthorizationServiceTests.cs | 58 ++-- .../GetPermissionsEndpointTests.cs | 12 +- .../Roles/AddRole/AddRoleEndpointTests.cs | 12 +- .../DeleteRole/DeleteRoleEndpointTests.cs | 12 +- .../GetRolePermissionsEndpointTests.cs | 12 +- .../Roles/GetRoles/GetRolesEndpointTests.cs | 12 +- .../UpdateRole/UpdateRoleEndpointTests.cs | 13 +- .../Endpoints/Common/BaseEndpointTests.cs | 3 +- .../Common/Fixtures/BaseEndpointFixture.cs | 2 +- .../GetDirectoriesEndpointTests.cs | 14 +- .../Drives/GetDrivesEndpointTests.cs | 12 +- .../Files/GetFilesEndpointTests.cs | 16 +- .../Files/GetTreeFilesEndpointTests.cs | 12 +- .../Path/CheckPathExistsEndpointTests.cs | 8 +- .../Path/CombinePathEndpointTests.cs | 12 +- .../Path/GetPathParentEndpointTests.cs | 12 +- .../Path/GetPathRootEndpointTests.cs | 12 +- .../Path/SplitPathEndpointTests.cs | 12 +- .../Path/ValidatePathEndpointTests.cs | 9 +- .../Thumbnails/GetThumbnailEndpointTests.cs | 12 +- .../SetupApplicationEndpointTests.cs | 14 +- .../ChangePasswordEndpointTests.cs | 12 +- .../GetUsers/GetUsersEndpointTests.cs | 12 +- .../Login/LoginEndpointTests.cs | 12 +- .../RecoverPasswordEndpointTests.cs | 12 +- .../Register/RegisterEndpointTests.cs | 12 +- .../GetAuthorizationEndpointTests.cs | 12 +- .../GetUserPermissionsEndpointTests.cs | 12 +- .../GetUserRole/GetUserRoleEndpointTests.cs | 12 +- ...dateUserRoleAndPermissionsEndpointTests.cs | 12 +- 436 files changed, 4234 insertions(+), 3922 deletions(-) create mode 100644 src/Lumina.Domain.SharedKernel/Common/Enums/Primitives/ErrorType.cs rename src/{Lumina.Domain.SharedKernel => Lumina.Domain}/Common/Errors/Errors.FileSystemManagement.cs (96%) rename src/{Lumina.Domain.SharedKernel => Lumina.Domain}/Common/Errors/Errors.Library.cs (95%) rename src/{Lumina.Domain.SharedKernel => Lumina.Domain}/Common/Errors/Errors.LibraryScanning.cs (96%) rename src/{Lumina.Domain.SharedKernel => Lumina.Domain}/Common/Errors/Errors.MediaContributor.cs (95%) rename src/{Lumina.Domain.SharedKernel => Lumina.Domain}/Common/Errors/Errors.Metadata.cs (98%) rename src/{Lumina.Domain.SharedKernel => Lumina.Domain}/Common/Errors/Errors.Permission.cs (85%) rename src/{Lumina.Domain.SharedKernel => Lumina.Domain}/Common/Errors/Errors.Plugins.cs (93%) rename src/{Lumina.Domain.SharedKernel => Lumina.Domain}/Common/Errors/Errors.Thumbnails.cs (88%) rename src/{Lumina.Domain.SharedKernel => Lumina.Domain}/Common/Errors/Errors.Users.cs (89%) rename src/{Lumina.Domain.SharedKernel => Lumina.Domain}/Common/Errors/Errors.WrittenContent.cs (97%) rename src/Lumina.Domain/Common/Primitives/{Results.cs => Result.Markers.cs} (56%) create mode 100644 src/Lumina.Domain/Common/Primitives/UnexpectedError.cs diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IPermissionRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IPermissionRepository.cs index c932d2f9..6164ff9e 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IPermissionRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IPermissionRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; @@ -23,6 +23,6 @@ public interface IPermissionRepository : IRepository, /// /// The list of Ids of the permissions to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - Task>> GetByIdsAsync(IEnumerable ids, CancellationToken cancellationToken); + /// An containing either a collection of , or an error. + Task>> GetByIdsAsync(IEnumerable ids, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IRoleRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IRoleRepository.cs index 22198c9c..75f11825 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IRoleRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IRoleRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; @@ -25,6 +25,6 @@ public interface IRoleRepository : IRepository, /// /// The type of role to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a if found, or an error. - Task> GetByNameAsync(string roleType, CancellationToken cancellationToken); + /// An containing either a if found, or an error. + Task> GetByNameAsync(string roleType, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs index f6dba43d..893e7f40 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; @@ -25,8 +25,8 @@ public interface IBookRepository : IRepository, /// /// The Id of the media library whose books are retrieved. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - Task>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + /// An containing either a collection of , or an error. + Task>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); /// /// Gets the book of the media library identified by that is stored at the provided . @@ -34,8 +34,8 @@ public interface IBookRepository : IRepository, /// The Id of the media library whose book is retrieved. /// The file system path of the book to be retrieved. /// Cancellation token that can be used to stop the execution. - /// An containing either the stored at the provided path, or an error. - Task> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken); + /// An containing either the stored at the provided path, or an error. + Task> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken); /// /// Gets a page of the books of the media library identified by whose metadata has not been enriched yet, @@ -45,14 +45,14 @@ public interface IBookRepository : IRepository, /// The path of the last retrieved book, used for keyset pagination. Pass to get the first page. /// The maximum number of books to retrieve. /// Cancellation token that can be used to stop the execution. - /// An containing either a page of books needing their metadata enriched, or an error. - Task>> GetBooksNeedingMetadataAsync(Guid libraryId, string? lastPath, int pageSize, CancellationToken cancellationToken); + /// An containing either a page of books needing their metadata enriched, or an error. + Task>> GetBooksNeedingMetadataAsync(Guid libraryId, string? lastPath, int pageSize, CancellationToken cancellationToken); /// /// Gets the number of books of the media library identified by whose metadata has not been enriched yet. /// /// The Id of the media library whose books are counted. /// Cancellation token that can be used to stop the execution. - /// An containing either the number of books needing their metadata enriched, or an error. - Task> GetBooksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken); + /// An containing either the number of books needing their metadata enriched, or an error. + Task> GetBooksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteAllRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteAllRepositoryAction.cs index d57fe3fa..52efaa54 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteAllRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteAllRepositoryAction.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using System.Threading.Tasks; #endregion @@ -13,6 +13,6 @@ public interface IDeleteAllRepositoryAction /// /// Deletes all entities from the storage medium. /// - /// An representing either a successful operation, or an error. - Task> DeleteAllAsync(); + /// An representing either a successful operation, or an error. + Task> DeleteAllAsync(); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteByIdRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteByIdRepositoryAction.cs index e7303b8c..8a815923 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteByIdRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteByIdRepositoryAction.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using System.Threading; using System.Threading.Tasks; #endregion @@ -17,6 +17,6 @@ public interface IDeleteByIdRepositoryAction where TId : notnull /// /// The id of the element to be deleted. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> DeleteByIdAsync(TId id, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> DeleteByIdAsync(TId id, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs index 954a74a3..58f34768 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Common; using System.Collections.Generic; using System.Threading; @@ -18,6 +18,6 @@ public interface IGetAllRepositoryAction where TModel : IStorageEntity /// Gets all data of type from the storage medium. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - Task>> GetAllAsync(CancellationToken cancellationToken); + /// An containing either a collection of , or an error. + Task>> GetAllAsync(CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs index 03ea871f..69d82b5b 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Common; using System.Threading; using System.Threading.Tasks; @@ -20,6 +20,6 @@ public interface IGetByIdRepositoryAction where TModel : IStorageEn /// /// The id of the element to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a identified by , or an error. - Task> GetByIdAsync(TId id, CancellationToken cancellationToken); + /// An containing either a identified by , or an error. + Task> GetByIdAsync(TId id, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRangeRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRangeRepositoryAction.cs index 9251f07d..4e817e5c 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRangeRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRangeRepositoryAction.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Common; using System.Collections.Generic; using System.Threading; @@ -19,6 +19,6 @@ public interface IInsertRangeRepositoryAction where TModel : IStorageEnt /// /// The elements to be saved. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> InsertRangeAsync(IReadOnlyCollection entities, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> InsertRangeAsync(IReadOnlyCollection entities, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRepositoryAction.cs index cf785503..ce93bcfd 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRepositoryAction.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Common; using System.Threading; using System.Threading.Tasks; @@ -18,6 +18,6 @@ public interface IInsertRepositoryAction where TModel : IStorageEntity /// /// The element to be saved. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> InsertAsync(TModel data, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> InsertAsync(TModel data, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IUpdateRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IUpdateRepositoryAction.cs index e97c4679..a2ebb600 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IUpdateRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IUpdateRepositoryAction.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Common; using System.Threading; using System.Threading.Tasks; @@ -18,6 +18,6 @@ public interface IUpdateRepositoryAction where TModel : IStorageEntity /// /// The element that will be updated. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> UpdateAsync(TModel data, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> UpdateAsync(TModel data, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/IDirectoryScanFingerprintRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/IDirectoryScanFingerprintRepository.cs index c075318d..9bd6a205 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/IDirectoryScanFingerprintRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/IDirectoryScanFingerprintRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; using System; @@ -20,14 +20,14 @@ public interface IDirectoryScanFingerprintRepository : IRepository /// The unique identifier of the library for which to get the directory scan fingerprints. /// Cancellation token that can be used to stop the execution. - /// An containing either a path mapped dictionary of directory scan fingerprints, or an error. - Task>> GetMappedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + /// An containing either a path mapped dictionary of directory scan fingerprints, or an error. + Task>> GetMappedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); /// /// Inserts or updates the provided directory scan fingerprints in the storage medium. /// /// The directory scan fingerprints to insert or update. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> UpsertRangeAsync(IReadOnlyCollection entities, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> UpsertRangeAsync(IReadOnlyCollection entities, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryRepository.cs index 0f5687d6..51b720cb 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; @@ -25,13 +25,13 @@ public interface ILibraryRepository : IRepository, /// Gets all media libraries that are marked as enabled and unlocked, from the storage medium. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - Task>> GetAllEnabledAndUnlockedAsync(CancellationToken cancellationToken); + /// An containing either a collection of , or an error. + Task>> GetAllEnabledAndUnlockedAsync(CancellationToken cancellationToken); /// /// Gets all media libraries that are marked as enabled from the storage medium. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - Task>> GetAllEnabledAsync(CancellationToken cancellationToken); + /// An containing either a collection of , or an error. + Task>> GetAllEnabledAsync(CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs index 54393d7e..4cc72122 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; @@ -24,13 +24,13 @@ public interface ILibraryScanRepository : IRepository, /// Gets the media library scans that belong to a media library identified by , for the previous month, from the storage medium. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - Task>> GetPastMonthScansByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + /// An containing either a collection of , or an error. + Task>> GetPastMonthScansByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); /// /// Gets the media library scans have a status, from the storage medium. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - Task>> GetRunningScansAsync(CancellationToken cancellationToken); + /// An containing either a collection of , or an error. + Task>> GetRunningScansAsync(CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanSnapshotRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanSnapshotRepository.cs index a34e4692..0b053d48 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanSnapshotRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanSnapshotRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; using System; @@ -21,16 +21,16 @@ public interface ILibraryScanSnapshotRepository : IRepositoryThe unique identifier of the library for which to get the deleted media library scan snapshot item paths. /// The unique identifier of the media library scan for which to determine the deleted media library scan snapshot item paths. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of deleted media library scan snapshot item paths, or an error. - Task>> GetDeletedPathsAsync(Guid libraryId, Guid scanId, CancellationToken cancellationToken); + /// An containing either a collection of deleted media library scan snapshot item paths, or an error. + Task>> GetDeletedPathsAsync(Guid libraryId, Guid scanId, CancellationToken cancellationToken); /// /// Gets the paths of all the media library scan snapshot items of the media library identified by . /// /// The unique identifier of the library whose media library scan snapshot item paths are retrieved. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of media library scan snapshot item paths, or an error. - Task>> GetPathsAsync(Guid libraryId, CancellationToken cancellationToken); + /// An containing either a collection of media library scan snapshot item paths, or an error. + Task>> GetPathsAsync(Guid libraryId, CancellationToken cancellationToken); /// /// Atomically applies the results of the current scan to the storage medium, by replacing the media library scan snapshot of the previous scan with the snapshot of the current scan. @@ -41,6 +41,6 @@ public interface ILibraryScanSnapshotRepository : IRepositoryThe unique identifier of the media library scan whose results are applied. /// The unique identifier of the user that initiated the media library scan, used for audit purposes. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> ApplySnapshotSwapAsync(Guid libraryId, Guid scanId, Guid userId, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> ApplySnapshotSwapAsync(Guid libraryId, Guid scanId, Guid userId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanStagingResultsRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanStagingResultsRepository.cs index da52f84a..5e280fb4 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanStagingResultsRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanStagingResultsRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; @@ -25,16 +25,16 @@ public interface ILibraryScanStagingResultsRepository : IRepositoryThe unique identifier of the media library scan whose staging results are marked. /// The unique identifier of the library whose media library scan snapshot is compared against. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> MarkChangesAgainstSnapshotAsync(Guid scanId, Guid libraryId, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> MarkChangesAgainstSnapshotAsync(Guid scanId, Guid libraryId, CancellationToken cancellationToken); /// /// Gets the number of media library scan staging results of the current scan that need their content hashed. /// /// The unique identifier of the media library scan whose staging results are counted. /// Cancellation token that can be used to stop the execution. - /// An containing either the number of staging results that need hashing, or an error. - Task> GetFilesToHashCountAsync(Guid scanId, CancellationToken cancellationToken); + /// An containing either the number of staging results that need hashing, or an error. + Task> GetFilesToHashCountAsync(Guid scanId, CancellationToken cancellationToken); /// /// Gets a page of the media library scan staging results that need their content hashed, ordered by path, using keyset pagination. @@ -43,8 +43,8 @@ public interface ILibraryScanStagingResultsRepository : IRepositoryThe path of the last retrieved file system item, used for keyset pagination. Pass to get the first page. /// The maximum number of staging results to retrieve. /// Cancellation token that can be used to stop the execution. - /// An containing either a page of staging results that need hashing, or an error. - Task>> GetFilesToHashPageAsync(Guid scanId, string? lastPath, int pageSize, CancellationToken cancellationToken); + /// An containing either a page of staging results that need hashing, or an error. + Task>> GetFilesToHashPageAsync(Guid scanId, string? lastPath, int pageSize, CancellationToken cancellationToken); /// /// Updates the content hashes of the provided media library scan staging results. @@ -52,14 +52,14 @@ public interface ILibraryScanStagingResultsRepository : IRepositoryThe unique identifier of the media library scan whose staging results are updated. /// The file system items whose content hashes are updated. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> UpdateFileHashesAsync(Guid scanId, IReadOnlyCollection hashedFiles, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> UpdateFileHashesAsync(Guid scanId, IReadOnlyCollection hashedFiles, CancellationToken cancellationToken); /// /// Clears all the media library scan staging results of the provided media library scan from the storage medium. /// /// The unique identifier of the media library scan whose staging results are cleared. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> ClearForScanAsync(Guid scanId, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> ClearForScanAsync(Guid scanId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/ILibraryMetadataProviderConfigurationRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/ILibraryMetadataProviderConfigurationRepository.cs index 9eeadf0b..36c00468 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/ILibraryMetadataProviderConfigurationRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/ILibraryMetadataProviderConfigurationRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; using System; @@ -20,8 +20,8 @@ public interface ILibraryMetadataProviderConfigurationRepository : IRepository /// The Id of the media library whose metadata provider configurations are retrieved. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - Task>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + /// An containing either a collection of , or an error. + Task>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); /// /// Gets the metadata provider configuration of the media library identified by for the plugin identified by . @@ -29,14 +29,14 @@ public interface ILibraryMetadataProviderConfigurationRepository : IRepositoryThe Id of the media library whose metadata provider configuration is retrieved. /// The Id of the plugin whose metadata provider configuration is retrieved. /// Cancellation token that can be used to stop the execution. - /// An containing either the , or an error. - Task> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken); + /// An containing either the , or an error. + Task> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken); /// /// Inserts the provided into the storage medium, or updates it when it already exists. /// /// The metadata provider configuration to insert or update. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> UpsertAsync(LibraryMetadataProviderConfigurationEntity configuration, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> UpsertAsync(LibraryMetadataProviderConfigurationEntity configuration, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IPluginRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IPluginRepository.cs index 142eb1ac..54ac313e 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IPluginRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IPluginRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; @@ -22,8 +22,8 @@ public interface IPluginRepository : IRepository, /// /// The plugin to insert or update. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> UpsertAsync(PluginEntity plugin, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> UpsertAsync(PluginEntity plugin, CancellationToken cancellationToken); /// /// Updates the settings of the plugin identified by . @@ -31,6 +31,6 @@ public interface IPluginRepository : IRepository, /// The Id of the plugin whose settings are updated. /// The serialized settings of the plugin. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> UpdateSettingsAsync(Guid pluginId, string? settingsJson, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> UpdateSettingsAsync(Guid pluginId, string? settingsJson, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserRepository.cs index 2c5b5cd6..ec0f2b90 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; @@ -24,6 +24,6 @@ public interface IUserRepository : IRepository, /// /// The username of the user to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a if found, or an error. - Task> GetByUsernameAsync(string username, CancellationToken cancellationToken); + /// An containing either a if found, or an error. + Task> GetByUsernameAsync(string username, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs b/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs index f6da07f6..da3303cb 100644 --- a/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs +++ b/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using System; using System.Threading; using System.Threading.Tasks; @@ -17,30 +17,30 @@ public interface IDataSeedService /// /// The unique identifier of the admin admin user who will own these permissions. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken); /// /// Sets up default authorization roles in the system. /// /// The unique identifier of the admin user for whom roles will be set. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken); /// /// Assigns admin role permissions to the admin user. /// /// The unique identifier of the admin user to receive admin role permissions. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken); /// /// Assigns admin role to the admin user. /// /// The unique identifier of the admin user to receive the admin role. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/Errors/Errors.Authentication.cs b/src/Lumina.Application/Common/Errors/Errors.Authentication.cs index a6bec2b7..df71803f 100644 --- a/src/Lumina.Application/Common/Errors/Errors.Authentication.cs +++ b/src/Lumina.Application/Common/Errors/Errors.Authentication.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion namespace Lumina.Application.Common.Errors; diff --git a/src/Lumina.Application/Common/Errors/Errors.Authorization.cs b/src/Lumina.Application/Common/Errors/Errors.Authorization.cs index 6c210728..a216fd92 100644 --- a/src/Lumina.Application/Common/Errors/Errors.Authorization.cs +++ b/src/Lumina.Application/Common/Errors/Errors.Authorization.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion namespace Lumina.Application.Common.Errors; diff --git a/src/Lumina.Application/Common/Errors/Errors.Persistence.cs b/src/Lumina.Application/Common/Errors/Errors.Persistence.cs index b6b21bfb..595dc8e0 100644 --- a/src/Lumina.Application/Common/Errors/Errors.Persistence.cs +++ b/src/Lumina.Application/Common/Errors/Errors.Persistence.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion namespace Lumina.Application.Common.Errors; diff --git a/src/Lumina.Application/Common/Infrastructure/Authorization/IAuthorizationService.cs b/src/Lumina.Application/Common/Infrastructure/Authorization/IAuthorizationService.cs index 05d3c59c..dd982e20 100644 --- a/src/Lumina.Application/Common/Infrastructure/Authorization/IAuthorizationService.cs +++ b/src/Lumina.Application/Common/Infrastructure/Authorization/IAuthorizationService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; @@ -47,6 +47,6 @@ public interface IAuthorizationService /// /// The unique identifier of the user for whom to retrieve the authorization roles and permissions. /// Cancellation token that can be used to stop the execution. - /// An containing either a , or an error. - Task> GetUserAuthorizationAsync(Guid userId, CancellationToken cancellationToken); + /// An containing either a , or an error. + Task> GetUserAuthorizationAsync(Guid userId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/AbstractValidator.cs b/src/Lumina.Application/Common/Infrastructure/Validation/AbstractValidator.cs index cb40c867..642f7eaf 100644 --- a/src/Lumina.Application/Common/Infrastructure/Validation/AbstractValidator.cs +++ b/src/Lumina.Application/Common/Infrastructure/Validation/AbstractValidator.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; #endregion diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs b/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs index 771dcf73..b5ee1e97 100644 --- a/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs +++ b/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using System; #endregion diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/IValidationRule.cs b/src/Lumina.Application/Common/Infrastructure/Validation/IValidationRule.cs index a914dfd2..b7527cd6 100644 --- a/src/Lumina.Application/Common/Infrastructure/Validation/IValidationRule.cs +++ b/src/Lumina.Application/Common/Infrastructure/Validation/IValidationRule.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; #endregion diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/IValidator.cs b/src/Lumina.Application/Common/Infrastructure/Validation/IValidator.cs index 59467cb7..705e32ed 100644 --- a/src/Lumina.Application/Common/Infrastructure/Validation/IValidator.cs +++ b/src/Lumina.Application/Common/Infrastructure/Validation/IValidator.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; #endregion diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs index fc07a557..ca484383 100644 --- a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs +++ b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; #endregion diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs index 4a5e08cc..75130e83 100644 --- a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs +++ b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; #endregion diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs index a9394093..fc64e18b 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Contracts.DTO.Common; using Lumina.Domain.Common.ValueObjects.Metadata; using System.Collections.Generic; @@ -18,9 +18,9 @@ public static class GenreDtoMapping /// /// The DTO to be converted. /// - /// An containing either a successfully converted , or an error message. + /// An containing either a successfully converted , or an error message. /// - public static ErrorOr ToDomainEntity(this GenreDto dto) + public static Result ToDomainEntity(this GenreDto dto) { return Genre.Create( dto.Name @@ -32,9 +32,9 @@ public static class GenreDtoMapping /// /// The DTOs to be converted. /// - /// An containing either a collection of converted , or an error message. + /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + public static IEnumerable> ToDomainEntities(this IEnumerable dtos) { return dtos.Select(repositoryEntity => repositoryEntity.ToDomainEntity()); } diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs index c9da761c..18106d78 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Contracts.DTO.Common; using Lumina.Domain.Common.ValueObjects.Metadata; @@ -41,9 +41,9 @@ public static class GenreEntityMapping /// /// The repository entity to be converted. /// - /// An containing either a successfully converted , or an error message. + /// An containing either a successfully converted , or an error message. /// - public static ErrorOr ToDomainEntity(this GenreEntity repositoryEntity) + public static Result ToDomainEntity(this GenreEntity repositoryEntity) { return Genre.Create( repositoryEntity.Name ?? default @@ -55,9 +55,9 @@ public static class GenreEntityMapping /// /// The repository entities to be converted. /// - /// An containing either a collection of converted , or an error message. + /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) { return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); } diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs index 02cf7d19..9c987743 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Contracts.DTO.Common; using Lumina.Domain.Common.ValueObjects.Metadata; using System.Collections.Generic; @@ -18,9 +18,9 @@ public static class TagDtoMapping /// /// The DTO to be converted. /// - /// An containing either a successfully converted , or an error message. + /// An containing either a successfully converted , or an error message. /// - public static ErrorOr ToDomainEntity(this TagDto dto) + public static Result ToDomainEntity(this TagDto dto) { return Tag.Create( dto.Name @@ -32,9 +32,9 @@ public static class TagDtoMapping /// /// The DTOs to be converted. /// - /// An containing either a collection of converted , or an error message. + /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + public static IEnumerable> ToDomainEntities(this IEnumerable dtos) { return dtos.Select(domainEntity => domainEntity.ToDomainEntity()); } diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs index 6f56f106..45ef4409 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Contracts.DTO.Common; using Lumina.Domain.Common.ValueObjects.Metadata; @@ -41,9 +41,9 @@ public static class TagEntityMapping /// /// The repository entity to be converted. /// - /// An containing either a successfully converted , or an error message. + /// An containing either a successfully converted , or an error message. /// - public static ErrorOr ToDomainEntity(this TagEntity repositoryEntity) + public static Result ToDomainEntity(this TagEntity repositoryEntity) { return Tag.Create( repositoryEntity.Name ?? default @@ -55,9 +55,9 @@ public static class TagEntityMapping /// /// The repository entities to be converted. /// - /// An containing either a collection of converted , or an error message. + /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) { return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); } diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMapping.cs index 211dba64..eaf0d574 100644 --- a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMapping.cs +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMapping.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; @@ -17,7 +17,7 @@ public static class FileSystemTreeNodeResponseMapping /// /// The response to be converted. /// The converted domain entity. - public static ErrorOr ToWindowsRootItem(this FileSystemTreeNodeResponse response) + public static Result ToWindowsRootItem(this FileSystemTreeNodeResponse response) { return WindowsRootItem.Create( response.Path, @@ -31,7 +31,7 @@ public static class FileSystemTreeNodeResponseMapping /// /// The response to be converted. /// The converted domain entity. - public static ErrorOr ToUnixRootItem(this FileSystemTreeNodeResponse _) + public static Result ToUnixRootItem(this FileSystemTreeNodeResponse _) { return UnixRootItem.Create( FileSystemItemStatus.Accessible diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs index 08598ec3..1484cf34 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; @@ -46,9 +46,9 @@ public static class LibraryEntityMapping /// /// The repository entity to be converted. /// - /// An containing either a successfully converted , or an error message. + /// An containing either a successfully converted , or an error message. /// - public static ErrorOr ToDomainEntity(this LibraryEntity repositoryEntity) + public static Result ToDomainEntity(this LibraryEntity repositoryEntity) { return Library.Create( LibraryId.Create(repositoryEntity.Id), @@ -71,9 +71,9 @@ public static class LibraryEntityMapping /// /// The repository entities to be converted. /// - /// An containing either a collection of converted , or an error message. + /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) { return repositoryEntities.Select(library => library.ToDomainEntity()); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanEntityMapping.cs index d6a0a78f..6b2abb72 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanEntityMapping.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; @@ -23,9 +23,9 @@ public static class LibraryScanEntityMapping /// /// The repository entity to be converted. /// - /// An containing either a converted , or an error message. + /// An containing either a converted , or an error message. /// - public static ErrorOr ToDomainEntity(this LibraryScanEntity repositoryEntity) + public static Result ToDomainEntity(this LibraryScanEntity repositoryEntity) { return LibraryScan.Create( ScanId.Create(repositoryEntity.Id), @@ -41,9 +41,9 @@ public static class LibraryScanEntityMapping /// /// The repository entities to be converted. /// - /// An containing either a collection of converted , or an error message. + /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) { return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs index 6d6f0e0c..1561d2cb 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -8,7 +8,7 @@ using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.Common.Primitives; + using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; @@ -31,31 +31,31 @@ public static class BookEntityMapping /// /// The repository entity to be converted. /// - /// An containing either a successfully converted , or an error message. + /// An containing either a successfully converted , or an error message. /// - public static ErrorOr ToDomainEntity(this BookEntity repositoryEntity) + public static Result ToDomainEntity(this BookEntity repositoryEntity) { - IEnumerable> tagsResult = repositoryEntity.Tags.ToDomainEntities(); - foreach (ErrorOr tagResult in tagsResult) - if (tagResult.IsError) + IEnumerable> tagsResult = repositoryEntity.Tags.ToDomainEntities(); + foreach (Result tagResult in tagsResult) + if (tagResult.IsFailure) return tagResult.Errors; - IEnumerable> genresResult = repositoryEntity.Genres.ToDomainEntities(); - foreach (ErrorOr genreResult in genresResult) - if (genreResult.IsError) + IEnumerable> genresResult = repositoryEntity.Genres.ToDomainEntities(); + foreach (Result genreResult in genresResult) + if (genreResult.IsFailure) return genreResult.Errors; - IEnumerable> isbnsResult = repositoryEntity.ISBNs.ToDomainEntities(); - foreach (ErrorOr isbnResult in isbnsResult) - if (isbnResult.IsError) + IEnumerable> isbnsResult = repositoryEntity.ISBNs.ToDomainEntities(); + foreach (Result isbnResult in isbnsResult) + if (isbnResult.IsFailure) return isbnResult.Errors; - IEnumerable> bookRatingsResult = repositoryEntity.Ratings.ToDomainEntities(); - foreach (ErrorOr bookRatingResult in bookRatingsResult) - if (bookRatingResult.IsError) + IEnumerable> bookRatingsResult = repositoryEntity.Ratings.ToDomainEntities(); + foreach (Result bookRatingResult in bookRatingsResult) + if (bookRatingResult.IsFailure) return bookRatingResult.Errors; - ErrorOr releaseInfoResult = ReleaseInfo.Create( + Result releaseInfoResult = ReleaseInfo.Create( Optional.FromNullable(repositoryEntity.OriginalReleaseDate), Optional.FromNullable(repositoryEntity.OriginalReleaseYear), Optional.FromNullable(repositoryEntity.ReReleaseDate), @@ -63,18 +63,18 @@ public static class BookEntityMapping Optional.FromNullable(repositoryEntity.ReleaseCountry), Optional.FromNullable(repositoryEntity.ReleaseVersion) ); - if (releaseInfoResult.IsError) + if (releaseInfoResult.IsFailure) return releaseInfoResult.Errors; Optional languageInfo = Optional.None(); if (repositoryEntity.LanguageCode is not null) { - ErrorOr languageInfoResult = LanguageInfo.Create( + Result languageInfoResult = LanguageInfo.Create( repositoryEntity.LanguageCode, repositoryEntity.LanguageName, Optional.FromNullable(repositoryEntity.LanguageNativeName) ); - if (languageInfoResult.IsError) + if (languageInfoResult.IsFailure) return languageInfoResult.Errors; languageInfo = languageInfoResult.Value; } @@ -82,29 +82,29 @@ public static class BookEntityMapping Optional originalLanguageCode = Optional.None(); if (repositoryEntity.OriginalLanguageCode is not null) { - ErrorOr originalLanguageInfoResult = LanguageInfo.Create( + Result originalLanguageInfoResult = LanguageInfo.Create( repositoryEntity.OriginalLanguageCode, repositoryEntity.OriginalLanguageName!, Optional.FromNullable(repositoryEntity.OriginalLanguageNativeName) ); - if (originalLanguageInfoResult.IsError) + if (originalLanguageInfoResult.IsFailure) return originalLanguageInfoResult.Errors; originalLanguageCode = originalLanguageInfoResult.Value; } - ErrorOr writtenContentMetadataResult = WrittenContentMetadata.Create( + Result writtenContentMetadataResult = WrittenContentMetadata.Create( repositoryEntity.Title, Optional.FromNullable(repositoryEntity.OriginalTitle), Optional.FromNullable(repositoryEntity.Description), releaseInfoResult.Value, - genresResult.Select(genre => genre.Value).ToList(), - tagsResult.Select(tag => tag.Value).ToList(), + [.. genresResult.Select(genre => genre.Value)], + [.. tagsResult.Select(tag => tag.Value)], languageInfo, originalLanguageCode, Optional.FromNullable(repositoryEntity.Publisher), Optional.FromNullable(repositoryEntity.PageCount) ); - if (writtenContentMetadataResult.IsError) + if (writtenContentMetadataResult.IsFailure) return writtenContentMetadataResult.Errors; Optional bookFormat = Optional.FromNullable(repositoryEntity.Format); @@ -129,9 +129,9 @@ public static class BookEntityMapping Optional.FromNullable(repositoryEntity.AppleBooksId), repositoryEntity.CreatedOnUtc, Optional.FromNullable(repositoryEntity.UpdatedOnUtc), - isbnsResult.Select(isbn => isbn.Value).ToList(), + [.. isbnsResult.Select(isbn => isbn.Value)], [], - bookRatingsResult.Select(bookRating => bookRating.Value).ToList()); + [.. bookRatingsResult.Select(bookRating => bookRating.Value)]); } /// @@ -140,9 +140,9 @@ public static class BookEntityMapping /// The repository entities to be converted. /// The converted domain entities. /// - /// An colection of containing either a collection of converted , or error messages. + /// An colection of containing either a collection of converted , or error messages. /// - public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) { return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainEntity()); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs index 0e8fa631..e295cd5b 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Primitives; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; + using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; @@ -26,15 +26,15 @@ public static class BookMetadataDtoMapping /// The metadata to be applied. /// The name of the metadata provider that enriched the book. /// The date and time when the metadata was enriched. - /// An representing either a successful operation, or an error. - public static ErrorOr ApplyMetadata(this Book book, BookMetadataDto metadata, string providerName, DateTime lastUpdateUtc) + /// An representing either a successful operation, or an error. + public static Result ApplyMetadata(this Book book, BookMetadataDto metadata, string providerName, DateTime lastUpdateUtc) { if (string.IsNullOrWhiteSpace(metadata.Title)) - return Domain.SharedKernel.Common.Errors.Errors.Metadata.TitleCannotBeEmpty; + return Lumina.Domain.Common.Errors.Errors.Metadata.TitleCannotBeEmpty; if (metadata.ReleaseInfo is null) - return Domain.SharedKernel.Common.Errors.Errors.Metadata.ReleaseInfoCannotBeNull; + return Lumina.Domain.Common.Errors.Errors.Metadata.ReleaseInfoCannotBeNull; - ErrorOr releaseInfoResult = ReleaseInfo.Create( + Result releaseInfoResult = ReleaseInfo.Create( Optional.FromNullable(metadata.ReleaseInfo.OriginalReleaseDate), Optional.FromNullable(metadata.ReleaseInfo.OriginalReleaseYear), Optional.FromNullable(metadata.ReleaseInfo.ReReleaseDate), @@ -42,28 +42,28 @@ public static class BookMetadataDtoMapping Optional.FromNullable(metadata.ReleaseInfo.ReleaseCountry), Optional.FromNullable(metadata.ReleaseInfo.ReleaseVersion) ); - if (releaseInfoResult.IsError) + if (releaseInfoResult.IsFailure) return releaseInfoResult.Errors; - List> domainGenresResult = metadata.Genres is not null + List> domainGenresResult = metadata.Genres is not null ? [.. metadata.Genres.Select(genre => Genre.Create(genre.Name))] : []; - List genresErrors = [.. domainGenresResult.Where(genreResult => genreResult.IsError).SelectMany(genreResult => genreResult.Errors)]; + List genresErrors = [.. domainGenresResult.Where(genreResult => genreResult.IsFailure).SelectMany(genreResult => genreResult.Errors)]; if (genresErrors.Count != 0) return genresErrors; - List> domainTagsResult = metadata.Tags is not null + List> domainTagsResult = metadata.Tags is not null ? [.. metadata.Tags.Select(tag => Tag.Create(tag.Name))] : []; - List tagsErrors = [.. domainTagsResult.Where(tagResult => tagResult.IsError).SelectMany(tagResult => tagResult.Errors)]; + List tagsErrors = [.. domainTagsResult.Where(tagResult => tagResult.IsFailure).SelectMany(tagResult => tagResult.Errors)]; if (tagsErrors.Count != 0) return tagsErrors; Optional languageInfo = Optional.None(); if (metadata.Language is not null) { - ErrorOr languageInfoResult = LanguageInfo.Create(metadata.Language.LanguageCode, metadata.Language.LanguageName, Optional.FromNullable(metadata.Language.NativeName)); - if (languageInfoResult.IsError) + Result languageInfoResult = LanguageInfo.Create(metadata.Language.LanguageCode, metadata.Language.LanguageName, Optional.FromNullable(metadata.Language.NativeName)); + if (languageInfoResult.IsFailure) return languageInfoResult.Errors; languageInfo = languageInfoResult.Value; } @@ -71,13 +71,13 @@ public static class BookMetadataDtoMapping Optional originalLanguageInfo = Optional.None(); if (metadata.OriginalLanguage is not null) { - ErrorOr originalLanguageInfoResult = LanguageInfo.Create(metadata.OriginalLanguage.LanguageCode, metadata.OriginalLanguage.LanguageName, Optional.FromNullable(metadata.OriginalLanguage.NativeName)); - if (originalLanguageInfoResult.IsError) + Result originalLanguageInfoResult = LanguageInfo.Create(metadata.OriginalLanguage.LanguageCode, metadata.OriginalLanguage.LanguageName, Optional.FromNullable(metadata.OriginalLanguage.NativeName)); + if (originalLanguageInfoResult.IsFailure) return originalLanguageInfoResult.Errors; originalLanguageInfo = originalLanguageInfoResult.Value; } - ErrorOr writtenContentMetadataResult = WrittenContentMetadata.Create( + Result writtenContentMetadataResult = WrittenContentMetadata.Create( metadata.Title, Optional.FromNullable(metadata.OriginalTitle), Optional.FromNullable(metadata.Description), @@ -89,17 +89,17 @@ public static class BookMetadataDtoMapping Optional.FromNullable(metadata.Publisher), Optional.FromNullable(metadata.PageCount) ); - if (writtenContentMetadataResult.IsError) + if (writtenContentMetadataResult.IsFailure) return writtenContentMetadataResult.Errors; - List> domainIsbnsResult = metadata.Isbns is not null + List> domainIsbnsResult = metadata.Isbns is not null ? [.. metadata.Isbns.Where(isbn => isbn.Value is not null && isbn.Format is not null).Select(isbn => Isbn.Create(isbn.Value, (IsbnFormat)(int)isbn.Format!.Value))] : []; - List isbnsErrors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsError).SelectMany(isbnResult => isbnResult.Errors)]; + List isbnsErrors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors)]; if (isbnsErrors.Count != 0) return isbnsErrors; - List> domainRatingsResult = metadata.Ratings is not null + List> domainRatingsResult = metadata.Ratings is not null ? [.. metadata.Ratings.Where(rating => rating.Value is not null && rating.MaxValue is not null).Select(rating => BookRating.Create( rating.Value!.Value, rating.MaxValue!.Value, @@ -107,7 +107,7 @@ public static class BookMetadataDtoMapping Optional.FromNullable(rating.VoteCount) ))] : []; - List ratingsErrors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsError).SelectMany(ratingResult => ratingResult.Errors)]; + List ratingsErrors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; if (ratingsErrors.Count != 0) return ratingsErrors; diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMapping.cs index 84ab6502..9f9c6e3c 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMapping.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.Common.Primitives; + using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using System.Collections.Generic; using System.Linq; @@ -20,9 +20,9 @@ public static class BookRatingDtoMapping /// /// The DTO to be converted. /// - /// An containing either a successfully converted , or an error message. + /// An containing either a successfully converted , or an error message. /// - public static ErrorOr ToDomainEntity(this BookRatingDto dto) + public static Result ToDomainEntity(this BookRatingDto dto) { return BookRating.Create( dto.Value ?? default, @@ -37,9 +37,9 @@ public static class BookRatingDtoMapping /// /// The DTOs to be converted. /// - /// An containing either a collection of converted , or an error message. + /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + public static IEnumerable> ToDomainEntities(this IEnumerable dtos) { return dtos.Select(domainEntity => domainEntity.ToDomainEntity()); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMapping.cs index d5ffcfbb..f8406648 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMapping.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.Common.Primitives; + using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using System.Collections.Generic; using System.Linq; @@ -46,9 +46,9 @@ public static class BookRatingEntityMapping /// /// The repository entity to be converted. /// - /// An containing either a successfully converted , or an error message. + /// An containing either a successfully converted , or an error message. /// - public static ErrorOr ToDomainEntity(this BookRatingEntity repositoryEntity) + public static Result ToDomainEntity(this BookRatingEntity repositoryEntity) { return BookRating.Create( repositoryEntity.Value ?? default, @@ -63,9 +63,9 @@ public static class BookRatingEntityMapping /// /// The repository entities to be converted. /// - /// An containing either a collection of converted , or an error message. + /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) { return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMapping.cs index 61ace5df..228e0d3d 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMapping.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; @@ -19,9 +19,9 @@ public static class IsbnDtoMapping /// /// The DTO to be converted. /// - /// An containing either a successfully converted , or an error message. + /// An containing either a successfully converted , or an error message. /// - public static ErrorOr ToDomainEntity(this IsbnDto dto) + public static Result ToDomainEntity(this IsbnDto dto) { return Isbn.Create( dto.Value, @@ -34,9 +34,9 @@ public static class IsbnDtoMapping /// /// The DTOs to be converted. /// - /// An containing either a collection of converted , or an error message. + /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + public static IEnumerable> ToDomainEntities(this IEnumerable dtos) { return dtos.Select(domainEntity => domainEntity.ToDomainEntity()); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMapping.cs index 8f4b202a..d5e1645b 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMapping.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; @@ -42,9 +42,9 @@ public static class IsbnEntityMapping /// /// The repository entity to be converted. /// - /// An containing either a successfully converted , or an error message. + /// An containing either a successfully converted , or an error message. /// - public static ErrorOr ToDomainEntity(this IsbnEntity repositoryEntity) + public static Result ToDomainEntity(this IsbnEntity repositoryEntity) { return Isbn.Create( repositoryEntity.Value ?? default, @@ -57,9 +57,9 @@ public static class IsbnEntityMapping /// /// The repository entities to be converted. /// - /// An containing either a collection of converted , or an error message. + /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) { return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); } diff --git a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs index c95dddb8..da4ef78e 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; @@ -19,7 +19,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPer /// /// Handler for the query to retrieve the list of authorization permissions. /// -public class GetPermissionsQueryHandler : IQueryHandler>> +public class GetPermissionsQueryHandler : IQueryHandler>> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; @@ -44,15 +44,15 @@ public class GetPermissionsQueryHandler : IQueryHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a collection of , or an error message. + /// An containing either a collection of , or an error message. /// - public async Task>> HandleAsync(GetPermissionsQuery query, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetPermissionsQuery query, CancellationToken cancellationToken) { // only admins can see the list of authorization permissions bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; - ErrorOr> getPermissionsResult = await _permissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); - return getPermissionsResult.Match(value => ErrorOrFactory.From(value.ToResponses()), errors => errors); + Result> getPermissionsResult = await _permissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + return getPermissionsResult.Match(value => Result.From(value.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs index ecc324ac..f86006d8 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; @@ -21,7 +21,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; /// /// Handler for the command to add an authorization role. /// -public class AddRoleCommandHandler : ICommandHandler> +public class AddRoleCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IAuthorizationService _authorizationService; @@ -49,9 +49,9 @@ public class AddRoleCommandHandler : ICommandHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public async Task> HandleAsync(AddRoleCommand request, CancellationToken cancellationToken) + public async Task> HandleAsync(AddRoleCommand request, CancellationToken cancellationToken) { List validationResult = _validator.Validate(request); if (validationResult.Count > 0) @@ -77,13 +77,13 @@ public class AddRoleCommandHandler : ICommandHandler insertRoleResult = await roleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false); - if (insertRoleResult.IsError) + Result insertRoleResult = await roleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false); + if (insertRoleResult.IsFailure) return insertRoleResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // retrieve the newly saved authorization role from the persistence medium and return it - ErrorOr getRoleResult = await roleRepository.GetByNameAsync(request.RoleName, cancellationToken).ConfigureAwait(false); - if (getRoleResult.IsError) + Result getRoleResult = await roleRepository.GetByNameAsync(request.RoleName, cancellationToken).ConfigureAwait(false); + if (getRoleResult.IsFailure) return getRoleResult.Errors; if (getRoleResult.Value is null) return Errors.Persistence.ErrorPersistingAuthorizationRole; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs index a4de4b25..fb4ed8fe 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; @@ -22,7 +22,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; /// /// Handler for the command to delete an authorization role. /// -public class DeleteRoleCommandHandler : ICommandHandler> +public class DeleteRoleCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IAuthorizationService _authorizationService; @@ -49,8 +49,8 @@ public class DeleteRoleCommandHandler : ICommandHandler /// The request to be handled. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> HandleAsync(DeleteRoleCommand command, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> HandleAsync(DeleteRoleCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) @@ -63,16 +63,16 @@ public class DeleteRoleCommandHandler : ICommandHandler(); - ErrorOr getExistingRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); - if (getExistingRoleResult.IsError) + Result getExistingRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); + if (getExistingRoleResult.IsFailure) return getExistingRoleResult.Errors; else if (getExistingRoleResult.Value is null) return Errors.Authorization.RoleNotFound; else if (getExistingRoleResult.Value.RoleName == "Admin") return Errors.Authorization.AdminRoleCannotBeDeleted; // delete the role and its permissions - ErrorOr deleteRoleResult = await roleRepository.DeleteByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); - if (deleteRoleResult.IsError) + Result deleteRoleResult = await roleRepository.DeleteByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); + if (deleteRoleResult.IsFailure) return deleteRoleResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return deleteRoleResult.Value; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs index 5534b42b..3dcb67c2 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; @@ -21,7 +21,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; /// /// Handler for the command to update an authorization role. /// -public class UpdateRoleCommandHandler : ICommandHandler> +public class UpdateRoleCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IAuthorizationService _authorizationService; @@ -49,9 +49,9 @@ public class UpdateRoleCommandHandler : ICommandHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully updated , or an error message. + /// An containing either a successfully updated , or an error message. /// - public async Task> HandleAsync(UpdateRoleCommand command, CancellationToken cancellationToken) + public async Task> HandleAsync(UpdateRoleCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) @@ -78,13 +78,13 @@ public class UpdateRoleCommandHandler : ICommandHandler updateRoleResult = await roleRepository.UpdateAsync(newRole, cancellationToken).ConfigureAwait(false); - if (updateRoleResult.IsError) + Result updateRoleResult = await roleRepository.UpdateAsync(newRole, cancellationToken).ConfigureAwait(false); + if (updateRoleResult.IsFailure) return updateRoleResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // retrieve the updated authorization role from the persistence medium and return it - ErrorOr getRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); - if (getRoleResult.IsError) + Result getRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); + if (getRoleResult.IsFailure) return getRoleResult.Errors; if (getRoleResult.Value is null) return Errors.Persistence.ErrorPersistingAuthorizationRole; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs index c1735073..b3455ca1 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; @@ -20,7 +20,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermi /// /// Handler for the query to retrieve the list of authorization permissions for a role. /// -public class GetRolePermissionsQueryHandler : IQueryHandler> +public class GetRolePermissionsQueryHandler : IQueryHandler> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; @@ -48,9 +48,9 @@ public class GetRolePermissionsQueryHandler : IQueryHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a collection of , or an error message. + /// An containing either a collection of , or an error message. /// - public async Task> HandleAsync(GetRolePermissionsQuery request, CancellationToken cancellationToken) + public async Task> HandleAsync(GetRolePermissionsQuery request, CancellationToken cancellationToken) { List validationResult = _validator.Validate(request); if (validationResult.Count > 0) @@ -61,8 +61,8 @@ public class GetRolePermissionsQueryHandler : IQueryHandler getRoleResult = await _roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false); - if (getRoleResult.IsError) + Result getRoleResult = await _roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false); + if (getRoleResult.IsFailure) return getRoleResult.Errors; else if (getRoleResult.Value is null) return Errors.Authorization.RoleNotFound; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs index db716a4b..909a68f1 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; @@ -19,7 +19,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; /// /// Handler for the query to retrieve the list of authorization roles. /// -public class GetRolesQueryHandler : IQueryHandler>> +public class GetRolesQueryHandler : IQueryHandler>> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; @@ -44,15 +44,15 @@ public class GetRolesQueryHandler : IQueryHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a collection of , or an error message. + /// An containing either a collection of , or an error message. /// - public async Task>> HandleAsync(GetRolesQuery query, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetRolesQuery query, CancellationToken cancellationToken) { // only admins can see the list of authorization roles bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; - ErrorOr> getRolesResult = await _roleRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); - return getRolesResult.Match(value => ErrorOrFactory.From(value.ToResponses()), errors => errors); + Result> getRolesResult = await _roleRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + return getRolesResult.Match(value => Result.From(value.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs index 141362f8..50461153 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; using Lumina.Application.Common.Infrastructure.Validation; @@ -16,7 +16,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDi /// /// Handler for the query to get all directories. /// -public class GetDirectoriesQueryHandler : IQueryHandler>> +public class GetDirectoriesQueryHandler : IQueryHandler>> { private readonly IDirectoryService _directoryService; private readonly IValidator _validator; @@ -38,15 +38,15 @@ public class GetDirectoriesQueryHandler : IQueryHandlerThe query containing the requested path. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a collection of , or an error message. + /// An containing either a collection of , or an error message. /// - public Task>> HandleAsync(GetDirectoriesQuery query, CancellationToken cancellationToken) + public Task>> HandleAsync(GetDirectoriesQuery query, CancellationToken cancellationToken) { List validationResult = _validator.Validate(query); if (validationResult.Count > 0) - return Task.FromResult>>(validationResult); + return Task.FromResult>>(validationResult); - ErrorOr> getSubdirectoriesResult = _directoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements); - return Task.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); + Result> getSubdirectoriesResult = _directoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements); + return Task.FromResult(getSubdirectoriesResult.Match(values => Result.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs index 601823c9..c58c1d87 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; #endregion namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs index c509b39c..5511a4be 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.Common; @@ -15,7 +15,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; /// /// Handler for the query to get all drives. /// -public class GetDrivesQueryHandler : IQueryHandler>> +public class GetDrivesQueryHandler : IQueryHandler>> { private readonly IDriveService _driveService; @@ -34,11 +34,11 @@ public class GetDrivesQueryHandler : IQueryHandlerThe query containing the requested path. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a collection of , or an error message. + /// An containing either a collection of , or an error message. /// - public Task>> HandleAsync(GetDrivesQuery query, CancellationToken cancellationToken) + public Task>> HandleAsync(GetDrivesQuery query, CancellationToken cancellationToken) { - ErrorOr> getDrivesResult = _driveService.GetDrives(); - return Task.FromResult(getDrivesResult.Match(values => ErrorOrFactory.From(values.ToTreeNodeResponses()), errors => errors)); + Result> getDrivesResult = _driveService.GetDrives(); + return Task.FromResult(getDrivesResult.Match(values => Result.From(values.ToTreeNodeResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs index 45d78a98..5718613e 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Files; using Lumina.Application.Common.Infrastructure.Validation; @@ -16,7 +16,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; /// /// Handler for the query to get all files. /// -public class GetFilesQueryHandler : IQueryHandler>> +public class GetFilesQueryHandler : IQueryHandler>> { private readonly IFileService _fileService; private readonly IValidator _validator; @@ -38,15 +38,15 @@ public class GetFilesQueryHandler : IQueryHandlerThe query containing the requested path. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a collection of , or an error message. + /// An containing either a collection of , or an error message. /// - public Task>> HandleAsync(GetFilesQuery query, CancellationToken cancellationToken) + public Task>> HandleAsync(GetFilesQuery query, CancellationToken cancellationToken) { List validationResult = _validator.Validate(query); if (validationResult.Count > 0) - return Task.FromResult>>(validationResult); + return Task.FromResult>>(validationResult); - ErrorOr> getFilesResult = _fileService.GetFiles(query.Path!, query.IncludeHiddenElements); - return Task.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); + Result> getFilesResult = _fileService.GetFiles(query.Path!, query.IncludeHiddenElements); + return Task.FromResult(getFilesResult.Match(values => Result.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidator.cs index 3315dd6f..3854ae91 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; #endregion namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs index 68651cd0..586660e2 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Files; using Lumina.Application.Common.Infrastructure.Validation; @@ -16,7 +16,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFile /// /// Handler for the query to get all files. /// -public class GetTreeFilesQueryHandler : IQueryHandler>> +public class GetTreeFilesQueryHandler : IQueryHandler>> { private readonly IFileService _fileService; private readonly IValidator _validator; @@ -38,15 +38,15 @@ public class GetTreeFilesQueryHandler : IQueryHandlerThe query containing the requested path. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a collection of , or an error message. + /// An containing either a collection of , or an error message. /// - public Task>> HandleAsync(GetTreeFilesQuery query, CancellationToken cancellationToken) + public Task>> HandleAsync(GetTreeFilesQuery query, CancellationToken cancellationToken) { List validationResult = _validator.Validate(query); if (validationResult.Count > 0) - return Task.FromResult>>(validationResult); + return Task.FromResult>>(validationResult); - ErrorOr> getFilesResult = _fileService.GetFiles(query.Path!, query.IncludeHiddenElements); - return Task.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors)); + Result> getFilesResult = _fileService.GetFiles(query.Path!, query.IncludeHiddenElements); + return Task.FromResult(getFilesResult.Match(values => Result.From(values.ToFileSystemTreeNodeResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidator.cs index 30c51e7f..07212e1e 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; #endregion namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs index b6d6e233..6c35c37b 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; @@ -15,7 +15,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePat /// /// Handler for the command to split a file system path. /// -public class CombinePathCommandHandler : ICommandHandler> +public class CombinePathCommandHandler : ICommandHandler> { private readonly IPathService _pathService; private readonly IValidator _validator; @@ -37,15 +37,15 @@ public class CombinePathCommandHandler : ICommandHandlerThe command containing the requested paths. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a , or an error message. + /// An containing either a , or an error message. /// - public Task> HandleAsync(CombinePathCommand command, CancellationToken cancellationToken) + public Task> HandleAsync(CombinePathCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) - return Task.FromResult>(validationResult); + return Task.FromResult>(validationResult); - ErrorOr combinePathResult = _pathService.CombinePath(command.OriginalPath!, command.NewPath!); - return Task.FromResult(combinePathResult.Match(values => ErrorOrFactory.From(new PathSegmentResponse(combinePathResult.Value)), errors => errors)); + Result combinePathResult = _pathService.CombinePath(command.OriginalPath!, command.NewPath!); + return Task.FromResult(combinePathResult.Match(values => Result.From(new PathSegmentResponse(combinePathResult.Value)), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandValidator.cs index bfc496d9..5fb0015d 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; #endregion namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs index 28332339..e667c119 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; @@ -16,7 +16,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; /// /// Handler for the command to split a file system path. /// -public class SplitPathCommandHandler : ICommandHandler>> +public class SplitPathCommandHandler : ICommandHandler>> { private readonly IPathService _pathService; private readonly IValidator _validator; @@ -38,15 +38,15 @@ public class SplitPathCommandHandler : ICommandHandlerThe command containing the requested path. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a collection of , or an error message. + /// An containing either a collection of , or an error message. /// - public Task>> HandleAsync(SplitPathCommand command, CancellationToken cancellationToken) + public Task>> HandleAsync(SplitPathCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) - return Task.FromResult>>(validationResult); + return Task.FromResult>>(validationResult); - ErrorOr> parsePathResult = _pathService.ParsePath(command.Path!); - return Task.FromResult(parsePathResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); + Result> parsePathResult = _pathService.ParsePath(command.Path!); + return Task.FromResult(parsePathResult.Match(values => Result.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandValidator.cs index 001852f1..066eaf65 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; #endregion namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs index 228cb273..8e90b042 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.FileSystemManagement.Path; @@ -14,7 +14,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathEx /// /// Handler for the query to check the existence a file system path. /// -public class CheckPathExistsQueryHandler : IQueryHandler> +public class CheckPathExistsQueryHandler : IQueryHandler> { private readonly IPathService _pathService; private readonly IValidator _validator; @@ -36,14 +36,14 @@ public class CheckPathExistsQueryHandler : IQueryHandlerThe query containing the request. /// Cancellation token that can be used to stop the execution. /// - /// An containing either if the specified path exists, if it doesn't, or an error message. + /// An containing either if the specified path exists, if it doesn't, or an error message. /// - public Task> HandleAsync(CheckPathExistsQuery query, CancellationToken cancellationToken) + public Task> HandleAsync(CheckPathExistsQuery query, CancellationToken cancellationToken) { List validationResult = _validator.Validate(query); if (validationResult.Count > 0) - return Task.FromResult>(validationResult); + return Task.FromResult>(validationResult); - return Task.FromResult(ErrorOrFactory.From(new PathExistsResponse(_pathService.Exists(query.Path!, query.IncludeHiddenElements)))); + return Task.FromResult(Result.From(new PathExistsResponse(_pathService.Exists(query.Path!, query.IncludeHiddenElements)))); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidator.cs index f943d41b..7fe7e80e 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; #endregion namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs index 46c0216d..5f82dd62 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; @@ -16,7 +16,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathPare /// /// Handler for the query to get the parent of a file system path. /// -public class GetPathParentQueryHandler : IQueryHandler>> +public class GetPathParentQueryHandler : IQueryHandler>> { private readonly IPathService _pathService; private readonly IValidator _validator; @@ -38,15 +38,15 @@ public class GetPathParentQueryHandler : IQueryHandlerThe query containing the requested path. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a collection of , or an error message. + /// An containing either a collection of , or an error message. /// - public Task>> HandleAsync(GetPathParentQuery query, CancellationToken cancellationToken) + public Task>> HandleAsync(GetPathParentQuery query, CancellationToken cancellationToken) { List validationResult = _validator.Validate(query); if (validationResult.Count > 0) - return Task.FromResult>>(validationResult); + return Task.FromResult>>(validationResult); - ErrorOr> goUpOneLevelResult = _pathService.GoUpOneLevel(query.Path!); - return Task.FromResult(goUpOneLevelResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); + Result> goUpOneLevelResult = _pathService.GoUpOneLevel(query.Path!); + return Task.FromResult(goUpOneLevelResult.Match(values => Result.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidator.cs index b1b903e1..60a56923 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; #endregion namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs index b9a57317..8c67c96b 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; @@ -16,7 +16,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot /// /// Handler for the query to get the root of a file system path. /// -public class GetPathRootQueryHandler : IQueryHandler> +public class GetPathRootQueryHandler : IQueryHandler> { private readonly IPathService _pathService; private readonly IValidator _validator; @@ -37,14 +37,14 @@ public class GetPathRootQueryHandler : IQueryHandler /// The query containing the requested path. /// Cancellation token that can be used to stop the execution. - /// An containing either the root of the specified path, or an error. - public Task> HandleAsync(GetPathRootQuery query, CancellationToken cancellationToken) + /// An containing either the root of the specified path, or an error. + public Task> HandleAsync(GetPathRootQuery query, CancellationToken cancellationToken) { List validationResult = _validator.Validate(query); if (validationResult.Count > 0) - return Task.FromResult>(validationResult); + return Task.FromResult>(validationResult); - ErrorOr getPathRootResult = _pathService.GetPathRoot(query.Path!); - return Task.FromResult(getPathRootResult.Match(values => ErrorOrFactory.From(values.ToResponse()), errors => errors)); + Result getPathRootResult = _pathService.GetPathRoot(query.Path!); + return Task.FromResult(getPathRootResult.Match(values => Result.From(values.ToResponse()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidator.cs index d7d81acb..fc31388d 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; #endregion namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandler.cs index b53f1aa3..d03092b1 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.FileSystemManagement.Path; @@ -14,7 +14,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePat /// /// Handler for the query to validate a file system path. /// -public class ValidatePathQueryHandler : IQueryHandler> +public class ValidatePathQueryHandler : IQueryHandler> { private readonly IPathService _pathService; private readonly IValidator _validator; @@ -36,14 +36,14 @@ public class ValidatePathQueryHandler : IQueryHandlerThe query containing the request. /// Cancellation token that can be used to stop the execution. /// - /// An containing either if the specified path is valid, if it isn't, or an error message. + /// An containing either if the specified path is valid, if it isn't, or an error message. /// - public Task> HandleAsync(ValidatePathQuery query, CancellationToken cancellationToken) + public Task> HandleAsync(ValidatePathQuery query, CancellationToken cancellationToken) { List validationResult = _validator.Validate(query); if (validationResult.Count > 0) - return Task.FromResult>(validationResult); + return Task.FromResult>(validationResult); - return Task.FromResult(ErrorOrFactory.From(new PathValidResponse(_pathService.IsValidPath(query.Path!)))); + return Task.FromResult(Result.From(new PathValidResponse(_pathService.IsValidPath(query.Path!)))); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidator.cs index 747a33d0..143339ea 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; #endregion namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs index a7d2072c..b2c1efac 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails; using Lumina.Application.Common.Infrastructure.Validation; @@ -16,7 +16,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThu /// /// Handler for the query to get the file thumbnail. /// -public class GetThumbnailQueryHandler : IQueryHandler> +public class GetThumbnailQueryHandler : IQueryHandler> { private readonly IThumbnailService _thumbnailsService; private readonly IValidator _validator; @@ -37,14 +37,14 @@ public class GetThumbnailQueryHandler : IQueryHandler /// The query to be handled. /// Cancellation token that can be used to stop the execution. - /// An containing either a thumbnail, or an error. - public async Task> HandleAsync(GetThumbnailQuery query, CancellationToken cancellationToken) + /// An containing either a thumbnail, or an error. + public async Task> HandleAsync(GetThumbnailQuery query, CancellationToken cancellationToken) { List validationResult = _validator.Validate(query); if (validationResult.Count > 0) return validationResult; - ErrorOr getThumbnailResult = await _thumbnailsService.GetThumbnailAsync(query.Path!, query.Quality, cancellationToken); - return await ValueTask.FromResult(getThumbnailResult.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors)); + Result getThumbnailResult = await _thumbnailsService.GetThumbnailAsync(query.Path!, query.Quality, cancellationToken); + return await ValueTask.FromResult(getThumbnailResult.Match(value => Result.From(value.ToResponse()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs index 37255df8..d65311cb 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; #endregion namespace Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs index c80d4889..a2179d80 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; @@ -23,7 +23,7 @@ namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApp /// /// Handler for the command to perform the initial application setup. /// -public class SetupApplicationCommandHandler : ICommandHandler> +public class SetupApplicationCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IPasswordHashService _hashService; @@ -71,9 +71,9 @@ public class SetupApplicationCommandHandler : ICommandHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public async Task> HandleAsync(SetupApplicationCommand command, CancellationToken cancellationToken) + public async Task> HandleAsync(SetupApplicationCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) @@ -81,8 +81,8 @@ public class SetupApplicationCommandHandler : ICommandHandler(); - ErrorOr> selectUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); - if (selectUsersResult.IsError) + Result> selectUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (selectUsersResult.IsFailure) return selectUsersResult.Errors; else if (selectUsersResult.Value.Any()) return Errors.Authorization.AdminAccountAlreadyCreated; @@ -112,26 +112,26 @@ public class SetupApplicationCommandHandler : ICommandHandler insertUserResult = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); - if (insertUserResult.IsError) + Result insertUserResult = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); + if (insertUserResult.IsFailure) return insertUserResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // set the default permissions, roles, roles permissions - ErrorOr setPermissionsResult = await _dataSeedService.SetDefaultAuthorizationPermissionsAsync(id, cancellationToken).ConfigureAwait(false); - if (setPermissionsResult.IsError) + Result setPermissionsResult = await _dataSeedService.SetDefaultAuthorizationPermissionsAsync(id, cancellationToken).ConfigureAwait(false); + if (setPermissionsResult.IsFailure) return setPermissionsResult.Errors; - ErrorOr setRoleResult = await _dataSeedService.SetDefaultAuthorizationRolesAsync(id, cancellationToken).ConfigureAwait(false); - if (setRoleResult.IsError) + Result setRoleResult = await _dataSeedService.SetDefaultAuthorizationRolesAsync(id, cancellationToken).ConfigureAwait(false); + if (setRoleResult.IsFailure) return setRoleResult.Errors; - ErrorOr setRolePermissionResult = await _dataSeedService.SetAdminRolePermissionsAsync(id, cancellationToken).ConfigureAwait(false); - if (setRolePermissionResult.IsError) + Result setRolePermissionResult = await _dataSeedService.SetAdminRolePermissionsAsync(id, cancellationToken).ConfigureAwait(false); + if (setRolePermissionResult.IsFailure) return setRolePermissionResult.Errors; - ErrorOr setRoleToAdminResult = await _dataSeedService.SetAdminRoleToAdministratorAccount(id, cancellationToken).ConfigureAwait(false); - if (setRoleToAdminResult.IsError) + Result setRoleToAdminResult = await _dataSeedService.SetAdminRoleToAdministratorAccount(id, cancellationToken).ConfigureAwait(false); + if (setRoleToAdminResult.IsFailure) return setRoleToAdminResult.Errors; // TODO: insert the default admin profile preferences when they are implemented diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs index 6eec60bf..56db7aa7 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; @@ -40,8 +40,8 @@ public class CheckInitializationQueryHandler : IQueryHandler(); // if the repository reports an error, or there are no users, the application has not been initialized - ErrorOr> selectUsersResult = await userRepository.GetAllAsync(cancellationToken); - if (!selectUsersResult.IsError) + Result> selectUsersResult = await userRepository.GetAllAsync(cancellationToken); + if (!selectUsersResult.IsFailure) return new InitializationResponse(selectUsersResult.Value.Any()); return new InitializationResponse(false); } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs index 7ce6ce44..9c105181 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; @@ -23,7 +23,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; @@ -31,7 +31,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; /// /// Handler for the command to add a media library. /// -public class AddLibraryCommandHandler : ICommandHandler> +public class AddLibraryCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -71,9 +71,9 @@ public class AddLibraryCommandHandler : ICommandHandlerThe command to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public async Task> HandleAsync(AddLibraryCommand command, CancellationToken cancellationToken) + public async Task> HandleAsync(AddLibraryCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) @@ -87,19 +87,19 @@ public class AddLibraryCommandHandler : ICommandHandler fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage); - if (fileSystemPathIdResult.IsError) + Result fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage); + if (fileSystemPathIdResult.IsFailure) return fileSystemPathIdResult.Errors; - ErrorOr imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false); - if (imageCheckResult.IsError) + Result imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false); + if (imageCheckResult.IsFailure) return imageCheckResult.Errors; if (imageCheckResult.Value == ImageType.None) return DomainErrors.Library.CoverFileMustBeAnImage; } // create a domain library object - ErrorOr createLibraryResult = Library.Create( + Result createLibraryResult = Library.Create( UserId.Create(_currentUserService.UserId!.Value), command.Title!, Enum.Parse(command.LibraryType!), @@ -113,7 +113,7 @@ public class AddLibraryCommandHandler : ICommandHandler insertLibraryResult = await libraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); - if (insertLibraryResult.IsError) + Result insertLibraryResult = await libraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); + if (insertLibraryResult.IsFailure) return insertLibraryResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // retrieve the newly saved media library from the persistence medium and return it - ErrorOr getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); - if (getCreatedLibraryResult.IsError) + Result getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); + if (getCreatedLibraryResult.IsFailure) return getCreatedLibraryResult.Errors; if (getCreatedLibraryResult.Value is null) return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs index 8e6f0bc2..b439d346 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs @@ -2,7 +2,7 @@ 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 Lumina.Domain.Common.Errors; using System; #endregion diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs index 2d9d60da..530cf153 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; @@ -22,7 +22,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrari /// /// Handler for the command for canceling the scan of all media libraries. /// -public class CancelLibrariesScanCommandHandler : ICommandHandler> +public class CancelLibrariesScanCommandHandler : ICommandHandler> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; @@ -53,14 +53,14 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler /// The command to be handled. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> HandleAsync(CancelLibrariesScanCommand command, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> HandleAsync(CancelLibrariesScanCommand command, CancellationToken cancellationToken) { ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); // get the running library scans of the current user from the repository - ErrorOr> getRunningLibraryScansResult = await libraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false); - if (getRunningLibraryScansResult.IsError) + Result> getRunningLibraryScansResult = await libraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false); + if (getRunningLibraryScansResult.IsFailure) return getRunningLibraryScansResult.Errors; // filter the library scans to process @@ -72,24 +72,24 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler libraryScan.UserId == _currentUserService.UserId)); // convert persistence library scans to domain entities - IEnumerable> libraryScansDomainResult = authorizedLibraryScans.ToDomainEntities(); + IEnumerable> libraryScansDomainResult = authorizedLibraryScans.ToDomainEntities(); List domainEvents = []; // for each library scan, perform the cancellation - foreach (ErrorOr libraryScanDomainResult in libraryScansDomainResult) + foreach (Result libraryScanDomainResult in libraryScansDomainResult) { - if (libraryScanDomainResult.IsError) + if (libraryScanDomainResult.IsFailure) return libraryScanDomainResult.Errors; // cancel the media library scan - ErrorOr cancelScanResult = libraryScanDomainResult.Value.CancelScan(); - if (cancelScanResult.IsError) + Result cancelScanResult = libraryScanDomainResult.Value.CancelScan(); + if (cancelScanResult.IsFailure) return cancelScanResult.Errors; // update the status of the library scan in the repository - ErrorOr updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); - if (updateLibraryScanResult.IsError) + Result updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateLibraryScanResult.IsFailure) return updateLibraryScanResult.Errors; // collect all the domain events created during this library scan start diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs index c51a844a..db7cc2f3 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; @@ -15,7 +15,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibraryScan; @@ -23,7 +23,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrary /// /// Handler for the command for canceling the scan of a media library. /// -public class CancelLibraryScanCommandHandler : ICommandHandler> +public class CancelLibraryScanCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -58,8 +58,8 @@ public class CancelLibraryScanCommandHandler : ICommandHandler /// The command to be handled. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> HandleAsync(CancelLibraryScanCommand command, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> HandleAsync(CancelLibraryScanCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) @@ -68,8 +68,8 @@ public class CancelLibraryScanCommandHandler : ICommandHandler(); // get the library scan from the repository - ErrorOr getLibraryScansResult = await libraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false); - if (getLibraryScansResult.IsError) + Result getLibraryScansResult = await libraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false); + if (getLibraryScansResult.IsFailure) return getLibraryScansResult.Errors; if (getLibraryScansResult.Value is null) return DomainErrors.LibraryScanning.LibraryScanNotFound; @@ -80,18 +80,18 @@ public class CancelLibraryScanCommandHandler : ICommandHandler libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); - if (libraryScanDomainResult.IsError) + Result libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); + if (libraryScanDomainResult.IsFailure) return libraryScanDomainResult.Errors; // cancel the media library scan - ErrorOr cancelScanResult = libraryScanDomainResult.Value.CancelScan(); - if (cancelScanResult.IsError) + Result cancelScanResult = libraryScanDomainResult.Value.CancelScan(); + if (cancelScanResult.IsFailure) return cancelScanResult.Errors; // update the status of the library scan in the repository - ErrorOr updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); - if (updateLibraryScanResult.IsError) + Result updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateLibraryScanResult.IsFailure) return updateLibraryScanResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs index 05e15b60..2510aaf3 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using System; #endregion diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs index 97c63bf2..40eeaae0 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; @@ -15,7 +15,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary; @@ -23,7 +23,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary /// /// Handler for the command to delete a library by its Id. /// -public class DeleteLibraryCommandHandler : ICommandHandler> +public class DeleteLibraryCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -58,8 +58,8 @@ public class DeleteLibraryCommandHandler : ICommandHandler /// The command to be handled. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> HandleAsync(DeleteLibraryCommand command, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> HandleAsync(DeleteLibraryCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) @@ -67,8 +67,8 @@ public class DeleteLibraryCommandHandler : ICommandHandler(); - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsError) + Result getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; @@ -79,13 +79,13 @@ public class DeleteLibraryCommandHandler : ICommandHandler createLibraryResult = getLibraryResult.Value.ToDomainEntity(); - if (createLibraryResult.IsError) + Result createLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (createLibraryResult.IsFailure) return createLibraryResult.Errors; // delete the domain aggregate - ErrorOr deleteDomainLibraryResult = createLibraryResult.Value.Delete(); - if (deleteDomainLibraryResult.IsError) + Result deleteDomainLibraryResult = createLibraryResult.Value.Delete(); + if (deleteDomainLibraryResult.IsFailure) return deleteDomainLibraryResult.Errors; // queue any domain events @@ -93,8 +93,8 @@ public class DeleteLibraryCommandHandler : ICommandHandler deletePersistenceLibraryResult = await libraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); - if (deletePersistenceLibraryResult.IsError) + Result deletePersistenceLibraryResult = await libraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + if (deletePersistenceLibraryResult.IsFailure) return deletePersistenceLibraryResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandValidator.cs index 39847676..d2130cc5 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using System; #endregion diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs index ceda7784..616e50ee 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; @@ -25,7 +25,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries /// /// Handler for the command for initiating the scan of all media libraries. /// -public class ScanLibrariesCommandHandler : ICommandHandler>> +public class ScanLibrariesCommandHandler : ICommandHandler>> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -56,19 +56,19 @@ public class ScanLibrariesCommandHandler : ICommandHandler /// The command to be handled. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task>> HandleAsync(ScanLibrariesCommand command, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task>> HandleAsync(ScanLibrariesCommand command, CancellationToken cancellationToken) { ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); // get all media libraries that are enabled and unlocked from the persistence medium - ErrorOr> getLibrariesResult = await libraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false); - if (getLibrariesResult.IsError) + Result> getLibrariesResult = await libraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false); + if (getLibrariesResult.IsFailure) return getLibrariesResult.Errors; // convert persistence libraries to domain entities - IEnumerable> domainEntitiesResult = getLibrariesResult.Value.ToDomainEntities(); + IEnumerable> domainEntitiesResult = getLibrariesResult.Value.ToDomainEntities(); // if the current user is not an admin, they can only scan the libraries that belong to them if (!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false)) @@ -78,41 +78,41 @@ public class ScanLibrariesCommandHandler : ICommandHandler domainEvents = []; // for each library, start the scan - foreach (ErrorOr domainLibraryResult in domainEntitiesResult) + foreach (Result domainLibraryResult in domainEntitiesResult) { - if (domainLibraryResult.IsError) + if (domainLibraryResult.IsFailure) return domainLibraryResult.Errors; // get the past month's scans for this library - ErrorOr> pastLibraryScansResult = + Result> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(domainLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); - if (pastLibraryScansResult.IsError) + if (pastLibraryScansResult.IsFailure) return pastLibraryScansResult.Errors; // convert the repository scans history to domain objects - IEnumerable> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities(); - foreach (ErrorOr pastLibraryScanDomainResult in pastLibraryScansDomainResult) - if (pastLibraryScanDomainResult.IsError) + IEnumerable> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities(); + foreach (Result pastLibraryScanDomainResult in pastLibraryScansDomainResult) + if (pastLibraryScanDomainResult.IsFailure) return pastLibraryScanDomainResult.Errors; // start the media library scan - ErrorOr libraryScanResult = LibraryScan.Create( + Result libraryScanResult = LibraryScan.Create( LibraryId.Create(domainLibraryResult.Value.Id.Value), UserId.Create(_currentUserService.UserId!.Value), [.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)] ); - if (libraryScanResult.IsError) + if (libraryScanResult.IsFailure) return libraryScanResult.Errors; - ErrorOr startScanResult = libraryScanResult.Value.QueueScan(); + Result startScanResult = libraryScanResult.Value.QueueScan(); // when the user demands a "scan all libraries" action, it would be annoying to receive an error if a library is already being scanned. // instead, just don't start the scan on such a library, and start it on the others that can be started - if (startScanResult.IsError) + if (startScanResult.IsFailure) continue; // add the library scan to the persistence medium - ErrorOr insertLibraryScanResult = await libraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); - if (insertLibraryScanResult.IsError) + Result insertLibraryScanResult = await libraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (insertLibraryScanResult.IsFailure) return insertLibraryScanResult.Errors; // collect all the domain events created during this library scan start diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs index 826ed966..d22135bf 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; @@ -21,7 +21,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary; @@ -29,7 +29,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary; /// /// Handler for the command for initiating the scan of a media library. /// -public class ScanLibraryCommandHandler : ICommandHandler> +public class ScanLibraryCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -64,8 +64,8 @@ public class ScanLibraryCommandHandler : ICommandHandler /// The command to be handled. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> HandleAsync(ScanLibraryCommand command, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> HandleAsync(ScanLibraryCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) @@ -75,8 +75,8 @@ public class ScanLibraryCommandHandler : ICommandHandler(); // get the media library from the persistence medium - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsError) + Result getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) return getLibraryResult.Errors; if (getLibraryResult.Value is null) @@ -95,37 +95,37 @@ public class ScanLibraryCommandHandler : ICommandHandler domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); - if (domainLibraryResult.IsError) + Result domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsFailure) return domainLibraryResult.Errors; // get the past month's scans for this library - ErrorOr> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, cancellationToken).ConfigureAwait(false); - if (pastLibraryScansResult.IsError) + Result> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + if (pastLibraryScansResult.IsFailure) return pastLibraryScansResult.Errors; // convert the repository scans history to domain objects - IEnumerable> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities(); - foreach (ErrorOr pastLibraryScanDomainResult in pastLibraryScansDomainResult) - if (pastLibraryScanDomainResult.IsError) + IEnumerable> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities(); + foreach (Result pastLibraryScanDomainResult in pastLibraryScansDomainResult) + if (pastLibraryScanDomainResult.IsFailure) return pastLibraryScanDomainResult.Errors; // queue the media library scan - ErrorOr libraryScanResult = LibraryScan.Create( + Result libraryScanResult = LibraryScan.Create( LibraryId.Create(command.Id), UserId.Create(_currentUserService.UserId!.Value), [.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)] ); - if (libraryScanResult.IsError) + if (libraryScanResult.IsFailure) return libraryScanResult.Errors; - ErrorOr queueScanResult = libraryScanResult.Value.QueueScan(); - if (queueScanResult.IsError) + Result queueScanResult = libraryScanResult.Value.QueueScan(); + if (queueScanResult.IsFailure) return queueScanResult.Errors; // add the library scan to the persistence medium - ErrorOr insertLibraryScanResult = await libraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); - if (insertLibraryScanResult.IsError) + Result insertLibraryScanResult = await libraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (insertLibraryScanResult.IsFailure) return insertLibraryScanResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandValidator.cs index f053e552..aae421e3 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using System; #endregion diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs index 5daac492..70432b7f 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; @@ -26,7 +26,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; @@ -34,7 +34,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary /// /// Handler for the command to update a media library. /// -public class UpdateLibraryCommandHandler : ICommandHandler> +public class UpdateLibraryCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -74,9 +74,9 @@ public class UpdateLibraryCommandHandler : ICommandHandlerThe command to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully updated , or an error message. + /// An containing either a successfully updated , or an error message. /// - public async Task> HandleAsync(UpdateLibraryCommand command, CancellationToken cancellationToken) + public async Task> HandleAsync(UpdateLibraryCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) @@ -85,12 +85,12 @@ public class UpdateLibraryCommandHandler : ICommandHandler fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage); - if (fileSystemPathIdResult.IsError) + Result fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage); + if (fileSystemPathIdResult.IsFailure) return fileSystemPathIdResult.Errors; - ErrorOr imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false); - if (imageCheckResult.IsError) + Result imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false); + if (imageCheckResult.IsFailure) return imageCheckResult.Errors; if (imageCheckResult.Value == ImageType.None) return DomainErrors.Library.CoverFileMustBeAnImage; @@ -98,8 +98,8 @@ public class UpdateLibraryCommandHandler : ICommandHandler(); - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsError) + Result getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; @@ -111,7 +111,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler createLibraryResult = Library.Create( + Result createLibraryResult = Library.Create( LibraryId.Create(command.Id), UserId.Create(command.OwnerId), command.Title!, @@ -125,20 +125,20 @@ public class UpdateLibraryCommandHandler : ICommandHandler ScanId.Create(libraryScan.Id)).ToList() ); - if (createLibraryResult.IsError) + if (createLibraryResult.IsFailure) return createLibraryResult.Errors; // convert the domain library entity to a repository library entity LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity(); // update the repository entity and save changes - ErrorOr updateLibraryResult = await libraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); - if (updateLibraryResult.IsError) + Result updateLibraryResult = await libraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); + if (updateLibraryResult.IsFailure) return updateLibraryResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // retrieve the updated media library from the persistence medium and return it - ErrorOr getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); - if (getCreatedLibraryResult.IsError) + Result getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); + if (getCreatedLibraryResult.IsFailure) return getCreatedLibraryResult.Errors; if (getCreatedLibraryResult.Value is null) return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs index 6d32e5eb..53ed0211 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs @@ -2,7 +2,7 @@ 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 Lumina.Domain.Common.Errors; using System; #endregion diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs index 5f4ab957..17beb518 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; @@ -45,16 +45,16 @@ public class LibraryDeletedDomainEventHandler : IDomainEventHandler libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value); - if (libraryPathResult.IsError) + Result libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value); + if (libraryPathResult.IsFailure) throw new EventualConsistencyException(libraryPathResult.FirstError, libraryPathResult.Errors); - ErrorOr newLibraryPathIdResult = FileSystemPathId.Create(libraryPathResult.Value); - if (newLibraryPathIdResult.IsError) + Result newLibraryPathIdResult = FileSystemPathId.Create(libraryPathResult.Value); + if (newLibraryPathIdResult.IsFailure) throw new EventualConsistencyException(newLibraryPathIdResult.FirstError, newLibraryPathIdResult.Errors); - ErrorOr deleteLibraryDirectoryResult = _environmentContext.DirectoryProviderService.DeleteDirectory(newLibraryPathIdResult.Value); - if (deleteLibraryDirectoryResult.IsError) + Result deleteLibraryDirectoryResult = _environmentContext.DirectoryProviderService.DeleteDirectory(newLibraryPathIdResult.Value); + if (deleteLibraryDirectoryResult.IsFailure) throw new EventualConsistencyException(deleteLibraryDirectoryResult.FirstError, deleteLibraryDirectoryResult.Errors); return ValueTask.CompletedTask; @@ -65,23 +65,23 @@ public class LibraryDeletedDomainEventHandler : IDomainEventHandler /// The id of the media library for which to regtrieve the file system path. /// - /// An containing either the file system path of the media library, or an error message. + /// An containing either the file system path of the media library, or an error message. /// - private ErrorOr GetLibraryPath(Guid libraryId) + private Result GetLibraryPath(Guid libraryId) { // root directory for media - ErrorOr rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); - if (rootPathResult.IsError) + Result rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); + if (rootPathResult.IsFailure) return rootPathResult.Errors; // libraries directory - ErrorOr librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); - if (librariesPathResult.IsError) + Result librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); + if (librariesPathResult.IsFailure) return librariesPathResult.Errors; // this new particular library' directory - ErrorOr libraryPathResult = _pathService.CombinePath(librariesPathResult.Value, libraryId.ToString()); - if (libraryPathResult.IsError) + Result libraryPathResult = _pathService.CombinePath(librariesPathResult.Value, libraryId.ToString()); + if (libraryPathResult.IsFailure) return libraryPathResult.Errors; return libraryPathResult.Value; } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs index e83e3411..638d1778 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; @@ -61,22 +61,22 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler saveCoverImageResult = await SaveCoverImageToMediaDirectoryAsync(domainEvent.Library.Id.Value, domainEvent.Library.CoverImage, cancellationToken).ConfigureAwait(false); - if (saveCoverImageResult.IsError) + Result saveCoverImageResult = await SaveCoverImageToMediaDirectoryAsync(domainEvent.Library.Id.Value, domainEvent.Library.CoverImage, cancellationToken).ConfigureAwait(false); + if (saveCoverImageResult.IsFailure) throw new EventualConsistencyException(saveCoverImageResult.FirstError, saveCoverImageResult.Errors); domainEvent.Library.SetInternalLibraryCoverImagePath(saveCoverImageResult.Value); // update the media library with the new cover location ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); - ErrorOr updateLibraryResult = await libraryRepository.UpdateAsync(domainEvent.Library.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); - if (updateLibraryResult.IsError) + Result updateLibraryResult = await libraryRepository.UpdateAsync(domainEvent.Library.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateLibraryResult.IsFailure) throw new EventualConsistencyException(updateLibraryResult.FirstError, updateLibraryResult.Errors); await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); } else // no cover image is provided, delete any cover image that might exist in the internal location for media library files { - ErrorOr libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value); - if (libraryPathResult.IsError) + Result libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value); + if (libraryPathResult.IsFailure) throw new EventualConsistencyException(libraryPathResult.FirstError, libraryPathResult.Errors); DeleteCoverImageFromMediaDirectory(libraryPathResult.Value); } @@ -87,23 +87,23 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler /// The id of the media library for which to regtrieve the file system path. /// - /// An containing either the file system path of the media library, or an error message. + /// An containing either the file system path of the media library, or an error message. /// - private ErrorOr GetLibraryPath(Guid libraryId) + private Result GetLibraryPath(Guid libraryId) { // root directory for media - ErrorOr rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); - if (rootPathResult.IsError) + Result rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); + if (rootPathResult.IsFailure) return rootPathResult.Errors; // libraries directory - ErrorOr librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); - if (librariesPathResult.IsError) + Result librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); + if (librariesPathResult.IsFailure) return librariesPathResult.Errors; // this new particular library' directory - ErrorOr libraryPathResult = _pathService.CombinePath(librariesPathResult.Value, libraryId.ToString()); - if (libraryPathResult.IsError) + Result libraryPathResult = _pathService.CombinePath(librariesPathResult.Value, libraryId.ToString()); + if (libraryPathResult.IsFailure) return libraryPathResult.Errors; return libraryPathResult.Value; } @@ -115,62 +115,62 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandlerThe file path of the image file that will be copied to the media directory. /// Cancellation token that can be used to stop the execution. /// - /// An containing either the location of the new cover image, or an error message. + /// An containing either the location of the new cover image, or an error message. /// - private async Task> SaveCoverImageToMediaDirectoryAsync(Guid libraryId, string imagePath, CancellationToken cancellationToken) + private async Task> SaveCoverImageToMediaDirectoryAsync(Guid libraryId, string imagePath, CancellationToken cancellationToken) { - ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(imagePath); - if (fileSystemPathIdResult.IsError) + Result fileSystemPathIdResult = FileSystemPathId.Create(imagePath); + if (fileSystemPathIdResult.IsFailure) return fileSystemPathIdResult.Errors; - ErrorOr fileExistsResult = _environmentContext.FileProviderService.FileExists(fileSystemPathIdResult.Value); - if (fileExistsResult.IsError) + Result fileExistsResult = _environmentContext.FileProviderService.FileExists(fileSystemPathIdResult.Value); + if (fileExistsResult.IsFailure) return fileExistsResult.Errors; if (!fileExistsResult.Value) return Errors.FileSystemManagement.FileNotFound; // make sure the file is an actual supported image - ErrorOr imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false); - if (imageCheckResult.IsError) + Result imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false); + if (imageCheckResult.IsFailure) return imageCheckResult.Errors; if (imageCheckResult.Value == ImageType.None) return Errors.Library.CoverFileMustBeAnImage; // the provided cover image path exists and is a valid image, store it in the media directory - ErrorOr rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); // root directory for media - if (rootPathResult.IsError) + Result rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); // root directory for media + if (rootPathResult.IsFailure) return rootPathResult.Errors; - ErrorOr librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); // libraries directory - if (librariesPathResult.IsError) + Result librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); // libraries directory + if (librariesPathResult.IsFailure) return librariesPathResult.Errors; - ErrorOr rootPathIdResult = FileSystemPathId.Create(rootPathResult.Value); - if (rootPathIdResult.IsError) + Result rootPathIdResult = FileSystemPathId.Create(rootPathResult.Value); + if (rootPathIdResult.IsFailure) return rootPathIdResult.Errors; - ErrorOr librariesPathIdResult = FileSystemPathId.Create(librariesPathResult.Value); - if (librariesPathIdResult.IsError) + Result librariesPathIdResult = FileSystemPathId.Create(librariesPathResult.Value); + if (librariesPathIdResult.IsFailure) return librariesPathIdResult.Errors; // create the path of the new library - ErrorOr libraryPathResult = GetLibraryPath(libraryId); - if (libraryPathResult.IsError) + Result libraryPathResult = GetLibraryPath(libraryId); + if (libraryPathResult.IsFailure) return libraryPathResult.Errors; - ErrorOr newLibraryPathIdResult = FileSystemPathId.Create(libraryPathResult.Value); - if (newLibraryPathIdResult.IsError) + Result newLibraryPathIdResult = FileSystemPathId.Create(libraryPathResult.Value); + if (newLibraryPathIdResult.IsFailure) return newLibraryPathIdResult.Errors; // check if it doesn't already exist, and if so, create it - ErrorOr directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(newLibraryPathIdResult.Value); - if (directoryExistsResult.IsError) + Result directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(newLibraryPathIdResult.Value); + if (directoryExistsResult.IsFailure) return directoryExistsResult.Errors; if (!directoryExistsResult.Value) { - ErrorOr createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(librariesPathIdResult.Value, libraryId.ToString()); - if (createDirectoryResult.IsError) + Result createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(librariesPathIdResult.Value, libraryId.ToString()); + if (createDirectoryResult.IsFailure) return createDirectoryResult.Errors; } else @@ -178,18 +178,18 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler deleteExistingCoverImageResult = DeleteCoverImageFromMediaDirectory(libraryPathResult.Value); - if (deleteExistingCoverImageResult.IsError) + Result deleteExistingCoverImageResult = DeleteCoverImageFromMediaDirectory(libraryPathResult.Value); + if (deleteExistingCoverImageResult.IsFailure) return deleteExistingCoverImageResult.Errors; } // copy the new cover file from the location provided by the user - ErrorOr copyFileResult = _environmentContext.FileProviderService.CopyFile(fileSystemPathIdResult.Value, newLibraryPathIdResult.Value, true); - if (copyFileResult.IsError) + Result copyFileResult = _environmentContext.FileProviderService.CopyFile(fileSystemPathIdResult.Value, newLibraryPathIdResult.Value, true); + if (copyFileResult.IsFailure) return copyFileResult.Errors; // rename the new cover file to the standard naming - ErrorOr renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageCheckResult.Value.ToString().ToLower()}"); - if (renameFileResult.IsError) + Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageCheckResult.Value.ToString().ToLower()}"); + if (renameFileResult.IsFailure) return renameFileResult.Errors; // get the internal relative path for the copied file @@ -203,17 +203,17 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler /// The path where the library content is located. - /// An representing either a successful operation, or an error. - private ErrorOr DeleteCoverImageFromMediaDirectory(string libraryPath) + /// An representing either a successful operation, or an error. + private Result DeleteCoverImageFromMediaDirectory(string libraryPath) { - ErrorOr newLibraryPathIdResult = FileSystemPathId.Create(libraryPath); - if (newLibraryPathIdResult.IsError) + Result newLibraryPathIdResult = FileSystemPathId.Create(libraryPath); + if (newLibraryPathIdResult.IsFailure) return newLibraryPathIdResult.Errors; // get existing files of this media library's directory, and delete previous cover files, if they are found - ErrorOr> getExistingLibraryFilesResult = _environmentContext.FileProviderService.GetFilePaths(newLibraryPathIdResult.Value, true); - if (getExistingLibraryFilesResult.IsError) + Result> getExistingLibraryFilesResult = _environmentContext.FileProviderService.GetFilePaths(newLibraryPathIdResult.Value, true); + if (getExistingLibraryFilesResult.IsFailure) return getExistingLibraryFilesResult.Errors; foreach (FileSystemPathId filePathId in getExistingLibraryFilesResult.Value) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs index 0c176b68..fdbd0be7 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; 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.Mapping.MediaLibrary.Management; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; @@ -59,20 +59,20 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler getLibraryScansResult = await _libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryScansResult.IsError) + Result getLibraryScansResult = await _libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryScansResult.IsFailure) throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); if (getLibraryScansResult.Value is null) throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); // convert the repository scan to a domain object - ErrorOr libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); - if (libraryScanDomainResult.IsError) + Result libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); + if (libraryScanDomainResult.IsFailure) throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); // cancel the media library scan - ErrorOr cancelScanResult = _mediaLibraryScanningService.CancelScan(libraryScanDomainResult.Value); - if (cancelScanResult.IsError) + Result cancelScanResult = _mediaLibraryScanningService.CancelScan(libraryScanDomainResult.Value); + if (cancelScanResult.IsFailure) throw new EventualConsistencyException(cancelScanResult.FirstError, cancelScanResult.Errors); // release the scan processing resources @@ -80,8 +80,8 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler clearStagingResult = await stagingResultsRepository.ClearForScanAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); - if (clearStagingResult.IsError) + Result clearStagingResult = await stagingResultsRepository.ClearForScanAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + if (clearStagingResult.IsFailure) throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs index 8da1fdbf..e4b6d3d3 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; 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.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Progress; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; @@ -58,27 +58,27 @@ public class LibraryScanFailedDomainEventHandler : IDomainEventHandler(); // get the library scan from the repository - ErrorOr getLibraryScansResult = await libraryScanRepository.GetByIdAsync( + Result getLibraryScansResult = await libraryScanRepository.GetByIdAsync( domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryScansResult.IsError) + if (getLibraryScansResult.IsFailure) throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); if (getLibraryScansResult.Value is null) throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); // convert the repository scan to a domain object - ErrorOr libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); - if (libraryScanDomainResult.IsError) + Result libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); + if (libraryScanDomainResult.IsFailure) throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); // mark the media library scan as failed - ErrorOr failScanResult = libraryScanDomainResult.Value.FailScan(); + Result failScanResult = libraryScanDomainResult.Value.FailScan(); // we're going to ignore errors in this point, because scan jobs run in parallel, and two concurrent jobs of the same scan might trigger this domain event, // trying to set as failed a scan that has already been marked as failed by a concurrent job - if (!failScanResult.IsError) + if (!failScanResult.IsFailure) { // update the status of the library scan in the repository - ErrorOr updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); - if (updateLibraryScanResult.IsError) + Result updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateLibraryScanResult.IsFailure) throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors); await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); @@ -87,8 +87,8 @@ public class LibraryScanFailedDomainEventHandler : IDomainEventHandler clearStagingResult = await stagingResultsRepository.ClearForScanAsync(domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); - if (clearStagingResult.IsError) + Result clearStagingResult = await stagingResultsRepository.ClearForScanAsync(domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); + if (clearStagingResult.IsFailure) throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors); // notify SignalR clients that the library scan failed diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs index a0b20187..c5f7a482 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; 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.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Progress; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; @@ -57,26 +57,26 @@ public class LibraryScanFinishedDomainEventHandler : IDomainEventHandler(); // get the library scan from the repository - ErrorOr getLibraryScansResult = await libraryScanRepository.GetByIdAsync( + Result getLibraryScansResult = await libraryScanRepository.GetByIdAsync( domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryScansResult.IsError) + if (getLibraryScansResult.IsFailure) throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); if (getLibraryScansResult.Value is null) throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); // convert the repository scan to a domain object - ErrorOr libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); - if (libraryScanDomainResult.IsError) + Result libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); + if (libraryScanDomainResult.IsFailure) throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); // mark the media library scan as finished - ErrorOr finishScanResult = libraryScanDomainResult.Value.FinishScan(); - if (finishScanResult.IsError) + Result finishScanResult = libraryScanDomainResult.Value.FinishScan(); + if (finishScanResult.IsFailure) throw new EventualConsistencyException(finishScanResult.FirstError, finishScanResult.Errors); // update the library scan in the repository - ErrorOr updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); - if (updateLibraryScanResult.IsError) + Result updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateLibraryScanResult.IsFailure) throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors); await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs index adbaf656..2f18693e 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; @@ -51,19 +51,19 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler(); // get the library scan that was queued, from the repository - ErrorOr getLibraryScanResult = await libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryScanResult.IsError || getLibraryScanResult.Value is null) + Result getLibraryScanResult = await libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryScanResult.IsFailure || getLibraryScanResult.Value is null) throw new EventualConsistencyException(getLibraryScanResult.FirstError, getLibraryScanResult.Errors); // convert the repository entity to a domain entity - ErrorOr libraryScanDomainResult = getLibraryScanResult.Value.ToDomainEntity(); - if (libraryScanDomainResult.IsError) + Result libraryScanDomainResult = getLibraryScanResult.Value.ToDomainEntity(); + if (libraryScanDomainResult.IsFailure) throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); // start the media library scan - ErrorOr startScanResult = await _mediaLibraryScanningService.StartScanAsync( + Result startScanResult = await _mediaLibraryScanningService.StartScanAsync( libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, getLibraryScanResult.Value.Library.DownloadMetadataFromWeb, cancellationToken).ConfigureAwait(false); - if (startScanResult.IsError) + if (startScanResult.IsFailure) throw new EventualConsistencyException(startScanResult.FirstError, startScanResult.Errors); // queue any domain events diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs index a6597e5e..d66ffe68 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.Management; @@ -38,8 +38,8 @@ public class LibraryScanStartedDomainEventHandler : IDomainEventHandler(); // update the status of the library scan in the repository - ErrorOr updateLibraryScanResult = await libraryScanRepository.UpdateAsync(domainEvent.LibraryScan.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); - if (updateLibraryScanResult.IsError) + Result updateLibraryScanResult = await libraryScanRepository.UpdateAsync(domainEvent.LibraryScan.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateLibraryScanResult.IsFailure) throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors); await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs index 97ef688d..f6ed371f 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; @@ -19,7 +19,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibr /// /// Handler for the query to get the enabled media libraries. /// -public class GetEnabledLibrariesQueryHandler : IQueryHandler> +public class GetEnabledLibrariesQueryHandler : IQueryHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -47,19 +47,19 @@ public class GetEnabledLibrariesQueryHandler : IQueryHandlerThe query to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public async Task> HandleAsync(GetEnabledLibrariesQuery query, CancellationToken cancellationToken) + public async Task> HandleAsync(GetEnabledLibrariesQuery query, CancellationToken cancellationToken) { // get the enabled libraries from the repository ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); - ErrorOr> getEnabledLibrariesResult = await libraryRepository.GetAllEnabledAsync(cancellationToken).ConfigureAwait(false); - if (getEnabledLibrariesResult.IsError) + Result> getEnabledLibrariesResult = await libraryRepository.GetAllEnabledAsync(cancellationToken).ConfigureAwait(false); + if (getEnabledLibrariesResult.IsFailure) return getEnabledLibrariesResult.Errors; // admins can see all libraries if (await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false)) - return ErrorOrFactory.From(getEnabledLibrariesResult.Value.Select(library => library.ToResponse()).ToArray()); + return Result.From(getEnabledLibrariesResult.Value.Select(library => library.ToResponse()).ToArray()); else { // for regular users, only take the libraries that belong to them @@ -67,7 +67,7 @@ public class GetEnabledLibrariesQueryHandler : IQueryHandler library.UserId == _currentUserService.UserId) .Select(library => library.ToResponse())]; - return ErrorOrFactory.From(userEnabledLibraries); + return Result.From(userEnabledLibraries); } } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs index ea39a937..0cba2396 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; @@ -19,7 +19,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries; /// /// Handler for the query to get the media libraries. /// -public class GetLibrariesQueryHandler : IQueryHandler> +public class GetLibrariesQueryHandler : IQueryHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -47,19 +47,19 @@ public class GetLibrariesQueryHandler : IQueryHandlerThe query to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public async Task> HandleAsync(GetLibrariesQuery query, CancellationToken cancellationToken) + public async Task> HandleAsync(GetLibrariesQuery query, CancellationToken cancellationToken) { // get the libraries from the repository ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); - ErrorOr> getLibrariesResult = await libraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); - if (getLibrariesResult.IsError) + Result> getLibrariesResult = await libraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getLibrariesResult.IsFailure) return getLibrariesResult.Errors; // admins can see all libraries if (await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false)) - return ErrorOrFactory.From(getLibrariesResult.Value.Select(library => library.ToResponse()).ToArray()); + return Result.From(getLibrariesResult.Value.Select(library => library.ToResponse()).ToArray()); else { // for regular users, only take the libraries that belong to them @@ -67,7 +67,7 @@ public class GetLibrariesQueryHandler : IQueryHandler library.UserId == _currentUserService.UserId) .Select(library => library.ToResponse())]; - return ErrorOrFactory.From(userLibraries); + return Result.From(userLibraries); } } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs index 1cb15caa..46766776 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; @@ -14,7 +14,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary; @@ -22,7 +22,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary; /// /// Handler for the query to get a library by its Id. /// -public class GetLibraryQueryHandler : IQueryHandler> +public class GetLibraryQueryHandler : IQueryHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -54,9 +54,9 @@ public class GetLibraryQueryHandler : IQueryHandlerThe query to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public async Task> HandleAsync(GetLibraryQuery query, CancellationToken cancellationToken) + public async Task> HandleAsync(GetLibraryQuery query, CancellationToken cancellationToken) { List validationResult = _validator.Validate(query); if (validationResult.Count > 0) @@ -64,8 +64,8 @@ public class GetLibraryQueryHandler : IQueryHandler(); - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsError) + Result getLibraryResult = await libraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryValidator.cs index 7e2c54c4..50c3db06 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using System; #endregion diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs index dbbd4a1e..3630ca73 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; @@ -17,7 +17,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScanProgress; @@ -25,7 +25,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScan /// /// Handler for the query to get the progress of a library scan. /// -public class GetLibraryScanProgressQueryHandler : IQueryHandler> +public class GetLibraryScanProgressQueryHandler : IQueryHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -61,9 +61,9 @@ public class GetLibraryScanProgressQueryHandler : IQueryHandlerThe query to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a , or an error message. + /// An containing either a , or an error message. /// - public async Task> HandleAsync(GetLibraryScanProgressQuery query, CancellationToken cancellationToken) + public async Task> HandleAsync(GetLibraryScanProgressQuery query, CancellationToken cancellationToken) { List validationResult = _validator.Validate(query); if (validationResult.Count > 0) @@ -71,8 +71,8 @@ public class GetLibraryScanProgressQueryHandler : IQueryHandler(); - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsError) + Result getLibraryResult = await libraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; @@ -82,9 +82,9 @@ public class GetLibraryScanProgressQueryHandler : IQueryHandler getProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress( + Result getProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress( MediaLibraryScanCompositeId.Create(ScanId.Create(query.ScanId), UserId.Create(_currentUserService.UserId!.Value))); - if (getProgressResult.IsError) + if (getProgressResult.IsFailure) return getProgressResult.Errors; return getProgressResult.Value.ToResponse(); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryValidator.cs index 648b17a4..1bfe5198 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using System; #endregion diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs index bea6d4f2..ac3bae15 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; @@ -22,7 +22,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibr /// /// Handler for the query to get the ongoing media library scans. /// -public class GetRunningLibraryScansQueryHandler : IQueryHandler>> +public class GetRunningLibraryScansQueryHandler : IQueryHandler>> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -54,14 +54,14 @@ public class GetRunningLibraryScansQueryHandler : IQueryHandlerThe query to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public async Task>> HandleAsync(GetRunningLibraryScansQuery query, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetRunningLibraryScansQuery query, CancellationToken cancellationToken) { // get the ongoing library scans from the repository ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); - ErrorOr> getRunningScansResult = await libraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false); - if (getRunningScansResult.IsError) + Result> getRunningScansResult = await libraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false); + if (getRunningScansResult.IsFailure) return getRunningScansResult.Errors; // filter the library scans by what the user is allowed to see @@ -75,21 +75,21 @@ public class GetRunningLibraryScansQueryHandler : IQueryHandler libraryScanProgresses = []; - IEnumerable> userRunningDomainLibraryScans = userRunningRepositoryLibraryScans.ToDomainEntities(); - foreach (ErrorOr userRunningDomainLibraryScan in userRunningDomainLibraryScans) + IEnumerable> userRunningDomainLibraryScans = userRunningRepositoryLibraryScans.ToDomainEntities(); + foreach (Result userRunningDomainLibraryScan in userRunningDomainLibraryScans) { - if (userRunningDomainLibraryScan.IsError) + if (userRunningDomainLibraryScan.IsFailure) return userRunningDomainLibraryScan.Errors; else { - ErrorOr getLibraryScanProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress( + Result getLibraryScanProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress( MediaLibraryScanCompositeId.Create(userRunningDomainLibraryScan.Value.Id, userRunningDomainLibraryScan.Value.UserId)); - if (getLibraryScanProgressResult.IsError) + if (getLibraryScanProgressResult.IsFailure) return getLibraryScanProgressResult.Errors; libraryScanProgresses.Add(getLibraryScanProgressResult.Value.ToResponse()); } } - return ErrorOrFactory.From(libraryScanProgresses.AsEnumerable()); + return Result.From(libraryScanProgresses.AsEnumerable()); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs index 9d8d4434..a7498103 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; @@ -8,7 +8,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentL using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Domain.Common.Primitives; + using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; @@ -28,7 +28,7 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar /// /// Handler for the command to add a book. /// -public class AddBookCommandHandler : ICommandHandler> +public class AddBookCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IValidator _validator; @@ -50,9 +50,9 @@ public class AddBookCommandHandler : ICommandHandlerThe command to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public async Task> HandleAsync(AddBookCommand command, CancellationToken cancellationToken) + public async Task> HandleAsync(AddBookCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) @@ -70,37 +70,37 @@ public class AddBookCommandHandler : ICommandHandler> domainRatingsResult = command.Ratings!.ConvertAll(rating => BookRating.Create( + List> domainRatingsResult = command.Ratings!.ConvertAll(rating => BookRating.Create( rating.Value ?? default, rating.MaxValue ?? default, Optional.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : (BookRatingSource?)null), Optional.FromNullable(rating.VoteCount))); // check if any of the results contain errors - List errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsError).SelectMany(ratingResult => ratingResult.Errors)]; + List errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; if (errors.Count != 0) // if there are errors, return them return errors; List domainRatings = [.. domainRatingsResult.Select(rating => rating.Value)]; - List> domainGenresResult = command.Metadata!.Genres!.ConvertAll(genre => Genre.Create(genre.Name!)); - errors = [.. domainGenresResult.Where(genreResult => genreResult.IsError).SelectMany(genreResult => genreResult.Errors)]; + List> domainGenresResult = command.Metadata!.Genres!.ConvertAll(genre => Genre.Create(genre.Name!)); + errors = [.. domainGenresResult.Where(genreResult => genreResult.IsFailure).SelectMany(genreResult => genreResult.Errors)]; if (errors.Count != 0) return errors; List domainGenres = [.. domainGenresResult.Select(genre => genre.Value)]; - List> domainTagsResult = command.Metadata.Tags!.ConvertAll(tag => Tag.Create(tag.Name!)); - errors = [.. domainTagsResult.Where(tagResult => tagResult.IsError).SelectMany(tagResult => tagResult.Errors)]; + List> domainTagsResult = command.Metadata.Tags!.ConvertAll(tag => Tag.Create(tag.Name!)); + errors = [.. domainTagsResult.Where(tagResult => tagResult.IsFailure).SelectMany(tagResult => tagResult.Errors)]; if (errors.Count != 0) return errors; List domainTags = [.. domainTagsResult.Select(tag => tag.Value)]; - List> domainIsbnsResult = command.ISBNs!.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!)); - errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsError).SelectMany(isbnResult => isbnResult.Errors)]; + List> domainIsbnsResult = command.ISBNs!.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!)); + errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors)]; if (errors.Count != 0) return errors; List domainIsbns = [.. domainIsbnsResult.Select(isbn => isbn.Value)]; - ErrorOr releaseInfoResult = ReleaseInfo.Create( + Result releaseInfoResult = ReleaseInfo.Create( Optional.FromNullable(command.Metadata.ReleaseInfo!.OriginalReleaseDate), Optional.FromNullable(command.Metadata.ReleaseInfo.OriginalReleaseYear), Optional.FromNullable(command.Metadata.ReleaseInfo.ReReleaseDate), @@ -108,32 +108,32 @@ public class AddBookCommandHandler : ICommandHandler.FromNullable(command.Metadata.ReleaseInfo.ReleaseCountry), Optional.FromNullable(command.Metadata.ReleaseInfo.ReleaseVersion) ); - if (releaseInfoResult.IsError) + if (releaseInfoResult.IsFailure) return releaseInfoResult.Errors; ReleaseInfo releaseInfo = releaseInfoResult.Value; LanguageInfo? languageInfo = null; if (command.Metadata.Language is not null) { - ErrorOr languageInfoResult = LanguageInfo.Create( + Result languageInfoResult = LanguageInfo.Create( command.Metadata.Language.LanguageCode!, command.Metadata.Language.LanguageName!, Optional.FromNullable(command.Metadata.Language.NativeName)); - if (languageInfoResult.IsError) + if (languageInfoResult.IsFailure) return languageInfoResult.Errors; languageInfo = languageInfoResult.Value; } LanguageInfo? originalLanguageInfo = null; if (command.Metadata.OriginalLanguage is not null) { - ErrorOr originalLanguageInfoResult = LanguageInfo.Create( + Result originalLanguageInfoResult = LanguageInfo.Create( command.Metadata.OriginalLanguage.LanguageCode!, command.Metadata.OriginalLanguage.LanguageName!, Optional.FromNullable(command.Metadata.OriginalLanguage.NativeName)); - if (originalLanguageInfoResult.IsError) + if (originalLanguageInfoResult.IsFailure) return originalLanguageInfoResult.Errors; originalLanguageInfo = originalLanguageInfoResult.Value; } - ErrorOr metadataResult = WrittenContentMetadata.Create( + Result metadataResult = WrittenContentMetadata.Create( command.Metadata.Title!, Optional.FromNullable(command.Metadata.OriginalTitle), Optional.FromNullable(command.Metadata.Description), @@ -145,9 +145,9 @@ public class AddBookCommandHandler : ICommandHandler.FromNullable(command.Metadata.Publisher), Optional.FromNullable(command.Metadata.PageCount) ); - if (metadataResult.IsError) + if (metadataResult.IsFailure) return metadataResult.Errors; - ErrorOr createBookResult = Book.Create( + Result createBookResult = Book.Create( LibraryId.Create(command.LibraryId), command.Path, metadataResult.Value, @@ -168,13 +168,13 @@ public class AddBookCommandHandler : ICommandHandler(); BookEntity persistenceBook = createBookResult.Value.ToRepositoryEntity(); - ErrorOr insertBookResult = await bookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false); - if (insertBookResult.IsError) + Result insertBookResult = await bookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false); + if (insertBookResult.IsFailure) return insertBookResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs index 54147686..78df6434 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs @@ -2,7 +2,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; #endregion namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs index 078a3d42..1fecb892 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.Books; @@ -16,7 +16,7 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar /// /// Handler for the query to get all books. /// -public class GetBooksQueryHandler : IQueryHandler>> +public class GetBooksQueryHandler : IQueryHandler>> { private readonly IUnitOfWork _unitOfWork; @@ -35,14 +35,14 @@ public class GetBooksQueryHandler : IQueryHandlerThe query to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a collection of , or an error message. + /// An containing either a collection of , or an error message. /// - public async Task>> HandleAsync(GetBooksQuery query, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetBooksQuery query, CancellationToken cancellationToken) { // get a books repository IBookRepository bookRepository = _unitOfWork.GetRepository(); // get all books of the media library from the book repository - ErrorOr> getBooksResult = await bookRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); - return getBooksResult.Match(result => ErrorOrFactory.From(getBooksResult.Value.ToResponses()), errors => errors); + Result> getBooksResult = await bookRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); + return getBooksResult.Match(result => Result.From(getBooksResult.Value.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs index d1fb76bd..5ef6f702 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; @@ -17,7 +17,7 @@ namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProvide /// /// Handler for the command to reorder the metadata providers of a media library. /// -public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler> +public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IValidator _validator; @@ -39,17 +39,17 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An representing either a successful operation, or an error. + /// An representing either a successful operation, or an error. /// - public async Task> HandleAsync(ReorderLibraryMetadataProvidersCommand command, CancellationToken cancellationToken) + public async Task> HandleAsync(ReorderLibraryMetadataProvidersCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) return validationResult; ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository(); - ErrorOr> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); - if (getConfigurationsResult.IsError) + Result> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; Dictionary configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId); @@ -59,8 +59,8 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler upsertResult = await configurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); - if (upsertResult.IsError) + Result upsertResult = await configurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) return upsertResult.Errors; } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs index 73e9e473..1a9fd05c 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; #endregion namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs index 28ba686c..8f52da04 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; @@ -17,7 +17,7 @@ namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEna /// /// Handler for the command to enable or disable a metadata provider for a media library. /// -public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler> +public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IValidator _validator; @@ -39,17 +39,17 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An representing either a successful operation, or an error. + /// An representing either a successful operation, or an error. /// - public async Task> HandleAsync(SetLibraryMetadataProviderEnabledCommand command, CancellationToken cancellationToken) + public async Task> HandleAsync(SetLibraryMetadataProviderEnabledCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) return validationResult; ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository(); - ErrorOr getConfigurationResult = await configurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); - if (getConfigurationResult.IsError) + Result getConfigurationResult = await configurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); + if (getConfigurationResult.IsFailure) return getConfigurationResult.Errors; LibraryMetadataProviderConfigurationEntity configuration; @@ -61,8 +61,8 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); - if (getConfigurationsResult.IsError) + Result> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1; configuration = new LibraryMetadataProviderConfigurationEntity @@ -78,8 +78,8 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler upsertResult = await configurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); - if (upsertResult.IsError) + Result upsertResult = await configurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) return upsertResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return Result.Success; diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs index f9faf160..f631bc44 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; #endregion namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; diff --git a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs index 47d0e63b..a2f23f25 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; @@ -15,7 +15,7 @@ namespace Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; /// /// Handler for the command to update the settings of a plugin. /// -public class UpdatePluginSettingsCommandHandler : ICommandHandler> +public class UpdatePluginSettingsCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IValidator _validator; @@ -37,9 +37,9 @@ public class UpdatePluginSettingsCommandHandler : ICommandHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An representing either a successful operation, or an error. + /// An representing either a successful operation, or an error. /// - public async Task> HandleAsync(UpdatePluginSettingsCommand command, CancellationToken cancellationToken) + public async Task> HandleAsync(UpdatePluginSettingsCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) @@ -47,8 +47,8 @@ public class UpdatePluginSettingsCommandHandler : ICommandHandler(); string? settingsJson = command.Settings is not null ? JsonSerializer.Serialize(command.Settings) : null; - ErrorOr updateResult = await pluginRepository.UpdateSettingsAsync(command.PluginId, settingsJson, cancellationToken).ConfigureAwait(false); - if (updateResult.IsError) + Result updateResult = await pluginRepository.UpdateSettingsAsync(command.PluginId, settingsJson, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) return updateResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return Result.Success; diff --git a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs index aca3fa33..283e4bf5 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; #endregion namespace Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs index 367fabef..c8cee410 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; @@ -18,7 +18,7 @@ namespace Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; /// /// Handler for the query to get the metadata providers configured for a media library. /// -public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler>> +public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler>> { private readonly IUnitOfWork _unitOfWork; @@ -37,19 +37,19 @@ public class GetLibraryMetadataProvidersQueryHandler : IQueryHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a collection of , or an error. + /// An containing either a collection of , or an error. /// - public async Task>> HandleAsync(GetLibraryMetadataProvidersQuery query, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetLibraryMetadataProvidersQuery query, CancellationToken cancellationToken) { ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository(); - ErrorOr> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); - if (getConfigurationsResult.IsError) + Result> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; // build a plugin name lookup from the detected plugins IPluginRepository pluginRepository = _unitOfWork.GetRepository(); - ErrorOr> getPluginsResult = await pluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); - if (getPluginsResult.IsError) + Result> getPluginsResult = await pluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getPluginsResult.IsFailure) return getPluginsResult.Errors; Dictionary pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs index 50a85128..91941e01 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; @@ -7,7 +7,7 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Common.Mapping.Plugins; using Lumina.Contracts.Responses.Plugins; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Plugins.Contracts.Core.Plugins; using System.Collections.Generic; using System.Linq; @@ -20,7 +20,7 @@ namespace Lumina.Application.Core.Plugins.Queries.GetPluginSettings; /// /// Handler for the query to get the settings of a plugin and their schema. /// -public class GetPluginSettingsQueryHandler : IQueryHandler> +public class GetPluginSettingsQueryHandler : IQueryHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IPluginManager _pluginManager; @@ -42,13 +42,13 @@ public class GetPluginSettingsQueryHandler : IQueryHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a , or an error. + /// An containing either a , or an error. /// - public async Task> HandleAsync(GetPluginSettingsQuery query, CancellationToken cancellationToken) + public async Task> HandleAsync(GetPluginSettingsQuery query, CancellationToken cancellationToken) { IPluginRepository pluginRepository = _unitOfWork.GetRepository(); - ErrorOr getPluginResult = await pluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false); - if (getPluginResult.IsError) + Result getPluginResult = await pluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false); + if (getPluginResult.IsFailure) return getPluginResult.Errors; PluginEntity? pluginEntity = getPluginResult.Value; if (pluginEntity is null) diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs index 50777d81..4bc6e340 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; @@ -17,7 +17,7 @@ namespace Lumina.Application.Core.Plugins.Queries.GetPlugins; /// /// Handler for the query to get all the detected plugins. /// -public class GetPluginsQueryHandler : IQueryHandler>> +public class GetPluginsQueryHandler : IQueryHandler>> { private readonly IUnitOfWork _unitOfWork; @@ -36,14 +36,14 @@ public class GetPluginsQueryHandler : IQueryHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a collection of , or an error. + /// An containing either a collection of , or an error. /// - public async Task>> HandleAsync(GetPluginsQuery query, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetPluginsQuery query, CancellationToken cancellationToken) { IPluginRepository pluginRepository = _unitOfWork.GetRepository(); - ErrorOr> getPluginsResult = await pluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getPluginsResult = await pluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); return getPluginsResult.Match( - plugins => ErrorOrFactory.From>(plugins.Select(plugin => plugin.ToResponse()).ToList()), + plugins => Result.From>(plugins.Select(plugin => plugin.ToResponse()).ToList()), errors => errors); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs index 2ce0efcc..0304d7cf 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; @@ -19,7 +19,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Change /// /// Handler for the command to change the password of a user account. /// -public class ChangePasswordCommandHandler : ICommandHandler> +public class ChangePasswordCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IPasswordHashService _hashService; @@ -47,17 +47,17 @@ public class ChangePasswordCommandHandler : ICommandHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public async Task> HandleAsync(ChangePasswordCommand command, CancellationToken cancellationToken) + public async Task> HandleAsync(ChangePasswordCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) return validationResult; IUserRepository userRepository = _unitOfWork.GetRepository(); - ErrorOr getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); - if (getUserResult.IsError) + Result getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.UsernameDoesNotExist; @@ -69,8 +69,8 @@ public class ChangePasswordCommandHandler : ICommandHandler updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false); - if (updateUserResult.IsError) + Result updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false); + if (updateUserResult.IsFailure) return updateUserResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return new ChangePasswordResponse(true); diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs index dea38d92..98c1626c 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; @@ -20,7 +20,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Recove /// /// Handler for the command to recover the password of an account. /// -public class RecoverPasswordCommandHandler : ICommandHandler> +public class RecoverPasswordCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IPasswordHashService _hashService; @@ -56,9 +56,9 @@ public class RecoverPasswordCommandHandler : ICommandHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public async Task> HandleAsync(RecoverPasswordCommand command, CancellationToken cancellationToken) + public async Task> HandleAsync(RecoverPasswordCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) @@ -66,8 +66,8 @@ public class RecoverPasswordCommandHandler : ICommandHandler(); - ErrorOr getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); - if (getUserResult.IsError) + Result getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.UsernameDoesNotExist; @@ -86,8 +86,8 @@ public class RecoverPasswordCommandHandler : ICommandHandler updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false); - if (updateUserResult.IsError) + Result updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false); + if (updateUserResult.IsFailure) return updateUserResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return new RecoverPasswordResponse(true); diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs index b501be28..be45419c 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; @@ -21,7 +21,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Regist /// /// Handler for the command to register a new user account. /// -public class RegisterUserCommandHandler : ICommandHandler> +public class RegisterUserCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IPasswordHashService _hashService; @@ -65,9 +65,9 @@ public class RegisterUserCommandHandler : ICommandHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public async Task> HandleAsync(RegisterUserCommand command, CancellationToken cancellationToken) + public async Task> HandleAsync(RegisterUserCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) @@ -75,8 +75,8 @@ public class RegisterUserCommandHandler : ICommandHandler(); - ErrorOr getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); - if (getUserResult.IsError) + Result getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is not null) return Errors.Authentication.UsernameAlreadyExists; @@ -105,8 +105,8 @@ public class RegisterUserCommandHandler : ICommandHandler insertUserResult = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); - if (insertUserResult.IsError) + Result insertUserResult = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); + if (insertUserResult.IsFailure) return insertUserResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // TODO: insert the default admin profile preferences when they are implemented diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs index 7b20ba85..5cede5a5 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; @@ -20,7 +20,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUser /// /// Handler for the query to retrieve the list of users. /// -public class GetUsersQueryHandler : IQueryHandler>> +public class GetUsersQueryHandler : IQueryHandler>> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; @@ -45,15 +45,15 @@ public class GetUsersQueryHandler : IQueryHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a collection of , or an error message. + /// An containing either a collection of , or an error message. /// - public async Task>> HandleAsync(GetUsersQuery query, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetUsersQuery query, CancellationToken cancellationToken) { // only admins can see the list of users bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; - ErrorOr> getRolesResult = await _userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); - return getRolesResult.Match(value => ErrorOrFactory.From(value.ToResponses()), errors => errors); + Result> getRolesResult = await _userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + return getRolesResult.Match(value => Result.From(value.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs index 3db02cfe..cdabc541 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; @@ -21,7 +21,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUs /// /// Handler for the query to authenticate an account. /// -public class LoginUserQueryHandler : IQueryHandler> +public class LoginUserQueryHandler : IQueryHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IPasswordHashService _hashService; @@ -65,9 +65,9 @@ public class LoginUserQueryHandler : IQueryHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public async Task> HandleAsync(LoginUserQuery query, CancellationToken cancellationToken) + public async Task> HandleAsync(LoginUserQuery query, CancellationToken cancellationToken) { List validationResult = _validator.Validate(query); if (validationResult.Count > 0) @@ -75,8 +75,8 @@ public class LoginUserQueryHandler : IQueryHandler(); - ErrorOr getUserResult = await userRepository.GetByUsernameAsync(query.Username!, cancellationToken).ConfigureAwait(false); - if (getUserResult.IsError) + Result getUserResult = await userRepository.GetByUsernameAsync(query.Username!, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.InvalidUsernameOrPassword; diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs index 4c7899ef..a49145cc 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; @@ -16,7 +16,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; @@ -24,7 +24,7 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateU /// /// Handler for the command to update an authorization role. /// -public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler> +public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IAuthorizationService _authorizationService; @@ -52,9 +52,9 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully updated , or an error message. + /// An containing either a successfully updated , or an error message. /// - public async Task> HandleAsync(UpdateUserRoleAndPermissionsCommand command, CancellationToken cancellationToken) + public async Task> HandleAsync(UpdateUserRoleAndPermissionsCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) @@ -71,24 +71,24 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler(); // get the user to update - ErrorOr getUserResult = await userRepository.GetByIdAsync(command.UserId, cancellationToken).ConfigureAwait(false); - if (getUserResult.IsError || getUserResult.Value is null) + Result getUserResult = await userRepository.GetByIdAsync(command.UserId, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsFailure || getUserResult.Value is null) return DomainErrors.Users.UserDoesNotExist; - ErrorOr getRoleResult = default; + Result getRoleResult = default; if (command.RoleId is not null) { // get the new role getRoleResult = await roleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken).ConfigureAwait(false); - if (getRoleResult.IsError || getRoleResult.Value is null) + if (getRoleResult.IsFailure || getRoleResult.Value is null) return ApplicationErrors.Authorization.RoleNotFound; // check if we're changing an admin's role and if this would leave us without admins if (getUserResult.Value.UserRole?.Role.RoleName == "Admin" && getRoleResult.Value.RoleName != "Admin") { // count how many admins we have - ErrorOr> getAllUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); - if (getAllUsersResult.IsError) + Result> getAllUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getAllUsersResult.IsFailure) return getAllUsersResult.Errors; int adminCount = getAllUsersResult.Value.Count(user => user.UserRole?.Role.RoleName == "Admin"); @@ -97,9 +97,9 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler> getPermissionsResult = + Result> getPermissionsResult = await permissionRepository.GetByIdsAsync(command.Permissions, cancellationToken).ConfigureAwait(false); - if (getPermissionsResult.IsError) + if (getPermissionsResult.IsFailure) return getPermissionsResult.Errors; // update the user @@ -138,8 +138,8 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler updateResult = await userRepository.UpdateAsync(updatedUser, cancellationToken).ConfigureAwait(false); - if (updateResult.IsError) + Result updateResult = await userRepository.UpdateAsync(updatedUser, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) return updateResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidator.cs index d1d2491d..6798fc77 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidator.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidator.cs @@ -3,7 +3,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; using System; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs index 6e4ea133..068054d1 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.Errors; @@ -19,7 +19,7 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAutho /// /// Handler for the query to retrieve the authorization roles and permissions of an account. /// -public class GetAuthorizationQueryHandler : IQueryHandler> +public class GetAuthorizationQueryHandler : IQueryHandler> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; @@ -44,9 +44,9 @@ public class GetAuthorizationQueryHandler : IQueryHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a , or an error message. + /// An containing either a , or an error message. /// - public async Task> HandleAsync(GetAuthorizationQuery query, CancellationToken cancellationToken) + public async Task> HandleAsync(GetAuthorizationQuery query, CancellationToken cancellationToken) { List validationResult = _validator.Validate(query); if (validationResult.Count > 0) @@ -56,14 +56,14 @@ public class GetAuthorizationQueryHandler : IQueryHandler getCurrentUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(_currentUserService.UserId!.Value, cancellationToken).ConfigureAwait(false); - if (getCurrentUserPermissionResult.IsError) + Result getCurrentUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(_currentUserService.UserId!.Value, cancellationToken).ConfigureAwait(false); + if (getCurrentUserPermissionResult.IsFailure) return getCurrentUserPermissionResult.Errors; // if the current user is not an Admin, and the account for whom they request the permissions list is not theirs, deny the request if (getCurrentUserPermissionResult.Value.Role != "Admin") return Errors.Authorization.NotAuthorized; } - ErrorOr getUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); - return getUserPermissionResult.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors); + Result getUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); + return getUserPermissionResult.Match(value => Result.From(value.ToResponse()), errors => errors); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidator.cs index 7633da55..8eba2012 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidator.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using System; #endregion diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs index fad8a25c..1e8c61b9 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; @@ -21,7 +21,7 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserP /// /// Handler for the query to retrieve the authorization permissions of a user. /// -public class GetUserPermissionsQueryHandler : IQueryHandler>> +public class GetUserPermissionsQueryHandler : IQueryHandler>> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; @@ -49,9 +49,9 @@ public class GetUserPermissionsQueryHandler : IQueryHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a collection of , or an error message. + /// An containing either a collection of , or an error message. /// - public async Task>> HandleAsync(GetUserPermissionsQuery query, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetUserPermissionsQuery query, CancellationToken cancellationToken) { List validationResult = _validator.Validate(query); if (validationResult.Count > 0) @@ -62,11 +62,11 @@ public class GetUserPermissionsQueryHandler : IQueryHandler getUserResult = await _userRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); - if (getUserResult.IsError) + Result getUserResult = await _userRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.UsernameDoesNotExist; - return ErrorOrFactory.From(getUserResult.Value.UserPermissions.Select(userPermission => userPermission.Permission).ToResponses()); + return Result.From(getUserResult.Value.UserPermissions.Select(userPermission => userPermission.Permission).ToResponses()); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidator.cs index 83f30db7..dadcd455 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidator.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using System; #endregion diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs index 197a6c68..992f1d71 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; @@ -20,7 +20,7 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserR /// /// Handler for the query to retrieve the authorization role of a user. /// -public class GetUserRoleQueryHandler : IQueryHandler> +public class GetUserRoleQueryHandler : IQueryHandler> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; @@ -48,9 +48,9 @@ public class GetUserRoleQueryHandler : IQueryHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a , or an error message. + /// An containing either a , or an error message. /// - public async Task> HandleAsync(GetUserRoleQuery query, CancellationToken cancellationToken) + public async Task> HandleAsync(GetUserRoleQuery query, CancellationToken cancellationToken) { List validationResult = _validator.Validate(query); if (validationResult.Count > 0) @@ -61,11 +61,11 @@ public class GetUserRoleQueryHandler : IQueryHandler getUserResult = await _userRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); - if (getUserResult.IsError) + Result getUserResult = await _userRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.UsernameDoesNotExist; - return ErrorOrFactory.From(getUserResult.Value.UserRole?.Role.ToResponse()); + return Result.From(getUserResult.Value.UserRole?.Role.ToResponse()); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidator.cs index eaad5f25..b237326c 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidator.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidator.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using System; #endregion diff --git a/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs index 6a8b0058..26a77760 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.Errors; @@ -35,8 +35,8 @@ internal sealed class PermissionRepository : IPermissionRepository /// /// The authorization permission to add. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> InsertAsync(PermissionEntity permission, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> InsertAsync(PermissionEntity permission, CancellationToken cancellationToken) { bool permissionExists = await _luminaDbContext.Permissions.AnyAsync(repositoryPermission => repositoryPermission.Id == permission.Id, cancellationToken).ConfigureAwait(false); if (permissionExists) @@ -50,8 +50,8 @@ internal sealed class PermissionRepository : IPermissionRepository /// Gets all autorization permissions. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a collection of , or an error. + public async Task>> GetAllAsync(CancellationToken cancellationToken) { return await _luminaDbContext.Permissions.ToListAsync(cancellationToken).ConfigureAwait(false); } @@ -61,8 +61,8 @@ internal sealed class PermissionRepository : IPermissionRepository /// /// The list of Ids of the permissions to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetByIdsAsync(IEnumerable ids, CancellationToken cancellationToken) + /// An containing either a collection of , or an error. + public async Task>> GetByIdsAsync(IEnumerable ids, CancellationToken cancellationToken) { return await _luminaDbContext.Permissions.Where(permission => ids.Contains(permission.Id)).ToListAsync(cancellationToken).ConfigureAwait(false); } diff --git a/src/Lumina.DataAccess/Core/Repositories/Authorization/RolePermissionRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Authorization/RolePermissionRepository.cs index ef14416c..e607176d 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Authorization/RolePermissionRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Authorization/RolePermissionRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.DataAccess.Core.UoW; @@ -30,10 +30,10 @@ internal sealed class RolePermissionRepository : IRolePermissionRepository /// /// The authorization role permission to add. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public Task> InsertAsync(RolePermissionEntity rolePermission, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public Task> InsertAsync(RolePermissionEntity rolePermission, CancellationToken cancellationToken) { _luminaDbContext.RolePermissions.Add(rolePermission); - return Task.FromResult(ErrorOrFactory.From(Result.Created)); + return Task.FromResult(Result.From(Result.Created)); } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs index 98259a9e..cbf17889 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.Errors; @@ -34,8 +34,8 @@ internal sealed class RoleRepository : IRoleRepository /// /// The authorization role to add. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> InsertAsync(RoleEntity role, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> InsertAsync(RoleEntity role, CancellationToken cancellationToken) { bool roleExists = await _luminaDbContext.Roles.AnyAsync(repositoryRole => repositoryRole.Id == role.Id || repositoryRole.RoleName == role.RoleName, cancellationToken).ConfigureAwait(false); if (roleExists) @@ -49,8 +49,8 @@ internal sealed class RoleRepository : IRoleRepository /// Gets all autorization roles. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a collection of , or an error. + public async Task>> GetAllAsync(CancellationToken cancellationToken) { return await _luminaDbContext.Roles.ToListAsync(cancellationToken).ConfigureAwait(false); } @@ -60,8 +60,8 @@ internal sealed class RoleRepository : IRoleRepository /// /// The type of role to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a if found, or an error. - public async Task> GetByNameAsync(string roleType, CancellationToken cancellationToken) + /// An containing either a if found, or an error. + public async Task> GetByNameAsync(string roleType, CancellationToken cancellationToken) { return await _luminaDbContext.Roles .Include(role => role.RolePermissions) @@ -75,8 +75,8 @@ internal sealed class RoleRepository : IRoleRepository /// /// The id of the authorization role to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + /// An containing either a identified by , or an error. + public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) { return await _luminaDbContext.Roles .Include(role => role.RolePermissions) @@ -90,8 +90,8 @@ internal sealed class RoleRepository : IRoleRepository /// /// The role to update. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> UpdateAsync(RoleEntity data, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> UpdateAsync(RoleEntity data, CancellationToken cancellationToken) { // check if a role with the requested Id exists, and retrieve it RoleEntity? foundRole = await _luminaDbContext.Roles @@ -114,8 +114,8 @@ internal sealed class RoleRepository : IRoleRepository /// /// The id of the role to be deleted. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) { // check if a role with the requested Id exists, and retrieve it RoleEntity? foundRole = await _luminaDbContext.Roles diff --git a/src/Lumina.DataAccess/Core/Repositories/Authorization/UserRoleRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Authorization/UserRoleRepository.cs index ea895071..096db7ba 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Authorization/UserRoleRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Authorization/UserRoleRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.DataAccess.Core.UoW; @@ -30,10 +30,10 @@ internal sealed class UserRoleRepository : IUserRoleRepository /// /// The authorization user role to add. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public Task> InsertAsync(UserRoleEntity userRole, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public Task> InsertAsync(UserRoleEntity userRole, CancellationToken cancellationToken) { _luminaDbContext.UserRoles.Add(userRole); - return Task.FromResult(ErrorOrFactory.From(Result.Created)); + return Task.FromResult(Result.From(Result.Created)); } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs index 7f577a6e..f9ef8b27 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; @@ -37,8 +37,8 @@ internal sealed class BookRepository : IBookRepository /// /// The book to add. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> InsertAsync(BookEntity book, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> InsertAsync(BookEntity book, CancellationToken cancellationToken) { bool bookExists = await _luminaDbContext.Books.AnyAsync(repositoryBook => repositoryBook.Id == book.Id, cancellationToken: cancellationToken).ConfigureAwait(false); if (bookExists) @@ -66,8 +66,8 @@ internal sealed class BookRepository : IBookRepository /// /// The Id of the book to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + /// An containing either a , or an error. + public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) { return await _luminaDbContext.Books .Include(book => book.Tags) @@ -80,8 +80,8 @@ internal sealed class BookRepository : IBookRepository /// Gets all books. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a collection of , or an error. + public async Task>> GetAllAsync(CancellationToken cancellationToken) { return await _luminaDbContext.Books .Include(book => book.Tags) @@ -95,8 +95,8 @@ internal sealed class BookRepository : IBookRepository /// /// The Id of the media library whose books are retrieved. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + /// An containing either a collection of , or an error. + public async Task>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) { return await _luminaDbContext.Books .Include(book => book.Tags) @@ -112,8 +112,8 @@ internal sealed class BookRepository : IBookRepository /// The Id of the media library whose book is retrieved. /// The file system path of the book to be retrieved. /// Cancellation token that can be used to stop the execution. - /// An containing either the stored at the provided path, or an error. - public async Task> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken) + /// An containing either the stored at the provided path, or an error. + public async Task> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken) { return await _luminaDbContext.Books .Include(book => book.Tags) @@ -130,8 +130,8 @@ internal sealed class BookRepository : IBookRepository /// The path of the last retrieved book, used for keyset pagination. Pass to get the first page. /// The maximum number of books to retrieve. /// Cancellation token that can be used to stop the execution. - /// An containing either a page of books needing their metadata enriched, or an error. - public async Task>> GetBooksNeedingMetadataAsync(Guid libraryId, string? lastPath, int pageSize, CancellationToken cancellationToken) + /// An containing either a page of books needing their metadata enriched, or an error. + public async Task>> GetBooksNeedingMetadataAsync(Guid libraryId, string? lastPath, int pageSize, CancellationToken cancellationToken) { return await _luminaDbContext.Books .Include(book => book.Tags) @@ -150,8 +150,8 @@ internal sealed class BookRepository : IBookRepository /// /// The Id of the media library whose books are counted. /// Cancellation token that can be used to stop the execution. - /// An containing either the number of books needing their metadata enriched, or an error. - public async Task> GetBooksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken) + /// An containing either the number of books needing their metadata enriched, or an error. + public async Task> GetBooksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken) { return await _luminaDbContext.Books .CountAsync(book => book.LibraryId == libraryId && book.MetadataStatus != MetadataStatus.Enriched, cancellationToken).ConfigureAwait(false); @@ -162,8 +162,8 @@ internal sealed class BookRepository : IBookRepository /// /// The book to update. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> UpdateAsync(BookEntity data, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> UpdateAsync(BookEntity data, CancellationToken cancellationToken) { BookEntity? foundBook = await _luminaDbContext.Books .Include(book => book.Tags) diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/DirectoryScanFingerprintRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/DirectoryScanFingerprintRepository.cs index d4e67b16..1a45a198 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/DirectoryScanFingerprintRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/DirectoryScanFingerprintRepository.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Dapper; -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.DataAccess.Core.UoW; @@ -39,8 +39,8 @@ internal sealed class DirectoryScanFingerprintRepository : IDirectoryScanFingerp /// /// The unique identifier of the library for which to get the directory scan fingerprints. /// Cancellation token that can be used to stop the execution. - /// An containing either a path mapped dictionary of directory scan fingerprints, or an error. - public async Task>> GetMappedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + /// An containing either a path mapped dictionary of directory scan fingerprints, or an error. + public async Task>> GetMappedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) { await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false); const string GET_FINGERPRINTS_SQL = """ @@ -60,8 +60,8 @@ internal sealed class DirectoryScanFingerprintRepository : IDirectoryScanFingerp /// /// The directory scan fingerprints to insert or update. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> UpsertRangeAsync(IReadOnlyCollection entities, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> UpsertRangeAsync(IReadOnlyCollection entities, CancellationToken cancellationToken) { // nothing to upsert for an empty collection if (entities.Count == 0) diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs index 24adfb21..43b63d9e 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; @@ -35,8 +35,8 @@ internal sealed class LibraryRepository : ILibraryRepository /// /// The library to add. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> InsertAsync(LibraryEntity library, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> InsertAsync(LibraryEntity library, CancellationToken cancellationToken) { bool libraryExists = await _luminaDbContext.Libraries.AnyAsync(repositoryLibrary => repositoryLibrary.Id == library.Id, cancellationToken: cancellationToken).ConfigureAwait(false); if (libraryExists) @@ -51,8 +51,8 @@ internal sealed class LibraryRepository : ILibraryRepository /// /// The Id of the library to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + /// An containing either a identified by , or an error. + public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) { return await _luminaDbContext.Libraries .Include(library => library.ContentLocations) @@ -63,8 +63,8 @@ internal sealed class LibraryRepository : ILibraryRepository /// Gets all media libraries that are marked as enabled, from the storage medium. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllEnabledAsync(CancellationToken cancellationToken) + /// An containing either a collection of , or an error. + public async Task>> GetAllEnabledAsync(CancellationToken cancellationToken) { return await _luminaDbContext.Libraries .Include(library => library.ContentLocations) @@ -76,8 +76,8 @@ internal sealed class LibraryRepository : ILibraryRepository /// Gets all media libraries that are marked as enabled and unlocked, from the storage medium. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllEnabledAndUnlockedAsync(CancellationToken cancellationToken) + /// An containing either a collection of , or an error. + public async Task>> GetAllEnabledAndUnlockedAsync(CancellationToken cancellationToken) { return await _luminaDbContext.Libraries .Include(library => library.ContentLocations) @@ -89,8 +89,8 @@ internal sealed class LibraryRepository : ILibraryRepository /// Gets all media libraries. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a collection of , or an error. + public async Task>> GetAllAsync(CancellationToken cancellationToken) { return await _luminaDbContext.Libraries .Include(library => library.ContentLocations) @@ -102,8 +102,8 @@ internal sealed class LibraryRepository : ILibraryRepository /// /// The media library to update. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> UpdateAsync(LibraryEntity data, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> UpdateAsync(LibraryEntity data, CancellationToken cancellationToken) { LibraryEntity? foundLibrary = await _luminaDbContext.Libraries .Include(library => library.ContentLocations) @@ -124,8 +124,8 @@ internal sealed class LibraryRepository : ILibraryRepository /// /// The Id of the library to delete. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) { LibraryEntity? library = await _luminaDbContext.Libraries .Include(library => library.ContentLocations) diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs index 032609e3..6e072148 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; @@ -36,8 +36,8 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository /// /// The library scan to add. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> InsertAsync(LibraryScanEntity libraryScan, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> InsertAsync(LibraryScanEntity libraryScan, CancellationToken cancellationToken) { bool libraryScanExists = await _luminaDbContext.LibraryScans.AnyAsync( repositoryScanLibrary => repositoryScanLibrary.Id == libraryScan.Id, cancellationToken: cancellationToken).ConfigureAwait(false); @@ -53,8 +53,8 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository /// /// The id of the library scan to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + /// An containing either a identified by , or an error. + public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) { return await _luminaDbContext.LibraryScans .Include(libraryScan => libraryScan.Library) @@ -66,8 +66,8 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository /// Gets the media library scans that belong to a media library identified by , for the previous month, from the storage medium. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetPastMonthScansByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + /// An containing either a collection of , or an error. + public async Task>> GetPastMonthScansByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) { return await _luminaDbContext.LibraryScans .Include(library => library.Library) @@ -79,8 +79,8 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository /// Gets the media library scans that have a status, from the storage medium. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetRunningScansAsync(CancellationToken cancellationToken) + /// An containing either a collection of , or an error. + public async Task>> GetRunningScansAsync(CancellationToken cancellationToken) { return await _luminaDbContext.LibraryScans .Include(library => library.Library) @@ -93,8 +93,8 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository /// /// The media library scan to update. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> UpdateAsync(LibraryScanEntity data, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> UpdateAsync(LibraryScanEntity data, CancellationToken cancellationToken) { LibraryScanEntity? foundLibraryScan = await _luminaDbContext.LibraryScans .Include(libraryScan => libraryScan.Library) diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanResultRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanResultRepository.cs index 38b16f7e..f487c9d8 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanResultRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanResultRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.DataAccess.Core.UoW; @@ -30,10 +30,10 @@ internal sealed class LibraryScanResultRepository : ILibraryScanResultRepository /// /// The library scan result to add. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public Task> InsertAsync(LibraryScanResultEntity libraryScan, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public Task> InsertAsync(LibraryScanResultEntity libraryScan, CancellationToken cancellationToken) { _luminaDbContext.LibraryScanResults.Add(libraryScan); - return Task.FromResult(ErrorOrFactory.From(Result.Created)); + return Task.FromResult(Result.From(Result.Created)); } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanSnapshotRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanSnapshotRepository.cs index a0222fba..4652c2d3 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanSnapshotRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanSnapshotRepository.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Dapper; -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.DataAccess.Core.UoW; using Microsoft.Data.Sqlite; @@ -42,8 +42,8 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi /// The unique identifier of the library for which to get the deleted media library scan snapshot item paths. /// The unique identifier of the media library scan for which to determine the deleted media library scan snapshot item paths. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of deleted media library scan snapshot item paths, or an error. - public async Task>> GetDeletedPathsAsync(Guid libraryId, Guid scanId, CancellationToken cancellationToken) + /// An containing either a collection of deleted media library scan snapshot item paths, or an error. + public async Task>> GetDeletedPathsAsync(Guid libraryId, Guid scanId, CancellationToken cancellationToken) { await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false); const string GET_DELETED_PATHS_SQL = """ @@ -69,8 +69,8 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi /// /// The unique identifier of the library whose media library scan snapshot item paths are retrieved. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of media library scan snapshot item paths, or an error. - public async Task>> GetPathsAsync(Guid libraryId, CancellationToken cancellationToken) + /// An containing either a collection of media library scan snapshot item paths, or an error. + public async Task>> GetPathsAsync(Guid libraryId, CancellationToken cancellationToken) { await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false); const string GET_PATHS_SQL = """ @@ -94,8 +94,8 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi /// The unique identifier of the media library scan whose results are applied. /// The unique identifier of the user that initiated the media library scan, used for audit purposes. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> ApplySnapshotSwapAsync(Guid libraryId, Guid scanId, Guid userId, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> ApplySnapshotSwapAsync(Guid libraryId, Guid scanId, Guid userId, CancellationToken cancellationToken) { await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false); await using DbTransaction transaction = await connection.BeginTransactionAsync(cancellationToken); diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanStagingResultsRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanStagingResultsRepository.cs index c53b1739..661f9452 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanStagingResultsRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanStagingResultsRepository.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Dapper; -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads; @@ -40,8 +40,8 @@ internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingR /// /// The media library scan staging results to add. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> InsertRangeAsync(IReadOnlyCollection entities, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> InsertRangeAsync(IReadOnlyCollection entities, CancellationToken cancellationToken) { // nothing to insert for an empty collection if (entities.Count == 0) @@ -69,8 +69,8 @@ internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingR /// The unique identifier of the media library scan whose staging results are marked. /// The unique identifier of the library whose media library scan snapshot is compared against. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> MarkChangesAgainstSnapshotAsync(Guid scanId, Guid libraryId, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> MarkChangesAgainstSnapshotAsync(Guid scanId, Guid libraryId, CancellationToken cancellationToken) { await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false); // compare the discovered file system items against the media library scan snapshot of the previous scan, entirely in the database, so that the snapshot never needs to be loaded into memory: @@ -102,8 +102,8 @@ internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingR /// /// The unique identifier of the media library scan whose staging results are counted. /// Cancellation token that can be used to stop the execution. - /// An containing either the number of staging results that need hashing, or an error. - public async Task> GetFilesToHashCountAsync(Guid scanId, CancellationToken cancellationToken) + /// An containing either the number of staging results that need hashing, or an error. + public async Task> GetFilesToHashCountAsync(Guid scanId, CancellationToken cancellationToken) { await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false); const string GET_FILES_TO_HASH_COUNT_SQL = """ @@ -125,8 +125,8 @@ internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingR /// The path of the last retrieved file system item, used for keyset pagination. Pass to get the first page. /// The maximum number of staging results to retrieve. /// Cancellation token that can be used to stop the execution. - /// An containing either a page of staging results that need hashing, or an error. - public async Task>> GetFilesToHashPageAsync(Guid scanId, string? lastPath, int pageSize, CancellationToken cancellationToken) + /// An containing either a page of staging results that need hashing, or an error. + public async Task>> GetFilesToHashPageAsync(Guid scanId, string? lastPath, int pageSize, CancellationToken cancellationToken) { await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false); const string GET_FILES_TO_HASH_SQL = """ @@ -151,8 +151,8 @@ internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingR /// The unique identifier of the media library scan whose staging results are updated. /// The file system items whose content hashes are updated. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> UpdateFileHashesAsync(Guid scanId, IReadOnlyCollection hashedFiles, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> UpdateFileHashesAsync(Guid scanId, IReadOnlyCollection hashedFiles, CancellationToken cancellationToken) { await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false); await using DbTransaction transaction = await connection.BeginTransactionAsync(cancellationToken); @@ -179,8 +179,8 @@ internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingR /// /// The unique identifier of the media library scan whose staging results are cleared. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> ClearForScanAsync(Guid scanId, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> ClearForScanAsync(Guid scanId, CancellationToken cancellationToken) { await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false); const string CLEAR_SQL = "DELETE FROM LibraryScanStagingResults WHERE LibraryScanId = @scanId;"; diff --git a/src/Lumina.DataAccess/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepository.cs index 535bb317..ab502d5f 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepository.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.DataAccess.Core.UoW; @@ -34,8 +34,8 @@ internal sealed class LibraryMetadataProviderConfigurationRepository : ILibraryM /// /// The Id of the media library whose metadata provider configurations are retrieved. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + /// An containing either a collection of , or an error. + public async Task>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) { return await _luminaDbContext.LibraryMetadataProviderConfigurations .Where(configuration => configuration.LibraryId == libraryId) @@ -48,8 +48,8 @@ internal sealed class LibraryMetadataProviderConfigurationRepository : ILibraryM /// The Id of the media library whose metadata provider configuration is retrieved. /// The Id of the plugin whose metadata provider configuration is retrieved. /// Cancellation token that can be used to stop the execution. - /// An containing either the , or an error. - public async Task> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken) + /// An containing either the , or an error. + public async Task> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken) { return await _luminaDbContext.LibraryMetadataProviderConfigurations .FirstOrDefaultAsync(configuration => configuration.LibraryId == libraryId && configuration.PluginId == pluginId, cancellationToken).ConfigureAwait(false); @@ -60,8 +60,8 @@ internal sealed class LibraryMetadataProviderConfigurationRepository : ILibraryM /// /// The metadata provider configuration to insert or update. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> UpsertAsync(LibraryMetadataProviderConfigurationEntity configuration, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> UpsertAsync(LibraryMetadataProviderConfigurationEntity configuration, CancellationToken cancellationToken) { LibraryMetadataProviderConfigurationEntity? existingConfiguration = await _luminaDbContext.LibraryMetadataProviderConfigurations .FirstOrDefaultAsync(repositoryConfiguration => repositoryConfiguration.LibraryId == configuration.LibraryId && repositoryConfiguration.PluginId == configuration.PluginId, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs index 167eaeab..4c1a4bd9 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; @@ -34,8 +34,8 @@ internal sealed class PluginRepository : IPluginRepository /// /// The Id of the plugin to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + /// An containing either a , or an error. + public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) { return await _luminaDbContext.Plugins .FirstOrDefaultAsync(plugin => plugin.Id == id, cancellationToken).ConfigureAwait(false); @@ -45,8 +45,8 @@ internal sealed class PluginRepository : IPluginRepository /// Gets all the detected plugins. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a collection of , or an error. + public async Task>> GetAllAsync(CancellationToken cancellationToken) { return await _luminaDbContext.Plugins .ToListAsync(cancellationToken).ConfigureAwait(false); @@ -57,8 +57,8 @@ internal sealed class PluginRepository : IPluginRepository /// /// The plugin to insert or update. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> UpsertAsync(PluginEntity plugin, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> UpsertAsync(PluginEntity plugin, CancellationToken cancellationToken) { PluginEntity? existingPlugin = await _luminaDbContext.Plugins .FirstOrDefaultAsync(repositoryPlugin => repositoryPlugin.Id == plugin.Id, cancellationToken).ConfigureAwait(false); @@ -83,8 +83,8 @@ internal sealed class PluginRepository : IPluginRepository /// The Id of the plugin whose settings are updated. /// The serialized settings of the plugin. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> UpdateSettingsAsync(Guid pluginId, string? settingsJson, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> UpdateSettingsAsync(Guid pluginId, string? settingsJson, CancellationToken cancellationToken) { PluginEntity? existingPlugin = await _luminaDbContext.Plugins .FirstOrDefaultAsync(repositoryPlugin => repositoryPlugin.Id == pluginId, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs index 8da8d1ca..0414b5a9 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; @@ -35,8 +35,8 @@ internal sealed class UserRepository : IUserRepository /// /// The user to add. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> InsertAsync(UserEntity user, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> InsertAsync(UserEntity user, CancellationToken cancellationToken) { bool userExists = await _luminaDbContext.Users.AnyAsync(repositoryUser => repositoryUser.Id == user.Id, cancellationToken: cancellationToken).ConfigureAwait(false); if (userExists) @@ -50,8 +50,8 @@ internal sealed class UserRepository : IUserRepository /// Gets all users. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a collection of , or an error. + public async Task>> GetAllAsync(CancellationToken cancellationToken) { return await _luminaDbContext.Users.ToListAsync(cancellationToken).ConfigureAwait(false); } @@ -61,8 +61,8 @@ internal sealed class UserRepository : IUserRepository /// /// The username of the user to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a if found, or an error. - public async Task> GetByUsernameAsync(string username, CancellationToken cancellationToken) + /// An containing either a if found, or an error. + public async Task> GetByUsernameAsync(string username, CancellationToken cancellationToken) { return await _luminaDbContext.Users .Include(user => user.Libraries) @@ -80,8 +80,8 @@ internal sealed class UserRepository : IUserRepository /// /// Ther user to update. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> UpdateAsync(UserEntity data, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> UpdateAsync(UserEntity data, CancellationToken cancellationToken) { UserEntity? foundUser = await _luminaDbContext.Users .Include(user => user.Libraries) @@ -135,8 +135,8 @@ internal sealed class UserRepository : IUserRepository /// /// The id of the user to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + /// An containing either a identified by , or an error. + public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) { return await _luminaDbContext.Users .Include(user => user.Libraries) diff --git a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs index 022e9db3..0be13ad4 100644 --- a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs +++ b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Authorization; @@ -41,8 +41,8 @@ public class DataSeedService : IDataSeedService /// /// The unique identifier of the admin admin user who will own these permissions. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken) { IPermissionRepository permissionRepository = _unitOfWork.GetRepository(); // create the default authorization permissions and add them to the repository. @@ -55,8 +55,8 @@ public class DataSeedService : IDataSeedService ]; foreach (PermissionEntity permission in defaultPermissions) { - ErrorOr insertPermissionResult = await permissionRepository.InsertAsync(permission, cancellationToken).ConfigureAwait(false); - if (insertPermissionResult.IsError) + Result insertPermissionResult = await permissionRepository.InsertAsync(permission, cancellationToken).ConfigureAwait(false); + if (insertPermissionResult.IsFailure) return insertPermissionResult.Errors; } await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); @@ -68,8 +68,8 @@ public class DataSeedService : IDataSeedService /// /// The unique identifier of the admin user for whom roles will be set. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken) { IRoleRepository roleRepository = _unitOfWork.GetRepository(); @@ -80,8 +80,8 @@ public class DataSeedService : IDataSeedService ]; foreach (RoleEntity role in defaultRoles) { - ErrorOr insertRoleResult = await roleRepository.InsertAsync(role, cancellationToken).ConfigureAwait(false); - if (insertRoleResult.IsError) + Result insertRoleResult = await roleRepository.InsertAsync(role, cancellationToken).ConfigureAwait(false); + if (insertRoleResult.IsFailure) return insertRoleResult.Errors; } await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); @@ -93,24 +93,24 @@ public class DataSeedService : IDataSeedService /// /// The unique identifier of the admin user to receive admin role permissions. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken) { IRolePermissionRepository rolePermissionRepository = _unitOfWork.GetRepository(); IRoleRepository roleRepository = _unitOfWork.GetRepository(); IPermissionRepository permissionRepository = _unitOfWork.GetRepository(); // get the admin role - ErrorOr getAdminRoleResult = await roleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); - if (getAdminRoleResult.IsError) + Result getAdminRoleResult = await roleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); + if (getAdminRoleResult.IsFailure) return getAdminRoleResult.Errors; if (getAdminRoleResult.Value is null) return Errors.Authorization.AdminAccountNotFound; // get all permissions - ErrorOr> getPermissionsResult = await permissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); - if (getPermissionsResult.IsError) + Result> getPermissionsResult = await permissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getPermissionsResult.IsFailure) return getPermissionsResult.Errors; // add each permission to the admin role @@ -125,8 +125,8 @@ public class DataSeedService : IDataSeedService CreatedBy = userId, CreatedOnUtc = _dateTimeProvider.UtcNow }; - ErrorOr insertRolePermissionResult = await rolePermissionRepository.InsertAsync(rolePermissionEntity, cancellationToken).ConfigureAwait(false); - if (insertRolePermissionResult.IsError) + Result insertRolePermissionResult = await rolePermissionRepository.InsertAsync(rolePermissionEntity, cancellationToken).ConfigureAwait(false); + if (insertRolePermissionResult.IsFailure) return insertRolePermissionResult.Errors; } await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); @@ -138,8 +138,8 @@ public class DataSeedService : IDataSeedService /// /// The unique identifier of the admin user to receive the admin role. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken) { IUserRoleRepository userRoleRepository = _unitOfWork.GetRepository(); IRoleRepository roleRepository = _unitOfWork.GetRepository(); @@ -147,16 +147,16 @@ public class DataSeedService : IDataSeedService // get the admin role - ErrorOr getAdminRoleResult = await roleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); - if (getAdminRoleResult.IsError) + Result getAdminRoleResult = await roleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); + if (getAdminRoleResult.IsFailure) return getAdminRoleResult.Errors; if (getAdminRoleResult.Value is null) return Errors.Authorization.AdminRoleNotFound; // get admin user - ErrorOr getUserResult = await userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); - if (getUserResult.IsError) + Result getUserResult = await userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsFailure) return getUserResult.Errors; if (getUserResult.Value is null) @@ -172,8 +172,8 @@ public class DataSeedService : IDataSeedService User = getUserResult.Value, UserId = getUserResult.Value.Id }; - ErrorOr insertUserRoleResult = await userRoleRepository.InsertAsync(userRole, cancellationToken).ConfigureAwait(false); - if (insertUserRoleResult.IsError) + Result insertUserRoleResult = await userRoleRepository.InsertAsync(userRole, cancellationToken).ConfigureAwait(false); + if (insertUserRoleResult.IsFailure) return insertUserRoleResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Primitives/ErrorType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Primitives/ErrorType.cs new file mode 100644 index 00000000..59e76010 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Primitives/ErrorType.cs @@ -0,0 +1,42 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Primitives; + +/// +/// Enumeration for the type of an error. +/// +public enum ErrorType +{ + /// + /// Represents a generic failure. + /// + Failure, + + /// + /// Represents an unexpected error. + /// + Unexpected, + + /// + /// Represents a validation error. + /// + Validation, + + /// + /// Represents a conflict error. + /// + Conflict, + + /// + /// Represents a not found error. + /// + NotFound, + + /// + /// Represents an unauthorized error. + /// + Unauthorized, + + /// + /// Represents a forbidden error. + /// + Forbidden, +} diff --git a/src/Lumina.Domain.SharedKernel/Lumina.Domain.SharedKernel.csproj b/src/Lumina.Domain.SharedKernel/Lumina.Domain.SharedKernel.csproj index 42209cbc..0c1b73ae 100644 --- a/src/Lumina.Domain.SharedKernel/Lumina.Domain.SharedKernel.csproj +++ b/src/Lumina.Domain.SharedKernel/Lumina.Domain.SharedKernel.csproj @@ -13,8 +13,4 @@ - - - - diff --git a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.FileSystemManagement.cs b/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs similarity index 96% rename from src/Lumina.Domain.SharedKernel/Common/Errors/Errors.FileSystemManagement.cs rename to src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs index fcd3e87b..6b099e31 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.FileSystemManagement.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion -namespace Lumina.Domain.SharedKernel.Common.Errors; +namespace Lumina.Domain.Common.Errors; /// /// File management error types. diff --git a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Library.cs b/src/Lumina.Domain/Common/Errors/Errors.Library.cs similarity index 95% rename from src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Library.cs rename to src/Lumina.Domain/Common/Errors/Errors.Library.cs index b4b204b1..51a7d7dd 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Library.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Library.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion -namespace Lumina.Domain.SharedKernel.Common.Errors; +namespace Lumina.Domain.Common.Errors; /// /// Media Library error types. diff --git a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.LibraryScanning.cs b/src/Lumina.Domain/Common/Errors/Errors.LibraryScanning.cs similarity index 96% rename from src/Lumina.Domain.SharedKernel/Common/Errors/Errors.LibraryScanning.cs rename to src/Lumina.Domain/Common/Errors/Errors.LibraryScanning.cs index 7e956866..dad9c024 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.LibraryScanning.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.LibraryScanning.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion -namespace Lumina.Domain.SharedKernel.Common.Errors; +namespace Lumina.Domain.Common.Errors; /// /// Media Library Scan error types. diff --git a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.MediaContributor.cs b/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs similarity index 95% rename from src/Lumina.Domain.SharedKernel/Common/Errors/Errors.MediaContributor.cs rename to src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs index e53fe40d..4d443366 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.MediaContributor.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion -namespace Lumina.Domain.SharedKernel.Common.Errors; +namespace Lumina.Domain.Common.Errors; /// /// Media contributor error types. diff --git a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Metadata.cs b/src/Lumina.Domain/Common/Errors/Errors.Metadata.cs similarity index 98% rename from src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Metadata.cs rename to src/Lumina.Domain/Common/Errors/Errors.Metadata.cs index e7457812..29aa8125 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Metadata.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Metadata.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion -namespace Lumina.Domain.SharedKernel.Common.Errors; +namespace Lumina.Domain.Common.Errors; /// /// Metadata error types. diff --git a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Permission.cs b/src/Lumina.Domain/Common/Errors/Errors.Permission.cs similarity index 85% rename from src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Permission.cs rename to src/Lumina.Domain/Common/Errors/Errors.Permission.cs index 8b823e4c..7dc123e3 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Permission.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Permission.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion -namespace Lumina.Domain.SharedKernel.Common.Errors; +namespace Lumina.Domain.Common.Errors; /// /// Domain permission related error types. diff --git a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Plugins.cs b/src/Lumina.Domain/Common/Errors/Errors.Plugins.cs similarity index 93% rename from src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Plugins.cs rename to src/Lumina.Domain/Common/Errors/Errors.Plugins.cs index 80bb69ab..c0ed3faf 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Plugins.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Plugins.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion -namespace Lumina.Domain.SharedKernel.Common.Errors; +namespace Lumina.Domain.Common.Errors; /// /// Plugin error types. diff --git a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Thumbnails.cs b/src/Lumina.Domain/Common/Errors/Errors.Thumbnails.cs similarity index 88% rename from src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Thumbnails.cs rename to src/Lumina.Domain/Common/Errors/Errors.Thumbnails.cs index 7afcdfb4..44aa2a5e 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Thumbnails.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Thumbnails.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion -namespace Lumina.Domain.SharedKernel.Common.Errors; +namespace Lumina.Domain.Common.Errors; /// /// Domain thumbnails related error types. diff --git a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Users.cs b/src/Lumina.Domain/Common/Errors/Errors.Users.cs similarity index 89% rename from src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Users.cs rename to src/Lumina.Domain/Common/Errors/Errors.Users.cs index cb52aa15..498b5865 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.Users.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Users.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion -namespace Lumina.Domain.SharedKernel.Common.Errors; +namespace Lumina.Domain.Common.Errors; /// /// Users error types. diff --git a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.WrittenContent.cs b/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs similarity index 97% rename from src/Lumina.Domain.SharedKernel/Common/Errors/Errors.WrittenContent.cs rename to src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs index 47aa3a27..ac637464 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Errors/Errors.WrittenContent.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion -namespace Lumina.Domain.SharedKernel.Common.Errors; +namespace Lumina.Domain.Common.Errors; /// /// Written content error types. diff --git a/src/Lumina.Domain/Common/Exceptions/EventualConsistencyException.cs b/src/Lumina.Domain/Common/Exceptions/EventualConsistencyException.cs index f25bdb7a..e421d08b 100644 --- a/src/Lumina.Domain/Common/Exceptions/EventualConsistencyException.cs +++ b/src/Lumina.Domain/Common/Exceptions/EventualConsistencyException.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; #endregion diff --git a/src/Lumina.Domain/Common/Primitives/ConflictError.cs b/src/Lumina.Domain/Common/Primitives/ConflictError.cs index 8a999742..898987b1 100644 --- a/src/Lumina.Domain/Common/Primitives/ConflictError.cs +++ b/src/Lumina.Domain/Common/Primitives/ConflictError.cs @@ -1,10 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +#endregion + namespace Lumina.Domain.Common.Primitives; /// /// Error representing that the operation could not be completed due to a conflict with the current state. /// +/// The error code that uniquely identifies this error type. +/// The human-readable description of the error. public record ConflictError(string Code, string Description) : Error { + /// + /// Gets the type of this error. + /// + public override ErrorType Type => ErrorType.Conflict; + + /// + /// Gets the error code that uniquely identifies this error type. + /// public override string Code { get; } = Code; + + /// + /// Gets the human-readable description of the error. + /// public override string Description { get; } = Description; } diff --git a/src/Lumina.Domain/Common/Primitives/Error.cs b/src/Lumina.Domain/Common/Primitives/Error.cs index 97eb1dba..d056a16b 100644 --- a/src/Lumina.Domain/Common/Primitives/Error.cs +++ b/src/Lumina.Domain/Common/Primitives/Error.cs @@ -1,10 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +#endregion + namespace Lumina.Domain.Common.Primitives; /// -/// Represents an error that can be implicitly converted to a Results. +/// Represents an error that can be implicitly converted to a Result. /// public abstract record Error { + /// + /// Gets the type of this error. + /// + public abstract ErrorType Type { get; } + /// /// Gets the error code that uniquely identifies this error type. /// @@ -25,112 +34,134 @@ public abstract record Error } /// - /// Creates a new NotFoundError with the specified description. + /// Creates a new NotFoundError. /// + /// The error code, defaults to "General.NotFound" when null. /// The human-readable description of the error. - /// A new NotFoundError instance with code "NotFound". - public static NotFoundError NotFound(string description) + /// A new NotFoundError instance. + public static NotFoundError NotFound(string? code = null, string? description = null) { - return new("NotFound", description); + return new(code ?? "General.NotFound", description ?? "A 'Not Found' error has occurred."); } /// - /// Creates a new InvalidOperationError with the specified description. + /// Creates a new InvalidOperationError. /// + /// The error code, defaults to "General.InvalidOperation" when null. /// The human-readable description of the error. - /// A new InvalidOperationError instance with code "InvalidOperation". - public static InvalidOperationError InvalidOperation(string description) + /// A new InvalidOperationError instance. + public static InvalidOperationError InvalidOperation(string? code = null, string? description = null) { - return new("InvalidOperation", description); + return new(code ?? "General.InvalidOperation", description ?? "An invalid operation error has occurred."); } /// - /// Creates a new ForbiddenError with the specified description. + /// Creates a new ForbiddenError. /// + /// The error code, defaults to "General.Forbidden" when null. /// The human-readable description of the error. - /// A new ForbiddenError instance with code "Forbidden". - public static ForbiddenError Forbidden(string description) + /// A new ForbiddenError instance. + public static ForbiddenError Forbidden(string? code = null, string? description = null) { - return new("Forbidden", description); + return new(code ?? "General.Forbidden", description ?? "A 'Forbidden' error has occurred."); } /// - /// Creates a new FailureError with the specified description. + /// Creates a new FailureError. /// + /// The error code, defaults to "General.Failure" when null. /// The human-readable description of the error. - /// A new FailureError instance with code "Failure". - public static FailureError Failure(string description) + /// A new FailureError instance. + public static FailureError Failure(string? code = null, string? description = null) { - return new("Failure", description); + return new(code ?? "General.Failure", description ?? "A failure has occurred."); } /// - /// Creates a new ValidationError with the specified description. + /// Creates a new ValidationError. /// + /// The error code, defaults to "General.Validation" when null. /// The human-readable description of the error. - /// A new ValidationError instance with code "Validation". - public static ValidationError Validation(string description) + /// A new ValidationError instance. + public static ValidationError Validation(string? code = null, string? description = null) { - return new("Validation", description); + return new(code ?? "General.Validation", description ?? "A validation error has occurred."); } /// - /// Creates a new ConflictError with the specified description. + /// Creates a new ConflictError. /// + /// The error code, defaults to "General.Conflict" when null. /// The human-readable description of the error. - /// A new ConflictError instance with code "Conflict". - public static ConflictError Conflict(string description) + /// A new ConflictError instance. + public static ConflictError Conflict(string? code = null, string? description = null) { - return new("Conflict", description); + return new(code ?? "General.Conflict", description ?? "A conflict error has occurred."); } /// - /// Creates a new TimeoutError with the specified description. + /// Creates a new TimeoutError. /// + /// The error code, defaults to "General.Timeout" when null. /// The human-readable description of the error. - /// A new TimeoutError instance with code "Timeout". - public static TimeoutError Timeout(string description) + /// A new TimeoutError instance. + public static TimeoutError Timeout(string? code = null, string? description = null) { - return new("Timeout", description); + return new(code ?? "General.Timeout", description ?? "The operation timed out."); } /// - /// Creates a new UnauthorizedError with the specified description. + /// Creates a new UnauthorizedError. /// + /// The error code, defaults to "General.Unauthorized" when null. /// The human-readable description of the error. - /// A new UnauthorizedError instance with code "Unauthorized". - public static UnauthorizedError Unauthorized(string description) + /// A new UnauthorizedError instance. + public static UnauthorizedError Unauthorized(string? code = null, string? description = null) { - return new("Unauthorized", description); + return new(code ?? "General.Unauthorized", description ?? "An 'Unauthorized' error has occurred."); } /// - /// Creates a new InternalError with the specified description. + /// Creates a new UnexpectedError. /// + /// The error code, defaults to "General.Unexpected" when null. /// The human-readable description of the error. - /// A new InternalError instance with code "Internal". - public static InternalError Internal(string description) + /// A new UnexpectedError instance. + public static UnexpectedError Unexpected(string? code = null, string? description = null) { - return new("Internal", description); + return new(code ?? "General.Unexpected", description ?? "An unexpected error has occurred."); } /// - /// Creates a new ResourceUnavailableError with the specified description. + /// Creates a new InternalError. /// + /// The error code, defaults to "General.Internal" when null. /// The human-readable description of the error. - /// A new ResourceUnavailableError instance with code "ResourceUnavailable". - public static ResourceUnavailableError ResourceUnavailable(string description) + /// A new InternalError instance. + public static InternalError Internal(string? code = null, string? description = null) { - return new("ResourceUnavailable", description); + return new(code ?? "General.Internal", description ?? "An internal error has occurred."); } /// - /// Creates a new NotImplementedError with the specified description. + /// Creates a new ResourceUnavailableError. /// + /// The error code, defaults to "General.ResourceUnavailable" when null. /// The human-readable description of the error. - /// A new NotImplementedError instance with code "NotImplemented". - public static NotImplementedError NotImplemented(string description) + /// A new ResourceUnavailableError instance. + public static ResourceUnavailableError ResourceUnavailable(string? code = null, string? description = null) { - return new("NotImplemented", description); + return new(code ?? "General.ResourceUnavailable", description ?? "The required resource is currently unavailable."); + } + + /// + /// Creates a new NotImplementedError. + /// + /// The error code, defaults to "General.NotImplemented" when null. + /// The human-readable description of the error. + /// A new NotImplementedError instance. + public static NotImplementedError NotImplemented(string? code = null, string? description = null) + { + return new(code ?? "General.NotImplemented", description ?? "The requested functionality is not implemented."); } } diff --git a/src/Lumina.Domain/Common/Primitives/FailureError.cs b/src/Lumina.Domain/Common/Primitives/FailureError.cs index 548d18aa..b58943f3 100644 --- a/src/Lumina.Domain/Common/Primitives/FailureError.cs +++ b/src/Lumina.Domain/Common/Primitives/FailureError.cs @@ -1,10 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +#endregion + namespace Lumina.Domain.Common.Primitives; /// /// Error representing that some operation failing. /// +/// The error code that uniquely identifies this error type. +/// The human-readable description of the error. public record FailureError(string Code, string Description) : Error { + /// + /// Gets the type of this error. + /// + public override ErrorType Type => ErrorType.Failure; + + /// + /// Gets the error code that uniquely identifies this error type. + /// public override string Code { get; } = Code; + + /// + /// Gets the human-readable description of the error. + /// public override string Description { get; } = Description; } diff --git a/src/Lumina.Domain/Common/Primitives/ForbiddenError.cs b/src/Lumina.Domain/Common/Primitives/ForbiddenError.cs index c96bdf2a..d2522e7f 100644 --- a/src/Lumina.Domain/Common/Primitives/ForbiddenError.cs +++ b/src/Lumina.Domain/Common/Primitives/ForbiddenError.cs @@ -1,10 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +#endregion + namespace Lumina.Domain.Common.Primitives; /// /// Error representing that the operation is not allowed due to insufficient permissions or restrictions. /// +/// The error code that uniquely identifies this error type. +/// The human-readable description of the error. public record ForbiddenError(string Code, string Description) : Error { + /// + /// Gets the type of this error. + /// + public override ErrorType Type => ErrorType.Forbidden; + + /// + /// Gets the error code that uniquely identifies this error type. + /// public override string Code { get; } = Code; + + /// + /// Gets the human-readable description of the error. + /// public override string Description { get; } = Description; } diff --git a/src/Lumina.Domain/Common/Primitives/InternalError.cs b/src/Lumina.Domain/Common/Primitives/InternalError.cs index 0446e119..a7b24fb5 100644 --- a/src/Lumina.Domain/Common/Primitives/InternalError.cs +++ b/src/Lumina.Domain/Common/Primitives/InternalError.cs @@ -1,10 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +#endregion + namespace Lumina.Domain.Common.Primitives; /// /// Error representing that an unexpected internal error occurred. /// +/// The error code that uniquely identifies this error type. +/// The human-readable description of the error. public record InternalError(string Code, string Description) : Error { + /// + /// Gets the type of this error. + /// + public override ErrorType Type => ErrorType.Unexpected; + + /// + /// Gets the error code that uniquely identifies this error type. + /// public override string Code { get; } = Code; + + /// + /// Gets the human-readable description of the error. + /// public override string Description { get; } = Description; } diff --git a/src/Lumina.Domain/Common/Primitives/InvalidOperationError.cs b/src/Lumina.Domain/Common/Primitives/InvalidOperationError.cs index 7992af5e..3539ac7a 100644 --- a/src/Lumina.Domain/Common/Primitives/InvalidOperationError.cs +++ b/src/Lumina.Domain/Common/Primitives/InvalidOperationError.cs @@ -1,10 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +#endregion + namespace Lumina.Domain.Common.Primitives; /// /// Error representing that the operation is invalid in the current state or context. /// +/// The error code that uniquely identifies this error type. +/// The human-readable description of the error. public record InvalidOperationError(string Code, string Description) : Error { + /// + /// Gets the type of this error. + /// + public override ErrorType Type => ErrorType.Unexpected; + + /// + /// Gets the error code that uniquely identifies this error type. + /// public override string Code { get; } = Code; + + /// + /// Gets the human-readable description of the error. + /// public override string Description { get; } = Description; } diff --git a/src/Lumina.Domain/Common/Primitives/NotFoundError.cs b/src/Lumina.Domain/Common/Primitives/NotFoundError.cs index e9724789..a7f6ad90 100644 --- a/src/Lumina.Domain/Common/Primitives/NotFoundError.cs +++ b/src/Lumina.Domain/Common/Primitives/NotFoundError.cs @@ -1,10 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +#endregion + namespace Lumina.Domain.Common.Primitives; /// /// Error representing that the requested resource or entity was not found. /// +/// The error code that uniquely identifies this error type. +/// The human-readable description of the error. public record NotFoundError(string Code, string Description) : Error { + /// + /// Gets the type of this error. + /// + public override ErrorType Type => ErrorType.NotFound; + + /// + /// Gets the error code that uniquely identifies this error type. + /// public override string Code { get; } = Code; + + /// + /// Gets the human-readable description of the error. + /// public override string Description { get; } = Description; } diff --git a/src/Lumina.Domain/Common/Primitives/NotImplementedError.cs b/src/Lumina.Domain/Common/Primitives/NotImplementedError.cs index 5798c3d8..572cdf5f 100644 --- a/src/Lumina.Domain/Common/Primitives/NotImplementedError.cs +++ b/src/Lumina.Domain/Common/Primitives/NotImplementedError.cs @@ -1,10 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +#endregion + namespace Lumina.Domain.Common.Primitives; /// /// Error representing that the requested functionality is not implemented. /// +/// The error code that uniquely identifies this error type. +/// The human-readable description of the error. public record NotImplementedError(string Code, string Description) : Error { + /// + /// Gets the type of this error. + /// + public override ErrorType Type => ErrorType.Unexpected; + + /// + /// Gets the error code that uniquely identifies this error type. + /// public override string Code { get; } = Code; + + /// + /// Gets the human-readable description of the error. + /// public override string Description { get; } = Description; } diff --git a/src/Lumina.Domain/Common/Primitives/ResourceUnavailableError.cs b/src/Lumina.Domain/Common/Primitives/ResourceUnavailableError.cs index 4f08be8d..0b1af083 100644 --- a/src/Lumina.Domain/Common/Primitives/ResourceUnavailableError.cs +++ b/src/Lumina.Domain/Common/Primitives/ResourceUnavailableError.cs @@ -1,10 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +#endregion + namespace Lumina.Domain.Common.Primitives; /// /// Error representing that the required resource is currently unavailable. /// +/// The error code that uniquely identifies this error type. +/// The human-readable description of the error. public record ResourceUnavailableError(string Code, string Description) : Error { + /// + /// Gets the type of this error. + /// + public override ErrorType Type => ErrorType.Unexpected; + + /// + /// Gets the error code that uniquely identifies this error type. + /// public override string Code { get; } = Code; + + /// + /// Gets the human-readable description of the error. + /// public override string Description { get; } = Description; } diff --git a/src/Lumina.Domain/Common/Primitives/Results.cs b/src/Lumina.Domain/Common/Primitives/Result.Markers.cs similarity index 56% rename from src/Lumina.Domain/Common/Primitives/Results.cs rename to src/Lumina.Domain/Common/Primitives/Result.Markers.cs index eae5de3c..83de4ca1 100644 --- a/src/Lumina.Domain/Common/Primitives/Results.cs +++ b/src/Lumina.Domain/Common/Primitives/Result.Markers.cs @@ -1,9 +1,9 @@ namespace Lumina.Domain.Common.Primitives; /// -/// Provides predefined success results for operations that don't return meaningful data. +/// Provides predefined success results for operations that don't return meaningful data, and factory methods for results. /// -public static class Results +public static class Result { /// /// Represents a successful operation. @@ -24,4 +24,15 @@ public static class Results /// Represents a successful deletion operation. /// public static Deleted Deleted { get; } = new(); + + /// + /// Creates a successful result wrapping the provided value. + /// + /// The type of the value to wrap. + /// The value to wrap in a successful result. + /// A successful result containing the provided value. + public static Result From(TValue value) + { + return Result.Success(value); + } } diff --git a/src/Lumina.Domain/Common/Primitives/Result.cs b/src/Lumina.Domain/Common/Primitives/Result.cs index b7a28bc9..9addb649 100644 --- a/src/Lumina.Domain/Common/Primitives/Result.cs +++ b/src/Lumina.Domain/Common/Primitives/Result.cs @@ -1,3 +1,9 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Linq; +#endregion + namespace Lumina.Domain.Common.Primitives; /// diff --git a/src/Lumina.Domain/Common/Primitives/TimeoutError.cs b/src/Lumina.Domain/Common/Primitives/TimeoutError.cs index 610b06c0..cdd655ea 100644 --- a/src/Lumina.Domain/Common/Primitives/TimeoutError.cs +++ b/src/Lumina.Domain/Common/Primitives/TimeoutError.cs @@ -1,10 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +#endregion + namespace Lumina.Domain.Common.Primitives; /// /// Error representing that the operation timed out before completion. /// +/// The error code that uniquely identifies this error type. +/// The human-readable description of the error. public record TimeoutError(string Code, string Description) : Error { + /// + /// Gets the type of this error. + /// + public override ErrorType Type => ErrorType.Unexpected; + + /// + /// Gets the error code that uniquely identifies this error type. + /// public override string Code { get; } = Code; + + /// + /// Gets the human-readable description of the error. + /// public override string Description { get; } = Description; } diff --git a/src/Lumina.Domain/Common/Primitives/UnauthorizedError.cs b/src/Lumina.Domain/Common/Primitives/UnauthorizedError.cs index 686ad165..6115dbe7 100644 --- a/src/Lumina.Domain/Common/Primitives/UnauthorizedError.cs +++ b/src/Lumina.Domain/Common/Primitives/UnauthorizedError.cs @@ -1,10 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +#endregion + namespace Lumina.Domain.Common.Primitives; /// /// Error representing that authentication is required or has failed. /// +/// The error code that uniquely identifies this error type. +/// The human-readable description of the error. public record UnauthorizedError(string Code, string Description) : Error { + /// + /// Gets the type of this error. + /// + public override ErrorType Type => ErrorType.Unauthorized; + + /// + /// Gets the error code that uniquely identifies this error type. + /// public override string Code { get; } = Code; + + /// + /// Gets the human-readable description of the error. + /// public override string Description { get; } = Description; } diff --git a/src/Lumina.Domain/Common/Primitives/UnexpectedError.cs b/src/Lumina.Domain/Common/Primitives/UnexpectedError.cs new file mode 100644 index 00000000..55dfddc2 --- /dev/null +++ b/src/Lumina.Domain/Common/Primitives/UnexpectedError.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +#endregion + +namespace Lumina.Domain.Common.Primitives; + +/// +/// Error representing that an unexpected error occurred. +/// +/// The error code that uniquely identifies this error type. +/// The human-readable description of the error. +public record UnexpectedError(string Code, string Description) : Error +{ + /// + /// Gets the type of this error. + /// + public override ErrorType Type => ErrorType.Unexpected; + + /// + /// Gets the error code that uniquely identifies this error type. + /// + public override string Code { get; } = Code; + + /// + /// Gets the human-readable description of the error. + /// + public override string Description { get; } = Description; +} diff --git a/src/Lumina.Domain/Common/Primitives/ValidationError.cs b/src/Lumina.Domain/Common/Primitives/ValidationError.cs index 3a5d1de7..95ccbce2 100644 --- a/src/Lumina.Domain/Common/Primitives/ValidationError.cs +++ b/src/Lumina.Domain/Common/Primitives/ValidationError.cs @@ -1,10 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +#endregion + namespace Lumina.Domain.Common.Primitives; /// /// Error representing that the input or data failed validation rules. /// +/// The error code that uniquely identifies this error type. +/// The human-readable description of the error. public record ValidationError(string Code, string Description) : Error { + /// + /// Gets the type of this error. + /// + public override ErrorType Type => ErrorType.Validation; + + /// + /// Gets the error code that uniquely identifies this error type. + /// public override string Code { get; } = Code; + + /// + /// Gets the human-readable description of the error. + /// public override string Description { get; } = Description; } diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs index 4a247dce..9c713576 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Domain.Common.Models.Core; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics; #endregion @@ -33,12 +32,12 @@ public class Genre : ValueObject /// /// The value of the genre. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create(string? name) + public static Result Create(string? name) { if (string.IsNullOrWhiteSpace(name)) - return Errors.Metadata.GenreNameCannotBeEmpty; + return Errors.Errors.Metadata.GenreNameCannotBeEmpty; return new Genre(name); } diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs index a9e5e3db..dc32fc76 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Models.Core; + +using Lumina.Domain.Common.Errors; using System.Collections.Generic; using System.Diagnostics; #endregion @@ -50,16 +50,16 @@ public class LanguageInfo : ValueObject /// The full name of the language in English. /// The optional native name of the language. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create(string? languageCode, string? languageName, Optional nativeName) + public static Result Create(string? languageCode, string? languageName, Optional nativeName) { if (string.IsNullOrWhiteSpace(languageCode)) - return Errors.Metadata.LanguageCodeCannotBeEmpty; + return Errors.Errors.Metadata.LanguageCodeCannotBeEmpty; if (string.IsNullOrWhiteSpace(languageName)) - return Errors.Metadata.LanguageNameCannotBeEmpty; + return Errors.Errors.Metadata.LanguageNameCannotBeEmpty; if (languageCode.Length != 2) - return Errors.Metadata.InvalidIsoCode; + return Errors.Errors.Metadata.InvalidIsoCode; return new LanguageInfo(languageCode, languageName, nativeName); } diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs index 38a54896..c20e6a3f 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs @@ -1,11 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Diagnostics; -using Lumina.Domain.SharedKernel.Common.Errors; #endregion namespace Lumina.Domain.Common.ValueObjects.Metadata; @@ -82,9 +80,9 @@ public class ReleaseInfo : ValueObject /// The optional country or region of release. /// The optional release version or edition. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( Optional originalReleaseDate, Optional originalReleaseYear, Optional reReleaseDate, @@ -93,13 +91,13 @@ public class ReleaseInfo : ValueObject Optional releaseVersion) { if (originalReleaseDate.HasValue && originalReleaseYear.HasValue && originalReleaseDate.Value.Year != originalReleaseYear.Value) - return Errors.Metadata.OriginalReleaseDateAndYearMustMatch; + return Errors.Errors.Metadata.OriginalReleaseDateAndYearMustMatch; if (reReleaseDate.HasValue && reReleaseYear.HasValue && reReleaseDate.Value.Year != reReleaseYear.Value) - return Errors.Metadata.ReReleaseDateAndYearMustMatch; + return Errors.Errors.Metadata.ReReleaseDateAndYearMustMatch; if (originalReleaseDate.HasValue && reReleaseDate.HasValue && originalReleaseDate.Value > reReleaseDate.Value) - return Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate; + return Errors.Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate; if (originalReleaseYear.HasValue && reReleaseYear.HasValue && originalReleaseYear.Value > reReleaseYear.Value) - return Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear; + return Errors.Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear; return new ReleaseInfo(originalReleaseDate, originalReleaseYear, reReleaseDate, reReleaseYear, releaseCountry, releaseVersion); } diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs index fececb6c..d17b4cce 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Models.Core; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using System.Collections.Generic; using System.Diagnostics; #endregion @@ -33,12 +33,12 @@ public class Tag : ValueObject /// /// The value of the tag. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create(string? name) + public static Result Create(string? name) { if (string.IsNullOrWhiteSpace(name)) - return Errors.Metadata.TagNameCannotBeEmpty; + return Errors.Errors.Metadata.TagNameCannotBeEmpty; return new Tag(name); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs index 79848bc6..22c2bbf1 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Domain.Common.Primitives; + using Lumina.Domain.Common.ValueObjects.Metadata; using System.Collections.Generic; using System.Diagnostics; @@ -102,9 +102,9 @@ public class AudioMetadata : BaseMetadata /// The genres of the audio. /// The tags associated with the audio. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( string title, Optional originalTitle, int durationInSeconds, diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/Directory.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/Directory.cs index c35f7953..363126f1 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/Directory.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/Directory.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Domain.Common.Primitives; + using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; @@ -54,9 +54,9 @@ public sealed class Directory : FileSystemItem /// The date and time the directory was last modified. Can be optional if unknown. /// The status of the file system item. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( string path, string name, Optional dateCreated, @@ -64,16 +64,16 @@ public sealed class Directory : FileSystemItem FileSystemItemStatus status = FileSystemItemStatus.Accessible) { // TODO: enforce invariants - ErrorOr createPathResult = FileSystemPathId.Create(path); - if (createPathResult.IsError) + Result createPathResult = FileSystemPathId.Create(path); + if (createPathResult.IsFailure) return createPathResult.Errors; Directory newDirectory = new( createPathResult.Value, name, dateCreated, dateModified); - ErrorOr setStatusResult = newDirectory.SetStatus(status); - if (setStatusResult.IsError) + Result setStatusResult = newDirectory.SetStatus(status); + if (setStatusResult.IsFailure) return setStatusResult.Errors; return newDirectory; } @@ -86,9 +86,9 @@ public sealed class Directory : FileSystemItem /// The date and time the directory was last modified. Can be optional if unknown. /// The status of the file system item. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( FileSystemPathId id, string name, Optional dateCreated, @@ -101,8 +101,8 @@ public sealed class Directory : FileSystemItem name, dateCreated, dateModified); - ErrorOr setStatusResult = newDirectory.SetStatus(status); - if (setStatusResult.IsError) + Result setStatusResult = newDirectory.SetStatus(status); + if (setStatusResult.IsFailure) return setStatusResult.Errors; return newDirectory; } @@ -111,8 +111,8 @@ public sealed class Directory : FileSystemItem /// Updates the last modified date of the file system item. /// /// The new date and time of last modification. - /// An representing either a successful operation, or an error. - public ErrorOr UpdateLastModified(DateTime date) + /// An representing either a successful operation, or an error. + public Result UpdateLastModified(DateTime date) { DateModified = date; return Result.Updated; @@ -122,8 +122,8 @@ public sealed class Directory : FileSystemItem /// Adds a file system item to the directory. /// /// The file system item to add. - /// An representing either a successful operation, or an error. - public ErrorOr AddItem(FileSystemItem item) + /// An representing either a successful operation, or an error. + public Result AddItem(FileSystemItem item) { _items.Add(item); return Result.Updated; @@ -133,8 +133,8 @@ public sealed class Directory : FileSystemItem /// Removes a file system item from the directory. /// /// The file system item to remove. - /// An representing either a successful operation, or an error. - public ErrorOr RemoveItem(FileSystemItem item) + /// An representing either a successful operation, or an error. + public Result RemoveItem(FileSystemItem item) { _items.Remove(item); return Result.Updated; diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/File.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/File.cs index ded556b7..79086078 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/File.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/File.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Domain.Common.Primitives; + using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using System; using System.Diagnostics; #endregion @@ -55,9 +55,9 @@ public sealed class File : FileSystemItem /// The size of the file in bytes. /// The status of the file system item. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( string path, string name, Optional dateCreated, @@ -66,8 +66,8 @@ public sealed class File : FileSystemItem FileSystemItemStatus status = FileSystemItemStatus.Accessible) { // TODO: enforce invariants - ErrorOr createPathResult = FileSystemPathId.Create(path); - if (createPathResult.IsError) + Result createPathResult = FileSystemPathId.Create(path); + if (createPathResult.IsFailure) return createPathResult.Errors; File newFile = new( createPathResult.Value, @@ -75,8 +75,8 @@ public sealed class File : FileSystemItem dateCreated, dateModified, size); - ErrorOr setStatusResult = newFile.SetStatus(status); - if (setStatusResult.IsError) + Result setStatusResult = newFile.SetStatus(status); + if (setStatusResult.IsFailure) return setStatusResult.Errors; return newFile; } @@ -91,9 +91,9 @@ public sealed class File : FileSystemItem /// The size of the file in bytes. /// The status of the file system item. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( FileSystemPathId id, string name, Optional dateCreated, @@ -108,8 +108,8 @@ public sealed class File : FileSystemItem dateCreated, dateModified, size); - ErrorOr setStatusResult = newFile.SetStatus(status); - if (setStatusResult.IsError) + Result setStatusResult = newFile.SetStatus(status); + if (setStatusResult.IsFailure) return setStatusResult.Errors; return newFile; } @@ -118,8 +118,8 @@ public sealed class File : FileSystemItem /// Updates the last modified date of the file system item. /// /// The new date and time of last modification. - /// An representing either a successful operation, or an error. - public ErrorOr UpdateLastModified(DateTime date) + /// An representing either a successful operation, or an error. + public Result UpdateLastModified(DateTime date) { DateModified = date; return Result.Updated; @@ -129,8 +129,8 @@ public sealed class File : FileSystemItem /// Updates the size of the file. /// /// The new size, in bytes. - /// An representing either a successful operation, or an error. - public ErrorOr UpdateSize(long newSize) + /// An representing either a successful operation, or an error. + public Result UpdateSize(long newSize) { Size = newSize; return Result.Updated; @@ -140,8 +140,8 @@ public sealed class File : FileSystemItem /// Renames the file system item to the specified new name. /// /// The new name for the file system item. - /// An representing either a successful operation, or an error. - public ErrorOr Rename(string newName) + /// An representing either a successful operation, or an error. + public Result Rename(string newName) { if (string.IsNullOrWhiteSpace(newName)) return Errors.FileSystemManagement.NameCannotBeEmpty; diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItem.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItem.cs index c3503171..139c3a95 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItem.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItem.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; @@ -37,16 +37,16 @@ public sealed class UnixRootItem : FileSystemItem /// /// The status of the file system root item. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create(FileSystemItemStatus status = FileSystemItemStatus.Accessible) + public static Result Create(FileSystemItemStatus status = FileSystemItemStatus.Accessible) { - ErrorOr createPathResult = FileSystemPathId.Create(PATH); - if (createPathResult.IsError) + Result createPathResult = FileSystemPathId.Create(PATH); + if (createPathResult.IsFailure) return createPathResult.Errors; UnixRootItem newRoot = new(createPathResult.Value, PATH); - ErrorOr setStatusResult = newRoot.SetStatus(status); - if (setStatusResult.IsError) + Result setStatusResult = newRoot.SetStatus(status); + if (setStatusResult.IsFailure) return setStatusResult.Errors; return newRoot; } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItem.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItem.cs index 64e956fc..01165f69 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItem.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItem.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; @@ -38,22 +38,22 @@ public sealed class WindowsRootItem : FileSystemItem /// The name of the file system root item. /// The status of the file system root item. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( string path, string name, FileSystemItemStatus status = FileSystemItemStatus.Accessible) { // TODO: enforce invariants - ErrorOr createPathResult = FileSystemPathId.Create(path); - if (createPathResult.IsError) + Result createPathResult = FileSystemPathId.Create(path); + if (createPathResult.IsFailure) return createPathResult.Errors; WindowsRootItem newRoot = new( createPathResult.Value, name); - ErrorOr setStatusResult = newRoot.SetStatus(status); - if (setStatusResult.IsError) + Result setStatusResult = newRoot.SetStatus(status); + if (setStatusResult.IsFailure) return setStatusResult.Errors; return newRoot; } @@ -65,9 +65,9 @@ public sealed class WindowsRootItem : FileSystemItem /// The name of the file system root item. /// The status of the file system root item. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( FileSystemPathId id, string name, FileSystemItemStatus status = FileSystemItemStatus.Accessible) @@ -76,8 +76,8 @@ public sealed class WindowsRootItem : FileSystemItem WindowsRootItem newFile = new( id, name); - ErrorOr setStatusResult = newFile.SetStatus(status); - if (setStatusResult.IsError) + Result setStatusResult = newFile.SetStatus(status); + if (setStatusResult.IsFailure) return setStatusResult.Errors; return newFile; } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/FileSystemItem.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/FileSystemItem.cs index 27dc2588..653b644b 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/FileSystemItem.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/FileSystemItem.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Errors; -using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; + using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Diagnostics; #endregion @@ -52,8 +52,8 @@ public abstract class FileSystemItem : AggregateRoot /// Sets the status of the filesystem item. /// /// The status to be set. - /// An representing either a successful operation, or an error. - public ErrorOr SetStatus(FileSystemItemStatus status) + /// An representing either a successful operation, or an error. + public Result SetStatus(FileSystemItemStatus status) { Status = status; return Result.Updated; @@ -63,8 +63,8 @@ public abstract class FileSystemItem : AggregateRoot /// Sets the parent of the filesystem item. /// /// The file system item to be set as parent. - /// An representing either a successful operation, or an error. - public ErrorOr SetParent(FileSystemItem parent) + /// An representing either a successful operation, or an error. + public Result SetParent(FileSystemItem parent) { if (parent is not null) Parent = parent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderService.cs index 5cb4c72b..bad71749 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderService.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using Lumina.Domain.Common.Errors; + using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; @@ -38,19 +38,19 @@ internal class DirectoryProviderService : IDirectoryProviderService /// /// The path from which to retrieve the subdirectory paths. /// Whether to include hidden subdirectories or not. - /// An containing either a collection of directory paths or an error. - public ErrorOr> GetSubdirectoryPaths(FileSystemPathId path, bool includeHiddenElements) + /// An containing either a collection of directory paths or an error. + public Result> GetSubdirectoryPaths(FileSystemPathId path, bool includeHiddenElements) { // check if the user has access permissions to the provided path if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false)) return Errors.Permission.UnauthorizedAccess; - return ErrorOrFactory.From(_fileSystem.Directory.GetDirectories(path.Path) + return Result.From(_fileSystem.Directory.GetDirectories(path.Path) .Where(path => includeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden) .OrderBy(path => path) .Select(path => path.EndsWith(_fileSystem.Path.DirectorySeparatorChar) ? path : path + _fileSystem.Path.DirectorySeparatorChar) .Select(path => FileSystemPathId.Create(path)) - .Where(errorOrPathId => !errorOrPathId.IsError) - .Select(errorOrPathId => errorOrPathId.Value) + .Where(pathIdResult => !pathIdResult.IsFailure) + .Select(pathIdResult => pathIdResult.Value) .AsEnumerable()); } @@ -76,8 +76,8 @@ internal class DirectoryProviderService : IDirectoryProviderService /// Checks if a directory with the specified path exists. /// /// The path of the directory whose existance is checked. - /// An containing either the result of checking the existance of a directory, or an error. - public ErrorOr DirectoryExists(FileSystemPathId path) + /// An containing either the result of checking the existance of a directory, or an error. + public Result DirectoryExists(FileSystemPathId path) { return _fileSystem.Directory.Exists(path.Path); } @@ -87,8 +87,8 @@ internal class DirectoryProviderService : IDirectoryProviderService /// /// The path to extract the file name from. /// The name of the file without the path, or the last segment of the path if no file name is found. - /// An containing either a file name or an error. - public ErrorOr GetFileName(FileSystemPathId path) + /// An containing either a file name or an error. + public Result GetFileName(FileSystemPathId path) { string inputPath = path.Path.EndsWith(_fileSystem.Path.DirectorySeparatorChar) ? path.Path[..^1] : path.Path; return _fileSystem.Path.GetFileName(inputPath); @@ -98,8 +98,8 @@ internal class DirectoryProviderService : IDirectoryProviderService /// Gets the last write time of a specific path. /// /// The path to retrieve the last write time for. - /// An containing either the optional last write time of if available, or an error. - public ErrorOr> GetLastWriteTime(FileSystemPathId path) + /// An containing either the optional last write time of if available, or an error. + public Result> GetLastWriteTime(FileSystemPathId path) { // check if the user has access permissions to the provided path if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)) @@ -111,8 +111,8 @@ internal class DirectoryProviderService : IDirectoryProviderService /// Gets the creation time of a specific path. /// /// The path to retrieve the creation time for. - /// An containing the optional creation time of if available, or an error. - public ErrorOr> GetCreationTime(FileSystemPathId path) + /// An containing the optional creation time of if available, or an error. + public Result> GetCreationTime(FileSystemPathId path) { // check if the user has access permissions to the provided path if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)) @@ -125,8 +125,8 @@ internal class DirectoryProviderService : IDirectoryProviderService /// /// The path where the directory will be created.. /// The name of the directory that will be created. - /// An containing either the path of a created directory, or an error. - public ErrorOr CreateDirectory(FileSystemPathId path, string name) + /// An containing either the path of a created directory, or an error. + public Result CreateDirectory(FileSystemPathId path, string name) { // to create a directory, its parent directory must be writable if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Write, false)) @@ -142,8 +142,8 @@ internal class DirectoryProviderService : IDirectoryProviderService /// Identifier for the path where the directory to be copied is located. /// Identifier for the path where the directory will be copied. /// Whether to override existing directories, or not. - /// An containing either the copied directory, or an error. - public ErrorOr CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + /// An containing either the copied directory, or an error. + public Result CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) { // check if the source directory exists if (!_fileSystem.Directory.Exists(sourcePath.Path)) @@ -165,15 +165,15 @@ internal class DirectoryProviderService : IDirectoryProviderService // copy all subdirectories foreach (IDirectoryInfo subDirInfo in sourceDirInfo.GetDirectories()) { - ErrorOr newSourcePathResult = FileSystemPathId.Create(subDirInfo.FullName); - if (newSourcePathResult.IsError) + Result newSourcePathResult = FileSystemPathId.Create(subDirInfo.FullName); + if (newSourcePathResult.IsFailure) return newSourcePathResult.Errors; - ErrorOr newDestinationPathResult = FileSystemPathId.Create(_fileSystem.Path.Combine(destPath, subDirInfo.Name)); - if (newDestinationPathResult.IsError) + Result newDestinationPathResult = FileSystemPathId.Create(_fileSystem.Path.Combine(destPath, subDirInfo.Name)); + if (newDestinationPathResult.IsFailure) return newDestinationPathResult.Errors; // recursive call - ErrorOr copySubDirResult = CopyDirectory(newSourcePathResult.Value, newDestinationPathResult.Value, overrideExisting); - if (copySubDirResult.IsError) + Result copySubDirResult = CopyDirectory(newSourcePathResult.Value, newDestinationPathResult.Value, overrideExisting); + if (copySubDirResult.IsFailure) return copySubDirResult.Errors; } return FileSystemPathId.Create(destPath); @@ -205,8 +205,8 @@ internal class DirectoryProviderService : IDirectoryProviderService /// Identifier for the path where the directory to be moved is located. /// Identifier for the path where the directory will be moved. /// Whether to override existing directories, or not. - /// An containing either a moved directory, or an error. - public ErrorOr MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + /// An containing either a moved directory, or an error. + public Result MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) { // check if the source directory exists if (!_fileSystem.Directory.Exists(sourcePath.Path)) @@ -273,21 +273,21 @@ internal class DirectoryProviderService : IDirectoryProviderService /// /// The path of the directory to be renamed. /// The new name of the directory. - /// An containing either the absolute path of the renamed directory, or an error. - public ErrorOr RenameDirectory(FileSystemPathId path, string name) + /// An containing either the absolute path of the renamed directory, or an error. + public Result RenameDirectory(FileSystemPathId path, string name) { // to rename a directory, its parent directory must be writable string? parentDirectory = _fileSystem.Directory.GetParent(path.Path)?.FullName; if (!string.IsNullOrEmpty(parentDirectory)) { - ErrorOr parendDirectoryResult = FileSystemPathId.Create(parentDirectory); - if (parendDirectoryResult.IsError) + Result parendDirectoryResult = FileSystemPathId.Create(parentDirectory); + if (parendDirectoryResult.IsFailure) return parendDirectoryResult.Errors; string? newDirectory = _fileSystem.Path.Combine(parentDirectory, name); if (!string.IsNullOrEmpty(newDirectory)) { - ErrorOr newDirectoryPathResult = FileSystemPathId.Create(newDirectory); - if (newDirectoryPathResult.IsError) + Result newDirectoryPathResult = FileSystemPathId.Create(newDirectory); + if (newDirectoryPathResult.IsFailure) return newDirectoryPathResult.Errors; if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write, false)) return Errors.Permission.UnauthorizedAccess; @@ -308,8 +308,8 @@ internal class DirectoryProviderService : IDirectoryProviderService /// Deletes a directory at the specified path. /// /// The path of the directory to be deleted. - /// An containing either the result of deleting a directory, or an error. - public ErrorOr DeleteDirectory(FileSystemPathId path) + /// An containing either the result of deleting a directory, or an error. + public Result DeleteDirectory(FileSystemPathId path) { // check if the user has access permissions to the provided path if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete, false)) diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryService.cs index c078dea9..f404edc1 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryService.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using Lumina.Domain.Common.Errors; + using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; @@ -37,11 +37,11 @@ public class DirectoryService : IDirectoryService /// /// String representation of the file path. /// Whether to include hidden subdirectories or not. - /// An containing either a collection of subdirectories or an error. - public ErrorOr> GetSubdirectories(string path, bool includeHiddenElements) + /// An containing either a collection of subdirectories or an error. + public Result> GetSubdirectories(string path, bool includeHiddenElements) { - ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) + Result fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsFailure) return fileSystemPathIdResult.Errors; return GetSubdirectories(fileSystemPathIdResult.Value, includeHiddenElements); } @@ -51,8 +51,8 @@ public class DirectoryService : IDirectoryService /// /// Directory object to retrieve subdirectories for. /// Whether to include hidden subdirectories or not. - /// An containing either a collection of subdirectories or an error. - public ErrorOr> GetSubdirectories(Directory directory, bool includeHiddenElements) + /// An containing either a collection of subdirectories or an error. + public Result> GetSubdirectories(Directory directory, bool includeHiddenElements) { return GetSubdirectories(directory.Id, includeHiddenElements); } @@ -62,38 +62,38 @@ public class DirectoryService : IDirectoryService /// /// Identifier for the file path. /// Whether to include hidden subdirectories or not. - /// An containing either a collection of subdirectories or an error. - public ErrorOr> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements) + /// An containing either a collection of subdirectories or an error. + public Result> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements) { // retrieve the list of subdirectories - ErrorOr> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPaths(path, includeHiddenElements); - if (subdirectoryPathsResult.IsError) + Result> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPaths(path, includeHiddenElements); + if (subdirectoryPathsResult.IsFailure) return subdirectoryPathsResult.Errors; List result = []; foreach (FileSystemPathId subPath in subdirectoryPathsResult.Value) { // extract directory details - ErrorOr dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(subPath); - ErrorOr> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(subPath); - ErrorOr> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(subPath); + Result dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(subPath); + Result> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(subPath); + Result> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(subPath); // if any error occurred, mark directory as Inaccessible - if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) + if (dirNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure) { - ErrorOr errorDirResult = Directory.Create(subPath, !dirNameResult.IsError ? dirNameResult.Value : null!, - !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), - !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional.None()); - if (errorDirResult.IsError) + Result errorDirResult = Directory.Create(subPath, !dirNameResult.IsFailure ? dirNameResult.Value : null!, + !dateCreatedResult.IsFailure ? dateCreatedResult.Value : Optional.None(), + !dateModifiedResult.IsFailure ? dateModifiedResult.Value : Optional.None()); + if (errorDirResult.IsFailure) return errorDirResult.Errors; - ErrorOr setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - if (setStatusResult.IsError) + Result setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); + if (setStatusResult.IsFailure) return setStatusResult.Errors; result.Add(errorDirResult.Value); } else { - ErrorOr subDirectoryResult = Directory.Create(subPath, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value); - if (subDirectoryResult.IsError) + Result subDirectoryResult = Directory.Create(subPath, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value); + if (subDirectoryResult.IsFailure) return subDirectoryResult.Errors; result.Add(subDirectoryResult.Value); } @@ -106,11 +106,11 @@ public class DirectoryService : IDirectoryService /// /// String representation of the path where the directory will be created. /// The name of the directory that will be created. - /// An containing either the result of creating a directory, or an error. - public ErrorOr CreateDirectory(string path, string name) + /// An containing either the result of creating a directory, or an error. + public Result CreateDirectory(string path, string name) { - ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) + Result fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsFailure) return fileSystemPathIdResult.Errors; return CreateDirectory(fileSystemPathIdResult.Value, name); } @@ -120,37 +120,37 @@ public class DirectoryService : IDirectoryService /// /// Identifier for the path where the directory will be created. /// The name of the directory that will be created. - /// An containing either the result of creating a directory, or an error. - public ErrorOr CreateDirectory(FileSystemPathId path, string name) + /// An containing either the result of creating a directory, or an error. + public Result CreateDirectory(FileSystemPathId path, string name) { // first, check if the directory about to be created does not already exist - ErrorOr combinedPath = _platformContext.PathStrategy.CombinePath(path, name); - if (combinedPath.IsError) + Result combinedPath = _platformContext.PathStrategy.CombinePath(path, name); + if (combinedPath.IsFailure) return combinedPath.Errors; - ErrorOr directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(combinedPath.Value); - if (directoryExists.IsError) + Result directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(combinedPath.Value); + if (directoryExists.IsFailure) return directoryExists.Errors; else if (directoryExists.Value == true) return Errors.FileSystemManagement.DirectoryAlreadyExists; else { // create the new directory - ErrorOr newDirectoryPathResult = _environmentContext.DirectoryProviderService.CreateDirectory(path, name); - if (newDirectoryPathResult.IsError) + Result newDirectoryPathResult = _environmentContext.DirectoryProviderService.CreateDirectory(path, name); + if (newDirectoryPathResult.IsFailure) return newDirectoryPathResult.Errors; - ErrorOr dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value); - ErrorOr> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value); - ErrorOr> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(newDirectoryPathResult.Value); + Result dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value); + Result> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value); + Result> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(newDirectoryPathResult.Value); // if any error occurred, mark directory as Inaccessible - if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) + if (dirNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure) { - ErrorOr errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsError ? dirNameResult.Value : null!, - !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), - !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional.None()); - if (errorDirResult.IsError) + Result errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsFailure ? dirNameResult.Value : null!, + !dateCreatedResult.IsFailure ? dateCreatedResult.Value : Optional.None(), + !dateModifiedResult.IsFailure ? dateModifiedResult.Value : Optional.None()); + if (errorDirResult.IsFailure) return errorDirResult.Errors; - ErrorOr setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - if (setStatusResult.IsError) + Result setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); + if (setStatusResult.IsFailure) return setStatusResult.Errors; return errorDirResult; } @@ -165,19 +165,19 @@ public class DirectoryService : IDirectoryService /// String representation of the path where the directory to be copied is located. /// String representation of the path where the directory will be copied. /// Whether to override existing directories, or not. - /// An containing either a copied directory, or an error. - public ErrorOr CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting) + /// An containing either a copied directory, or an error. + public Result CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting) { // make sure the paths are in the expected format if (!sourcePath.EndsWith(_platformContext.PathStrategy.PathSeparator)) sourcePath += _platformContext.PathStrategy.PathSeparator; if (!destinationPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) destinationPath += _platformContext.PathStrategy.PathSeparator; - ErrorOr fileSystemSourcePathIdResult = FileSystemPathId.Create(sourcePath); - if (fileSystemSourcePathIdResult.IsError) + Result fileSystemSourcePathIdResult = FileSystemPathId.Create(sourcePath); + if (fileSystemSourcePathIdResult.IsFailure) return fileSystemSourcePathIdResult.Errors; - ErrorOr fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath); - if (fileSystemDestinationPathIdResult.IsError) + Result fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath); + if (fileSystemDestinationPathIdResult.IsFailure) return fileSystemDestinationPathIdResult.Errors; return CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); } @@ -188,18 +188,18 @@ public class DirectoryService : IDirectoryService /// Identifier for the path where the directory to be copied is located. /// Identifier for the path where the directory will be copied. /// Whether to override existing directories, or not. - /// An containing either the copied directory, or an error. - public ErrorOr CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + /// An containing either the copied directory, or an error. + public Result CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) { - ErrorOr directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(sourcePath); - if (directoryExists.IsError) + Result directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(sourcePath); + if (directoryExists.IsFailure) return directoryExists.Errors; else if (directoryExists.Value == false) return Errors.FileSystemManagement.DirectoryNotFound; else { // copy the directory - ErrorOr newDirectory = _environmentContext.DirectoryProviderService.CopyDirectory(sourcePath, destinationPath, overrideExisting); + Result newDirectory = _environmentContext.DirectoryProviderService.CopyDirectory(sourcePath, destinationPath, overrideExisting); throw new NotImplementedException(); } @@ -211,19 +211,19 @@ public class DirectoryService : IDirectoryService /// String representation of the path where the directory to be moved is located. /// String representation of the path where the directory will be moved. /// Whether to override existing directories, or not. - /// An containing either a moved directory, or an error. - public ErrorOr MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting) + /// An containing either a moved directory, or an error. + public Result MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting) { // make sure the paths are in the expected format if (!sourcePath.EndsWith(_platformContext.PathStrategy.PathSeparator)) sourcePath += _platformContext.PathStrategy.PathSeparator; if (!destinationPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) destinationPath += _platformContext.PathStrategy.PathSeparator; - ErrorOr fileSystemSourcePathIdResult = FileSystemPathId.Create(sourcePath); - if (fileSystemSourcePathIdResult.IsError) + Result fileSystemSourcePathIdResult = FileSystemPathId.Create(sourcePath); + if (fileSystemSourcePathIdResult.IsFailure) return fileSystemSourcePathIdResult.Errors; - ErrorOr fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath); - if (fileSystemDestinationPathIdResult.IsError) + Result fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath); + if (fileSystemDestinationPathIdResult.IsFailure) return fileSystemDestinationPathIdResult.Errors; return MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); } @@ -234,18 +234,18 @@ public class DirectoryService : IDirectoryService /// Identifier for the path where the directory to be moved is located. /// Identifier for the path where the directory will be moved. /// Whether to override existing directories, or not. - /// An containing either the moved directory, or an error. - public ErrorOr MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + /// An containing either the moved directory, or an error. + public Result MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) { - ErrorOr directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(sourcePath); - if (directoryExists.IsError) + Result directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(sourcePath); + if (directoryExists.IsFailure) return directoryExists.Errors; else if (directoryExists.Value == false) return Errors.FileSystemManagement.DirectoryNotFound; else { // move the directory - ErrorOr newDirectory = _environmentContext.DirectoryProviderService.MoveDirectory(sourcePath, destinationPath, overrideExisting); + Result newDirectory = _environmentContext.DirectoryProviderService.MoveDirectory(sourcePath, destinationPath, overrideExisting); throw new NotImplementedException(); } @@ -256,11 +256,11 @@ public class DirectoryService : IDirectoryService /// /// String representation of the directory path. /// The new name of the directory. - /// An containing either the renamed directory, or an error. - public ErrorOr RenameDirectory(string path, string name) + /// An containing either the renamed directory, or an error. + public Result RenameDirectory(string path, string name) { - ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) + Result fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsFailure) return fileSystemPathIdResult.Errors; return RenameDirectory(fileSystemPathIdResult.Value, name); } @@ -270,37 +270,37 @@ public class DirectoryService : IDirectoryService /// /// Identifier for the directory path. /// The new name of the directory. - /// An containing either the renamed directory, or an error. - public ErrorOr RenameDirectory(FileSystemPathId path, string name) + /// An containing either the renamed directory, or an error. + public Result RenameDirectory(FileSystemPathId path, string name) { // first, check if the directory about to be created does not already exist - ErrorOr combinedPath = _platformContext.PathStrategy.CombinePath(path, name); - if (combinedPath.IsError) + Result combinedPath = _platformContext.PathStrategy.CombinePath(path, name); + if (combinedPath.IsFailure) return combinedPath.Errors; - ErrorOr directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(combinedPath.Value); - if (directoryExists.IsError) + Result directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(combinedPath.Value); + if (directoryExists.IsFailure) return directoryExists.Errors; else if (directoryExists.Value == true) return Errors.FileSystemManagement.DirectoryAlreadyExists; else { // rename the directory - ErrorOr newDirectoryPathResult = _environmentContext.DirectoryProviderService.RenameDirectory(path, name); - if (newDirectoryPathResult.IsError) + Result newDirectoryPathResult = _environmentContext.DirectoryProviderService.RenameDirectory(path, name); + if (newDirectoryPathResult.IsFailure) return newDirectoryPathResult.Errors; - ErrorOr dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value); - ErrorOr> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value); - ErrorOr> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(newDirectoryPathResult.Value); + Result dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value); + Result> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value); + Result> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(newDirectoryPathResult.Value); // if any error occurred, mark directory as Inaccessible - if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) + if (dirNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure) { - ErrorOr errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsError ? dirNameResult.Value : null!, - !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), - !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional.None()); - if (errorDirResult.IsError) + Result errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsFailure ? dirNameResult.Value : null!, + !dateCreatedResult.IsFailure ? dateCreatedResult.Value : Optional.None(), + !dateModifiedResult.IsFailure ? dateModifiedResult.Value : Optional.None()); + if (errorDirResult.IsFailure) return errorDirResult.Errors; - ErrorOr setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - if (setStatusResult.IsError) + Result setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); + if (setStatusResult.IsFailure) return setStatusResult.Errors; return errorDirResult; } @@ -313,11 +313,11 @@ public class DirectoryService : IDirectoryService /// Delete a directory for the specified string path. /// /// String representation of the directory path. - /// An containing either the result of deleting a directory, or an error. - public ErrorOr DeleteDirectory(string path) + /// An containing either the result of deleting a directory, or an error. + public Result DeleteDirectory(string path) { - ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) + Result fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsFailure) return fileSystemPathIdResult.Errors; return DeleteDirectory(fileSystemPathIdResult.Value); } @@ -326,8 +326,8 @@ public class DirectoryService : IDirectoryService /// Delete a directory for the specified path. /// /// Identifier for the directory path. - /// An containing either the result of deleting a directory, or an error. - public ErrorOr DeleteDirectory(FileSystemPathId path) + /// An containing either the result of deleting a directory, or an error. + public Result DeleteDirectory(FileSystemPathId path) { return _environmentContext.DirectoryProviderService.DeleteDirectory(path); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveService.cs index c541816b..5bd68ba7 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; @@ -33,32 +33,32 @@ public class DriveService : IDriveService /// /// Retrieves the list of drives. /// - /// An containing either a collection of drives or an error. - public ErrorOr> GetDrives() + /// An containing either a collection of drives or an error. + public Result> GetDrives() { if (_platformContext.Platform == PlatformType.Unix) { - ErrorOr unixRootResult = UnixRootItem.Create(FileSystemItemStatus.Accessible); - if (unixRootResult.IsError) + Result unixRootResult = UnixRootItem.Create(FileSystemItemStatus.Accessible); + if (unixRootResult.IsFailure) return unixRootResult.Errors; return new List() { unixRootResult.Value }; } else - return ErrorOrFactory.From(_fileSystem.DriveInfo.GetDrives() + return Result.From(_fileSystem.DriveInfo.GetDrives() .OrderBy(driveInfo => driveInfo.Name) .Where(driveInfo => driveInfo.IsReady) .Select(driveInfo => { - ErrorOr root; - ErrorOr windowsRootResult = WindowsRootItem.Create(driveInfo.Name, driveInfo.Name); - if (windowsRootResult.IsError) + Result root; + Result windowsRootResult = WindowsRootItem.Create(driveInfo.Name, driveInfo.Name); + if (windowsRootResult.IsFailure) return windowsRootResult.Errors; else root = windowsRootResult.Value; return root; }) - .Where(errorOrDrive => !errorOrDrive.IsError) - .Select(errorOrDrive => errorOrDrive.Value) + .Where(driveResult => !driveResult.IsFailure) + .Select(driveResult => driveResult.Value) .AsEnumerable()); } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs index b8e2dda2..859295c3 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using Lumina.Domain.Common.Errors; + using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; @@ -37,18 +37,18 @@ internal class FileProviderService : IFileProviderService /// /// The path for which to retrieve the list of files. /// Whether to include hidden files or not. - /// An containing either a collection of file paths or an error. - public ErrorOr> GetFilePaths(FileSystemPathId path, bool includeHiddenElements) + /// An containing either a collection of file paths or an error. + public Result> GetFilePaths(FileSystemPathId path, bool includeHiddenElements) { // check if the user has access permissions to the provided path if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory)) return Errors.Permission.UnauthorizedAccess; - return ErrorOrFactory.From(_fileSystem.Directory.GetFiles(path.Path) + return Result.From(_fileSystem.Directory.GetFiles(path.Path) .Where(path => includeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden) .OrderBy(path => path) .Select(path => FileSystemPathId.Create(path)) - .Where(errorOrPathId => !errorOrPathId.IsError) - .Select(errorOrPathId => errorOrPathId.Value) + .Where(pathIdResult => !pathIdResult.IsFailure) + .Select(pathIdResult => pathIdResult.Value) .AsEnumerable()); } @@ -74,8 +74,8 @@ internal class FileProviderService : IFileProviderService /// Checks if a file with the specified path exists. /// /// The path of the file whose existance is checked. - /// An containing either the result of checking the existance of a file, or an error. - public ErrorOr FileExists(FileSystemPathId path) + /// An containing either the result of checking the existance of a file, or an error. + public Result FileExists(FileSystemPathId path) { return _fileSystem.File.Exists(path.Path); } @@ -84,8 +84,8 @@ internal class FileProviderService : IFileProviderService /// Retrieves the file name from the specified path. /// /// The path to extract the file name from. - /// An containing either the name of the file without the path, or the last segment of the path if no file name is found, or an error. - public ErrorOr GetFileName(FileSystemPathId path) + /// An containing either the name of the file without the path, or the last segment of the path if no file name is found, or an error. + public Result GetFileName(FileSystemPathId path) { return _fileSystem.Path.GetFileName(path.Path); } @@ -94,8 +94,8 @@ internal class FileProviderService : IFileProviderService /// Retrieves the contents of a file at the specified path. /// /// The path for which to retrieve the file contents. - /// An containing either the contents of a file at the specified path, or an error. - public ErrorOr GetFileAsync(FileSystemPathId path) + /// An containing either the contents of a file at the specified path, or an error. + public Result GetFileAsync(FileSystemPathId path) { // check if the user has access permissions to the provided path if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)) @@ -107,8 +107,8 @@ internal class FileProviderService : IFileProviderService /// Gets the last write time of a file at the specified path. /// /// The path of the file to retrieve the last write time for. - /// An containing either the optional last write time of if available, or an error. - public ErrorOr> GetLastWriteTime(FileSystemPathId path) + /// An containing either the optional last write time of if available, or an error. + public Result> GetLastWriteTime(FileSystemPathId path) { // check if the user has access permissions to the provided path if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)) @@ -120,8 +120,8 @@ internal class FileProviderService : IFileProviderService /// Gets the creation time of a file at the specified path. /// /// The path of the file to retrieve the creation time for. - /// An containing either the optional creation time of if available, or an error. - public ErrorOr> GetCreationTime(FileSystemPathId path) + /// An containing either the optional creation time of if available, or an error. + public Result> GetCreationTime(FileSystemPathId path) { // check if the user has access permissions to the provided path if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)) @@ -133,8 +133,8 @@ internal class FileProviderService : IFileProviderService /// Gets the size of a file at the specified path. /// /// The path of the file to retrieve the size for. - /// An containing either the size of or an error. - public ErrorOr GetSize(FileSystemPathId path) + /// An containing either the size of or an error. + public Result GetSize(FileSystemPathId path) { // check if the user has access permissions to the provided path if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)) @@ -148,8 +148,8 @@ internal class FileProviderService : IFileProviderService /// Identifier for the path where the file to be copied is located. /// Identifier for the path of the directory where the file will be copied. /// Whether to override existing files, or not. - /// An containing either the copied file, or an error. - public ErrorOr CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + /// An containing either the copied file, or an error. + public Result CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) { // check if the source file exists if (!_fileSystem.File.Exists(sourceFilePath.Path)) @@ -201,8 +201,8 @@ internal class FileProviderService : IFileProviderService /// Identifier for the path where the file to be moved is located. /// Identifier for the path of the directory where the file will be moved. /// Whether to override existing files, or not. - /// An containing either a moved file, or an error. - public ErrorOr MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + /// An containing either a moved file, or an error. + public Result MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) { // check if the source file exists if (!_fileSystem.File.Exists(sourceFilePath.Path)) @@ -232,20 +232,20 @@ internal class FileProviderService : IFileProviderService /// /// The path of the file to be renamed. /// The new name of the file. - /// An containing either the absolute path of the renamed file, or an error. - public ErrorOr RenameFile(FileSystemPathId path, string name) + /// An containing either the absolute path of the renamed file, or an error. + public Result RenameFile(FileSystemPathId path, string name) { string? parentDirectory = _fileSystem.FileInfo.New(path.Path)?.DirectoryName; if (!string.IsNullOrEmpty(parentDirectory)) { - ErrorOr parendDirectoryResult = FileSystemPathId.Create(parentDirectory); - if (parendDirectoryResult.IsError) + Result parendDirectoryResult = FileSystemPathId.Create(parentDirectory); + if (parendDirectoryResult.IsFailure) return parendDirectoryResult.Errors; string? newFile = _fileSystem.Path.Combine(parendDirectoryResult.Value.Path, name); if (!string.IsNullOrEmpty(newFile)) { - ErrorOr newFilePathResult = FileSystemPathId.Create(newFile); - if (newFilePathResult.IsError) + Result newFilePathResult = FileSystemPathId.Create(newFile); + if (newFilePathResult.IsFailure) return newFilePathResult.Errors; // check if the user has access permissions to the provided path if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute)) @@ -266,8 +266,8 @@ internal class FileProviderService : IFileProviderService /// Deletes a file at the specified path. /// /// The path of the file to be deleted. - /// An containing either the result of deleting a file, or an error. - public ErrorOr DeleteFile(FileSystemPathId path) + /// An containing either the result of deleting a file, or an error. + public Result DeleteFile(FileSystemPathId path) { // check if the user has access permissions to the provided path if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete)) diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileService.cs index 1dddbf57..5a8ea35a 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileService.cs @@ -1,12 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Collections.Generic; #endregion @@ -37,11 +36,11 @@ public class FileService : IFileService /// /// String representation of the file path. /// Whether to include hidden files or not. - /// An containing either a collection of files or an error. - public ErrorOr> GetFiles(string path, bool includeHiddenElements) + /// An containing either a collection of files or an error. + public Result> GetFiles(string path, bool includeHiddenElements) { - ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) + Result fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsFailure) return fileSystemPathIdResult.Errors; return GetFiles(fileSystemPathIdResult.Value, includeHiddenElements); } @@ -51,8 +50,8 @@ public class FileService : IFileService /// /// The file object. /// Whether to include hidden files or not. - /// An containing either a collection of files or an error. - public ErrorOr> GetFiles(File file, bool includeHiddenElements) + /// An containing either a collection of files or an error. + public Result> GetFiles(File file, bool includeHiddenElements) { return GetFiles(file.Id, includeHiddenElements); } @@ -62,40 +61,40 @@ public class FileService : IFileService /// /// Identifier for the file path. /// Whether to include hidden files or not. - /// An containing either a collection of files or an error. - public ErrorOr> GetFiles(FileSystemPathId path, bool includeHiddenElements) + /// An containing either a collection of files or an error. + public Result> GetFiles(FileSystemPathId path, bool includeHiddenElements) { // retrieve the list of files - ErrorOr> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path, includeHiddenElements); - if (filePathsResult.IsError) + Result> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path, includeHiddenElements); + if (filePathsResult.IsFailure) return filePathsResult.Errors; List result = []; IEnumerable filePaths = filePathsResult.Value; foreach (FileSystemPathId filePath in filePaths) { // extract file details and add to the result list - ErrorOr fileNameResult = _environmentContext.FileProviderService.GetFileName(filePath); - ErrorOr> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(filePath); - ErrorOr> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(filePath); - ErrorOr sizeResult = _environmentContext.FileProviderService.GetSize(filePath); + Result fileNameResult = _environmentContext.FileProviderService.GetFileName(filePath); + Result> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(filePath); + Result> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(filePath); + Result sizeResult = _environmentContext.FileProviderService.GetSize(filePath); long size = sizeResult.Value ?? 0; // if any of the details returned an error, set inaccessible status - if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) + if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure) { - ErrorOr errorFileResult = File.Create(filePath, !fileNameResult.IsError ? fileNameResult.Value : null!, - !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), - !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional.None(), size); - if (errorFileResult.IsError) + Result errorFileResult = File.Create(filePath, !fileNameResult.IsFailure ? fileNameResult.Value : null!, + !dateCreatedResult.IsFailure ? dateCreatedResult.Value : Optional.None(), + !dateModifiedResult.IsFailure ? dateModifiedResult.Value : Optional.None(), size); + if (errorFileResult.IsFailure) return errorFileResult.Errors; - ErrorOr setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - if (setStatusResult.IsError) + Result setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); + if (setStatusResult.IsFailure) return setStatusResult.Errors; result.Add(errorFileResult.Value); } else { - ErrorOr fileResult = File.Create(filePath, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size); - if (fileResult.IsError) + Result fileResult = File.Create(filePath, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size); + if (fileResult.IsFailure) return fileResult.Errors; result.Add(fileResult.Value); } @@ -109,19 +108,19 @@ public class FileService : IFileService /// String representation of the path where the file to be copied is located. /// String representation of the path of the directory where the file will be copied. /// Whether to override existing files, or not. - /// An containing either a copied file, or an error. - public ErrorOr CopyFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting) + /// An containing either a copied file, or an error. + public Result CopyFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting) { if (string.IsNullOrWhiteSpace(destinationDirectoryPath)) return Errors.FileSystemManagement.InvalidPath; // make sure the paths are in the expected format if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator; - ErrorOr fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); - if (fileSystemSourcePathIdResult.IsError) + Result fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); + if (fileSystemSourcePathIdResult.IsFailure) return fileSystemSourcePathIdResult.Errors; - ErrorOr fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); - if (fileSystemDestinationPathIdResult.IsError) + Result fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); + if (fileSystemDestinationPathIdResult.IsFailure) return fileSystemDestinationPathIdResult.Errors; return CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); } @@ -132,35 +131,35 @@ public class FileService : IFileService /// Identifier for the path where the file to be copied is located. /// Identifier for the path of the directory where the file will be copied. /// Whether to override existing files, or not. - /// An containing either the copied file, or an error. - public ErrorOr CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + /// An containing either the copied file, or an error. + public Result CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) { - ErrorOr fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath); - if (fileExists.IsError) + Result fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath); + if (fileExists.IsFailure) return fileExists.Errors; else if (fileExists.Value == false) return Errors.FileSystemManagement.FileNotFound; else { // copy the file - ErrorOr copyFileResult = _environmentContext.FileProviderService.CopyFile(sourceFilePath, destinationDirectoryPath, overrideExisting); - if (copyFileResult.IsError) + Result copyFileResult = _environmentContext.FileProviderService.CopyFile(sourceFilePath, destinationDirectoryPath, overrideExisting); + if (copyFileResult.IsFailure) return copyFileResult.Errors; - ErrorOr fileNameResult = _environmentContext.FileProviderService.GetFileName(copyFileResult.Value); - ErrorOr> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(copyFileResult.Value); - ErrorOr> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(copyFileResult.Value); - ErrorOr sizeResult = _environmentContext.FileProviderService.GetSize(copyFileResult.Value); + Result fileNameResult = _environmentContext.FileProviderService.GetFileName(copyFileResult.Value); + Result> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(copyFileResult.Value); + Result> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(copyFileResult.Value); + Result sizeResult = _environmentContext.FileProviderService.GetSize(copyFileResult.Value); long size = sizeResult.Value ?? 0; // if any of the details returned an error, set inaccessible status - if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) + if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure) { - ErrorOr errorFileResult = File.Create(copyFileResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!, - !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), - !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional.None(), size); - if (errorFileResult.IsError) + Result errorFileResult = File.Create(copyFileResult.Value, !fileNameResult.IsFailure ? fileNameResult.Value : null!, + !dateCreatedResult.IsFailure ? dateCreatedResult.Value : Optional.None(), + !dateModifiedResult.IsFailure ? dateModifiedResult.Value : Optional.None(), size); + if (errorFileResult.IsFailure) return errorFileResult.Errors; - ErrorOr setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - if (setStatusResult.IsError) + Result setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); + if (setStatusResult.IsFailure) return setStatusResult.Errors; return errorFileResult; } @@ -175,19 +174,19 @@ public class FileService : IFileService /// String representation of the path where the file to be moved is located. /// String representation of the path of the directory where the file will be moved. /// Whether to override existing files, or not. - /// An containing either a moved file, or an error. - public ErrorOr MoveFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting) + /// An containing either a moved file, or an error. + public Result MoveFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting) { if (string.IsNullOrWhiteSpace(destinationDirectoryPath)) return Errors.FileSystemManagement.InvalidPath; // make sure the paths are in the expected format if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator; - ErrorOr fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); - if (fileSystemSourcePathIdResult.IsError) + Result fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); + if (fileSystemSourcePathIdResult.IsFailure) return fileSystemSourcePathIdResult.Errors; - ErrorOr fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); - if (fileSystemDestinationPathIdResult.IsError) + Result fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); + if (fileSystemDestinationPathIdResult.IsFailure) return fileSystemDestinationPathIdResult.Errors; return MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); } @@ -198,35 +197,35 @@ public class FileService : IFileService /// Identifier for the path where the file to be moved is located. /// Identifier for the path of the directory where the file will be moved. /// Whether to override existing files, or not. - /// An containing either the moved file, or an error. - public ErrorOr MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + /// An containing either the moved file, or an error. + public Result MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) { - ErrorOr fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath); - if (fileExists.IsError) + Result fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath); + if (fileExists.IsFailure) return fileExists.Errors; else if (fileExists.Value == false) return Errors.FileSystemManagement.FileNotFound; else { // move the file - ErrorOr moveFileResult = _environmentContext.FileProviderService.MoveFile(sourceFilePath, destinationDirectoryPath, overrideExisting); - if (moveFileResult.IsError) + Result moveFileResult = _environmentContext.FileProviderService.MoveFile(sourceFilePath, destinationDirectoryPath, overrideExisting); + if (moveFileResult.IsFailure) return moveFileResult.Errors; - ErrorOr fileNameResult = _environmentContext.FileProviderService.GetFileName(moveFileResult.Value); - ErrorOr> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(moveFileResult.Value); - ErrorOr> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(moveFileResult.Value); - ErrorOr sizeResult = _environmentContext.FileProviderService.GetSize(moveFileResult.Value); + Result fileNameResult = _environmentContext.FileProviderService.GetFileName(moveFileResult.Value); + Result> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(moveFileResult.Value); + Result> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(moveFileResult.Value); + Result sizeResult = _environmentContext.FileProviderService.GetSize(moveFileResult.Value); long size = sizeResult.Value ?? 0; // if any of the details returned an error, set inaccessible status - if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) + if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure) { - ErrorOr errorFileResult = File.Create(moveFileResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!, - !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), - !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional.None(), size); - if (errorFileResult.IsError) + Result errorFileResult = File.Create(moveFileResult.Value, !fileNameResult.IsFailure ? fileNameResult.Value : null!, + !dateCreatedResult.IsFailure ? dateCreatedResult.Value : Optional.None(), + !dateModifiedResult.IsFailure ? dateModifiedResult.Value : Optional.None(), size); + if (errorFileResult.IsFailure) return errorFileResult.Errors; - ErrorOr setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - if (setStatusResult.IsError) + Result setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); + if (setStatusResult.IsFailure) return setStatusResult.Errors; return errorFileResult; } @@ -240,11 +239,11 @@ public class FileService : IFileService /// /// String representation of the file path. /// The new name of the file. - /// An containing either the renamed file, or an error. - public ErrorOr RenameFile(string path, string name) + /// An containing either the renamed file, or an error. + public Result RenameFile(string path, string name) { - ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) + Result fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsFailure) return fileSystemPathIdResult.Errors; return RenameFile(fileSystemPathIdResult.Value, name); } @@ -254,39 +253,39 @@ public class FileService : IFileService /// /// Identifier for the file path. /// The new name of the file. - /// An containing either the renamed file, or an error. - public ErrorOr RenameFile(FileSystemPathId path, string name) + /// An containing either the renamed file, or an error. + public Result RenameFile(FileSystemPathId path, string name) { // first, check if the directory about to be created does not already exist - ErrorOr combinedPath = _platformContext.PathStrategy.CombinePath(path, name); - if (combinedPath.IsError) + Result combinedPath = _platformContext.PathStrategy.CombinePath(path, name); + if (combinedPath.IsFailure) return combinedPath.Errors; - ErrorOr fileExists = _environmentContext.FileProviderService.FileExists(combinedPath.Value); - if (fileExists.IsError) + Result fileExists = _environmentContext.FileProviderService.FileExists(combinedPath.Value); + if (fileExists.IsFailure) return fileExists.Errors; else if (fileExists.Value == true) return Errors.FileSystemManagement.FileAlreadyExists; else { // rename the file - ErrorOr newFilePathResult = _environmentContext.FileProviderService.RenameFile(path, name); - if (newFilePathResult.IsError) + Result newFilePathResult = _environmentContext.FileProviderService.RenameFile(path, name); + if (newFilePathResult.IsFailure) return newFilePathResult.Errors; - ErrorOr fileNameResult = _environmentContext.FileProviderService.GetFileName(newFilePathResult.Value); - ErrorOr> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(newFilePathResult.Value); - ErrorOr> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(newFilePathResult.Value); - ErrorOr sizeResult = _environmentContext.FileProviderService.GetSize(newFilePathResult.Value); + Result fileNameResult = _environmentContext.FileProviderService.GetFileName(newFilePathResult.Value); + Result> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(newFilePathResult.Value); + Result> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(newFilePathResult.Value); + Result sizeResult = _environmentContext.FileProviderService.GetSize(newFilePathResult.Value); long size = sizeResult.Value ?? 0; // if any of the details returned an error, set inaccessible status - if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) + if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure) { - ErrorOr errorFileResult = File.Create(newFilePathResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!, - !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), - !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional.None(), size); - if (errorFileResult.IsError) + Result errorFileResult = File.Create(newFilePathResult.Value, !fileNameResult.IsFailure ? fileNameResult.Value : null!, + !dateCreatedResult.IsFailure ? dateCreatedResult.Value : Optional.None(), + !dateModifiedResult.IsFailure ? dateModifiedResult.Value : Optional.None(), size); + if (errorFileResult.IsFailure) return errorFileResult.Errors; - ErrorOr setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - if (setStatusResult.IsError) + Result setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); + if (setStatusResult.IsFailure) return setStatusResult.Errors; return errorFileResult; } @@ -299,11 +298,11 @@ public class FileService : IFileService /// Delete a file for the specified string path. /// /// String representation of the file path. - /// An containing either the result of deleting a file, or an error. - public ErrorOr DeleteFile(string path) + /// An containing either the result of deleting a file, or an error. + public Result DeleteFile(string path) { - ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) + Result fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsFailure) return fileSystemPathIdResult.Errors; return DeleteFile(fileSystemPathIdResult.Value); } @@ -312,13 +311,13 @@ public class FileService : IFileService /// Delete a file for the specified string path. /// /// Identifier for the file path. - /// An containing either the result of deleting a file, or an error. - public ErrorOr DeleteFile(FileSystemPathId path) + /// An containing either the result of deleting a file, or an error. + public Result DeleteFile(FileSystemPathId path) { return _environmentContext.FileProviderService.DeleteFile(path); } - public ErrorOr ReadFile(FileSystemPathId path) + public Result ReadFile(FileSystemPathId path) { return true; } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs index f17ab177..24249be1 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; #endregion @@ -30,32 +30,32 @@ internal class FileSystemStructureSeedService : IFileSystemStructureSeedService /// Sets up the default file system directories needed by the application. /// /// The base path where the directories will be created relative to. - /// An representing either a successful operation, or an error. - public ErrorOr SetDefaultDirectories(string rootPath) + /// An representing either a successful operation, or an error. + public Result SetDefaultDirectories(string rootPath) { // make sure the root path exists - ErrorOr rootPathIdResult = FileSystemPathId.Create(rootPath); - if (rootPathIdResult.IsError) + Result rootPathIdResult = FileSystemPathId.Create(rootPath); + if (rootPathIdResult.IsFailure) return rootPathIdResult.Errors; // create the libraries directory - ErrorOr librariesPathResult = _pathService.CombinePath(rootPath, "libraries"); - if (librariesPathResult.IsError) + Result librariesPathResult = _pathService.CombinePath(rootPath, "libraries"); + if (librariesPathResult.IsFailure) return librariesPathResult.Errors; - ErrorOr libraryPathIdResult = FileSystemPathId.Create(librariesPathResult.Value); - if (libraryPathIdResult.IsError) + Result libraryPathIdResult = FileSystemPathId.Create(librariesPathResult.Value); + if (libraryPathIdResult.IsFailure) return libraryPathIdResult.Errors; - ErrorOr librariesDirectoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(libraryPathIdResult.Value); - if (librariesDirectoryExistsResult.IsError) + Result librariesDirectoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(libraryPathIdResult.Value); + if (librariesDirectoryExistsResult.IsFailure) return librariesDirectoryExistsResult.Errors; // only create it if it doesn't already exist if (!librariesDirectoryExistsResult.Value) { - ErrorOr createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(rootPathIdResult.Value, "libraries"); - if (createDirectoryResult.IsError) + Result createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(rootPathIdResult.Value, "libraries"); + if (createDirectoryResult.IsFailure) return createDirectoryResult.Errors; } return Result.Created; diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeService.cs index 2be3e066..03c35de9 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeService.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using System; @@ -40,8 +40,8 @@ public class FileTypeService : IFileTypeService /// /// The file to determine if it is an image or not. /// Cancellation token that can be used to stop the execution. - /// An containing the type of image or an error. - public async Task> GetImageTypeAsync(File file, CancellationToken cancellationToken) + /// An containing the type of image or an error. + public async Task> GetImageTypeAsync(File file, CancellationToken cancellationToken) { return await GetImageTypeAsync(file.Id, cancellationToken).ConfigureAwait(false); } @@ -51,8 +51,8 @@ public class FileTypeService : IFileTypeService /// /// The path of the file to determine if it is an image or not. /// Cancellation token that can be used to stop the execution. - /// An containing the type of image or an error. - public async Task> GetImageTypeAsync(FileSystemPathId path, CancellationToken cancellationToken) + /// An containing the type of image or an error. + public async Task> GetImageTypeAsync(FileSystemPathId path, CancellationToken cancellationToken) { // check if the user has access permissions to the provided path if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)) diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryProviderService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryProviderService.cs index a3332339..91d2ca69 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryProviderService.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Domain.Common.Primitives; + using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; @@ -18,45 +18,45 @@ public interface IDirectoryProviderService /// /// The path from which to retrieve the subdirectory paths. /// Whether to include hidden subdirectories or not. - /// An containing either a collection of directory paths or an error. - ErrorOr> GetSubdirectoryPaths(FileSystemPathId path, bool includeHiddenElements); + /// An containing either a collection of directory paths or an error. + Result> GetSubdirectoryPaths(FileSystemPathId path, bool includeHiddenElements); /// /// Checks if a directory with the specified path exists. /// /// The path of the directory whose existance is checked. - /// An containing either the result of checking the existance of a directory, or an error. - ErrorOr DirectoryExists(FileSystemPathId path); + /// An containing either the result of checking the existance of a directory, or an error. + Result DirectoryExists(FileSystemPathId path); /// /// Retrieves the file name from the specified path. /// /// The path to extract the file name from. - /// An containing either a file name or an error. - ErrorOr GetFileName(FileSystemPathId path); + /// An containing either a file name or an error. + Result GetFileName(FileSystemPathId path); /// /// Gets the last write time of a specific path. /// /// The path to retrieve the last write time for. /// The last write time for the specified path, or null if unavailable. - /// An containing either the optional last write time of if available, or an error. - ErrorOr> GetLastWriteTime(FileSystemPathId path); + /// An containing either the optional last write time of if available, or an error. + Result> GetLastWriteTime(FileSystemPathId path); /// /// Gets the creation time of a specific path. /// /// The path to retrieve the creation time for. - /// An containing the optional creation time of if available, or an error. - ErrorOr> GetCreationTime(FileSystemPathId path); + /// An containing the optional creation time of if available, or an error. + Result> GetCreationTime(FileSystemPathId path); /// /// Creates a new directory with the specified name, at the specified path. /// /// The path where the directory will be created. /// The name of the directory that will be created. - /// An containing either the path of a created directory, or an error. - ErrorOr CreateDirectory(FileSystemPathId path, string name); + /// An containing either the path of a created directory, or an error. + Result CreateDirectory(FileSystemPathId path, string name); /// /// Copies a directory located at to . @@ -64,8 +64,8 @@ public interface IDirectoryProviderService /// Identifier for the path where the directory to be copied is located. /// Identifier for the path where the directory will be copied. /// Whether to override existing directories, or not. - /// An containing either the copied directory, or an error. - ErrorOr CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting); + /// An containing either the copied directory, or an error. + Result CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting); /// /// Moves a directory located at to . @@ -73,21 +73,21 @@ public interface IDirectoryProviderService /// Identifier for the path where the directory to be moved is located. /// Identifier for the path where the directory will be moved. /// Whether to override existing directories, or not. - /// An containing either a moved directory, or an error. - ErrorOr MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting); + /// An containing either a moved directory, or an error. + Result MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting); /// /// Renames a directory at the specified path. /// /// The path of the directory to be renamed. /// The new name of the directory. - /// An containing either the absolute path of the renamed directory, or an error. - ErrorOr RenameDirectory(FileSystemPathId path, string name); + /// An containing either the absolute path of the renamed directory, or an error. + Result RenameDirectory(FileSystemPathId path, string name); /// /// Deletes a directory at the specified path. /// /// The path of the directory to be deleted. - /// An containing either the result of deleting a directory, or an error. - ErrorOr DeleteDirectory(FileSystemPathId path); + /// An containing either the result of deleting a directory, or an error. + Result DeleteDirectory(FileSystemPathId path); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryService.cs index 48b4f5bb..96afe5aa 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using System.Collections.Generic; @@ -17,32 +17,32 @@ public interface IDirectoryService /// /// String representation of the file path. /// Whether to include hidden subdirectories or not. - /// An containing either a collection of subdirectories or an error. - ErrorOr> GetSubdirectories(string path, bool includeHiddenElements); + /// An containing either a collection of subdirectories or an error. + Result> GetSubdirectories(string path, bool includeHiddenElements); /// /// Retrieves subdirectories for the given directory. /// /// Directory object to retrieve subdirectories for. /// Whether to include hidden subdirectories or not. - /// An containing either a collection of subdirectories or an error. - ErrorOr> GetSubdirectories(Directory directory, bool includeHiddenElements); + /// An containing either a collection of subdirectories or an error. + Result> GetSubdirectories(Directory directory, bool includeHiddenElements); /// /// Retrieves subdirectories for the specified file system path. /// /// Identifier for the file path. /// Whether to include hidden subdirectories or not. - /// An containing either a collection of subdirectories or an error. - ErrorOr> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements); + /// An containing either a collection of subdirectories or an error. + Result> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements); /// /// Creates a directory with the specified , at the specified . /// /// String representation of the path where the directory will be created. /// The name of the directory that will be created. - /// An containing either a created directory, or an error. - ErrorOr CreateDirectory(string path, string name); + /// An containing either a created directory, or an error. + Result CreateDirectory(string path, string name); /// /// Copies a directory located at to . @@ -50,8 +50,8 @@ public interface IDirectoryService /// String representation of the path where the directory to be copied is located. /// String representation of the path where the directory will be copied. /// Whether to override existing directories, or not. - /// An containing either a copied directory, or an error. - ErrorOr CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting); + /// An containing either a copied directory, or an error. + Result CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting); /// /// Moves a directory located at to . @@ -59,21 +59,21 @@ public interface IDirectoryService /// String representation of the path where the directory to be moved is located. /// String representation of the path where the directory will be moved. /// Whether to override existing directories, or not. - /// An containing either a moved directory, or an error. - ErrorOr MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting); + /// An containing either a moved directory, or an error. + Result MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting); /// /// Renames a directory with the specified , at the specified . /// /// String representation of the path of the directory that will be renamed. /// The new name of the directory. - /// An containing either a renamed directory, or an error. - ErrorOr RenameDirectory(string path, string name); + /// An containing either a renamed directory, or an error. + Result RenameDirectory(string path, string name); /// /// Delete a directory for the specified string path. /// /// String representation of the directory path. - /// An containing either the result of deleting a directory, or an error. - ErrorOr DeleteDirectory(string path); + /// An containing either the result of deleting a directory, or an error. + Result DeleteDirectory(string path); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDriveService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDriveService.cs index 67333065..d18bd8a7 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDriveService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDriveService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using System.Collections.Generic; #endregion @@ -14,6 +14,6 @@ public interface IDriveService /// /// Retrieves the list of drives. /// - /// An containing either a collection of drives or an error. - ErrorOr> GetDrives(); + /// An containing either a collection of drives or an error. + Result> GetDrives(); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileProviderService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileProviderService.cs index f75f7b41..591ebd67 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileProviderService.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Domain.Common.Primitives; + using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; @@ -18,50 +18,50 @@ public interface IFileProviderService /// /// The path for which to retrieve the list of files. /// Whether to include hidden files or not. - /// An containing either a collection of file paths, or an error. - ErrorOr> GetFilePaths(FileSystemPathId path, bool includeHiddenElements); + /// An containing either a collection of file paths, or an error. + Result> GetFilePaths(FileSystemPathId path, bool includeHiddenElements); /// /// Retrieves the contents of a file at the specified path. /// /// The path for which to retrieve the file contents. - /// An containing either the contents of a file at the specified path, or an error. - ErrorOr GetFileAsync(FileSystemPathId path); + /// An containing either the contents of a file at the specified path, or an error. + Result GetFileAsync(FileSystemPathId path); /// /// Checks if a file with the specified path exists. /// /// The path of the file whose existance is checked. - /// An containing either the result of checking the existance of a file, or an error. - ErrorOr FileExists(FileSystemPathId path); + /// An containing either the result of checking the existance of a file, or an error. + Result FileExists(FileSystemPathId path); /// /// Retrieves the file name from the specified path. /// /// The path to extract the file name from. - /// An containing either the name of the file without the path, or the last segment of the path if no file name is found, or an error. - ErrorOr GetFileName(FileSystemPathId path); + /// An containing either the name of the file without the path, or the last segment of the path if no file name is found, or an error. + Result GetFileName(FileSystemPathId path); /// /// Gets the last write time of a file at the specified path. /// /// The path of the file to retrieve the last write time for. - /// An containing either the optional last write time of if available, or an error. - ErrorOr> GetLastWriteTime(FileSystemPathId path); + /// An containing either the optional last write time of if available, or an error. + Result> GetLastWriteTime(FileSystemPathId path); /// /// Gets the creation time of a file at the specified path. /// /// The path of the file to retrieve the creation time for. - /// An containing either the otional creation time of if available, or an error. - ErrorOr> GetCreationTime(FileSystemPathId path); + /// An containing either the otional creation time of if available, or an error. + Result> GetCreationTime(FileSystemPathId path); /// /// Gets the size of a file at the specified path. /// /// The path of the file to retrieve the size for. - /// An containing either the size of or an error. - ErrorOr GetSize(FileSystemPathId path); + /// An containing either the size of or an error. + Result GetSize(FileSystemPathId path); /// /// Copies a file located at to . @@ -69,8 +69,8 @@ public interface IFileProviderService /// Identifier for the path where the file to be copied is located. /// Identifier for the path of the directory where the file will be copied. /// Whether to override existing files, or not. - /// An containing either the copied file, or an error. - ErrorOr CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting); + /// An containing either the copied file, or an error. + Result CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting); /// /// Moves a file located at to . @@ -78,21 +78,21 @@ public interface IFileProviderService /// Identifier for the path where the file to be moved is located. /// Identifier for the path of the directory where the file will be moved. /// Whether to override existing files, or not. - /// An containing either a moved file, or an error. - ErrorOr MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting); + /// An containing either a moved file, or an error. + Result MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting); /// /// Renames a file at the specified path. /// /// The path of the file to be renamed. /// The new name of the file. - /// An containing either the absolute path of the renamed file, or an error. - ErrorOr RenameFile(FileSystemPathId path, string name); + /// An containing either the absolute path of the renamed file, or an error. + Result RenameFile(FileSystemPathId path, string name); /// /// Deletes a file at the specified path. /// /// The path of the file to be deleted. - /// An containing either the result of deleting a file, or an error. - ErrorOr DeleteFile(FileSystemPathId path); + /// An containing either the result of deleting a file, or an error. + Result DeleteFile(FileSystemPathId path); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileService.cs index 2cc9b5c7..ece87ff5 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using System.Collections.Generic; @@ -17,24 +17,24 @@ public interface IFileService /// /// String representation of the file path. /// Whether to include hidden files or not. - /// An containing either a collection of files or an error. - ErrorOr> GetFiles(string path, bool includeHiddenElements); + /// An containing either a collection of files or an error. + Result> GetFiles(string path, bool includeHiddenElements); /// /// Retrieves files associated with a given file. /// /// The file object. /// Whether to include hidden files or not. - /// An containing either a collection of files or an error. - ErrorOr> GetFiles(File file, bool includeHiddenElements); + /// An containing either a collection of files or an error. + Result> GetFiles(File file, bool includeHiddenElements); /// /// Retrieves files for a specified file path ID. /// /// Identifier for the file path. /// Whether to include hidden files or not. - /// An containing either a collection of files or an error. - ErrorOr> GetFiles(FileSystemPathId path, bool includeHiddenElements); + /// An containing either a collection of files or an error. + Result> GetFiles(FileSystemPathId path, bool includeHiddenElements); /// /// Copies a file located at to . @@ -42,8 +42,8 @@ public interface IFileService /// String representation of the path where the file to be copied is located. /// String representation of the path where the file will be copied. /// Whether to override existing files, or not. - /// An containing either a copied file, or an error. - ErrorOr CopyFile(string sourcePath, string destinationPath, bool? overrideExisting); + /// An containing either a copied file, or an error. + Result CopyFile(string sourcePath, string destinationPath, bool? overrideExisting); /// /// Moves a file located at to . @@ -51,21 +51,21 @@ public interface IFileService /// String representation of the path where the file to be moved is located. /// String representation of the path where the file will be moved. /// Whether to override existing files, or not. - /// An containing either a moved file, or an error. - ErrorOr MoveFile(string sourcePath, string destinationPath, bool? overrideExisting); + /// An containing either a moved file, or an error. + Result MoveFile(string sourcePath, string destinationPath, bool? overrideExisting); /// /// Renames a file with the specified , at the specified . /// /// String representation of the path of the file that will be renamed. /// The new name of the file. - /// An containing either a renamed file, or an error. - ErrorOr RenameFile(string path, string name); + /// An containing either a renamed file, or an error. + Result RenameFile(string path, string name); /// /// Delete a file for the specified string path. /// /// String representation of the file path. - /// An containing either the result of deleting a file, or an error. - ErrorOr DeleteFile(string path); + /// An containing either the result of deleting a file, or an error. + Result DeleteFile(string path); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileSystemStructureSeedService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileSystemStructureSeedService.cs index 07653e44..b0521b8f 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileSystemStructureSeedService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileSystemStructureSeedService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; @@ -13,6 +13,6 @@ public interface IFileSystemStructureSeedService /// Sets up the default file system directories needed by the application. /// /// The base path where the directories will be created relative to. - /// An representing either a successful operation, or an error. - ErrorOr SetDefaultDirectories(string rootPath); + /// An representing either a successful operation, or an error. + Result SetDefaultDirectories(string rootPath); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileTypeService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileTypeService.cs index 2b6ac8b1..6bc29f53 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileTypeService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileTypeService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; @@ -19,14 +19,14 @@ public interface IFileTypeService /// /// The file to determine if it is an image or not. /// Cancellation token that can be used to stop the execution. - /// An containing the type of image or an error. - Task> GetImageTypeAsync(File file, CancellationToken cancellationToken); + /// An containing the type of image or an error. + Task> GetImageTypeAsync(File file, CancellationToken cancellationToken); /// /// Determines if a file identified by is of type image or not, and returns its type. /// /// The path of the file to determine if it is an image or not. /// Cancellation token that can be used to stop the execution. - /// An containing the type of image or an error. - Task> GetImageTypeAsync(FileSystemPathId path, CancellationToken cancellationToken); + /// An containing the type of image or an error. + Task> GetImageTypeAsync(FileSystemPathId path, CancellationToken cancellationToken); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs index a70aaf80..93a314a4 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; #endregion @@ -36,22 +36,22 @@ public interface IPathService /// /// The path to be combined. /// The name to be combined with the path. - /// An containing the combined path, or an error. - ErrorOr CombinePath(string path, string name); + /// An containing the combined path, or an error. + Result CombinePath(string path, string name); /// /// Parses into path segments. /// /// The path to be parsed. - /// An containing the path segments, or an error. - ErrorOr> ParsePath(string path); + /// An containing the path segments, or an error. + Result> ParsePath(string path); /// /// Goes up one level from , and returns the path segments. /// /// The path from which to navigate up one level. - /// An containing the path segments of the path up one level from , or an error. - ErrorOr> GoUpOneLevel(string path); + /// An containing the path segments of the path up one level from , or an error. + Result> GoUpOneLevel(string path); /// /// Returns a collection of characters that are invalid for paths. @@ -63,6 +63,6 @@ public interface IPathService /// Returns the root portion of the given path. /// /// The path for which to get the root. - /// An containing the root of , or an error. - ErrorOr GetPathRoot(string path); + /// An containing the root of , or an error. + Result GetPathRoot(string path); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IThumbnailService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IThumbnailService.cs index 5f666995..48bf9dfe 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IThumbnailService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IThumbnailService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Threading; using System.Threading.Tasks; @@ -18,8 +18,8 @@ public interface IThumbnailService /// String representation of the file path. /// The quality of the thumbnail to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. - Task> GetThumbnailAsync(string path, int quality, CancellationToken cancellationToken); + /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. + Task> GetThumbnailAsync(string path, int quality, CancellationToken cancellationToken); /// /// Gets the thumbnail of a file at the specified path. @@ -27,6 +27,6 @@ public interface IThumbnailService /// The path object. /// The quality of the thumbnail to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. - Task> GetThumbnailAsync(FileSystemPathId path, int quality, CancellationToken cancellationToken); + /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. + Task> GetThumbnailAsync(FileSystemPathId path, int quality, CancellationToken cancellationToken); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs index 4ea03de8..d36e1873 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; @@ -36,8 +36,8 @@ public class PathService : IPathService /// if is a valid path, otherwise. public bool IsValidPath(string path) { - ErrorOr newPathResult = FileSystemPathId.Create(path); - if (newPathResult.IsError) + Result newPathResult = FileSystemPathId.Create(path); + if (newPathResult.IsFailure) return false; return _platformContext.PathStrategy.IsValidPath(newPathResult.Value); } @@ -50,8 +50,8 @@ public class PathService : IPathService /// if exists, otherwise. public bool Exists(string path, bool includeHiddenElements = true) { - ErrorOr newPathResult = FileSystemPathId.Create(path); - if (newPathResult.IsError) + Result newPathResult = FileSystemPathId.Create(path); + if (newPathResult.IsFailure) return false; return _platformContext.PathStrategy.Exists(newPathResult.Value, includeHiddenElements); } @@ -61,16 +61,16 @@ public class PathService : IPathService /// /// The path to be combined. /// The name to be combined with the path. - /// An containing the combined path, or an error. - public ErrorOr CombinePath(string path, string name) + /// An containing the combined path, or an error. + public Result CombinePath(string path, string name) { if (string.IsNullOrWhiteSpace(path) || string.IsNullOrWhiteSpace(name)) return Errors.FileSystemManagement.InvalidPath; - ErrorOr newPathResult = FileSystemPathId.Create(path); - if (newPathResult.IsError) + Result newPathResult = FileSystemPathId.Create(path); + if (newPathResult.IsFailure) return newPathResult.Errors; - ErrorOr combinedPathResult = _platformContext.PathStrategy.CombinePath(newPathResult.Value, name); - if (combinedPathResult.IsError) + Result combinedPathResult = _platformContext.PathStrategy.CombinePath(newPathResult.Value, name); + if (combinedPathResult.IsFailure) return combinedPathResult.Errors; return combinedPathResult.Value.Path; } @@ -79,11 +79,11 @@ public class PathService : IPathService /// Parses into path segments. /// /// The path to be parsed. - /// An containing the path segments, or an error. - public ErrorOr> ParsePath(string path) + /// An containing the path segments, or an error. + public Result> ParsePath(string path) { - ErrorOr newPathResult = FileSystemPathId.Create(path); - if (newPathResult.IsError) + Result newPathResult = FileSystemPathId.Create(path); + if (newPathResult.IsFailure) return newPathResult.Errors; return _platformContext.PathStrategy.ParsePath(newPathResult.Value); } @@ -92,11 +92,11 @@ public class PathService : IPathService /// Goes up one level from , and returns the path segments. /// /// The path from which to navigate up one level. - /// An containing the path segments of the path up one level from , or an error. - public ErrorOr> GoUpOneLevel(string path) + /// An containing the path segments of the path up one level from , or an error. + public Result> GoUpOneLevel(string path) { - ErrorOr newPathResult = FileSystemPathId.Create(path); - if (newPathResult.IsError) + Result newPathResult = FileSystemPathId.Create(path); + if (newPathResult.IsFailure) return newPathResult.Errors; return _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value); } @@ -114,11 +114,11 @@ public class PathService : IPathService /// Returns the root portion of the given path. /// /// The path for which to get the root. - /// An containing the root of , or an error. - public ErrorOr GetPathRoot(string path) + /// An containing the root of , or an error. + public Result GetPathRoot(string path) { - ErrorOr newPathResult = FileSystemPathId.Create(path); - if (newPathResult.IsError) + Result newPathResult = FileSystemPathId.Create(path); + if (newPathResult.IsFailure) return newPathResult.Errors; return _platformContext.PathStrategy.GetPathRoot(newPathResult.Value); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs index f70313fe..08b46525 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using SixLabors.ImageSharp; @@ -38,11 +38,11 @@ public class ThumbnailService : IThumbnailService /// String representation of the file path. /// The quality of the thumbnail to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. - public async Task> GetThumbnailAsync(string path, int quality, CancellationToken cancellationToken) + /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. + public async Task> GetThumbnailAsync(string path, int quality, CancellationToken cancellationToken) { - ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) + Result fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsFailure) return fileSystemPathIdResult.Errors; return await GetThumbnailAsync(fileSystemPathIdResult.Value, quality, cancellationToken); } @@ -53,18 +53,18 @@ public class ThumbnailService : IThumbnailService /// The path of the file for which to get the thumbnail. /// The quality of the thumbnail to get. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. - public async Task> GetThumbnailAsync(FileSystemPathId path, int quality, CancellationToken cancellationToken) + /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. + public async Task> GetThumbnailAsync(FileSystemPathId path, int quality, CancellationToken cancellationToken) { // first, get the type of the image file - ErrorOr imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(path, cancellationToken); - if (imageTypeResult.IsError) + Result imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(path, cancellationToken); + if (imageTypeResult.IsFailure) return imageTypeResult.Errors; if (imageTypeResult.Value != ImageType.None) { // then, get its bytes - ErrorOr resultFileContents = _environmentContext.FileProviderService.GetFileAsync(path); - if (resultFileContents.IsError) + Result resultFileContents = _environmentContext.FileProviderService.GetFileAsync(path); + if (resultFileContents.IsFailure) return resultFileContents.Errors; byte[] fileContents = resultFileContents.Value; // finally, resize or adjust quality based on image type diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs index fb9d417d..ffd4e584 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; #endregion @@ -33,22 +33,22 @@ public interface IPathStrategy /// /// The path to be combined. /// The name to be combined with the path. - /// An containing the combined path, or an error. - ErrorOr CombinePath(FileSystemPathId path, string name); + /// An containing the combined path, or an error. + Result CombinePath(FileSystemPathId path, string name); /// /// Parses into path segments. /// /// The path to be parsed. - /// An containing the path segments, or an error. - ErrorOr> ParsePath(FileSystemPathId path); + /// An containing the path segments, or an error. + Result> ParsePath(FileSystemPathId path); /// /// Goes up one level from , and returns the path segments. /// /// The path from which to navigate up one level. - /// An containing the path segments of the path up one level from , or an error. - ErrorOr> GoUpOneLevel(FileSystemPathId path); + /// An containing the path segments of the path up one level from , or an error. + Result> GoUpOneLevel(FileSystemPathId path); /// /// Returns a collection of characters that are invalid for paths. @@ -60,6 +60,6 @@ public interface IPathStrategy /// Returns the root portion of the given path. /// /// The path for which to get the root. - /// An containing the root of , or an error. - ErrorOr GetPathRoot(FileSystemPathId path); + /// An containing the root of , or an error. + Result GetPathRoot(FileSystemPathId path); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs index cceb4db6..1aa7dacc 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; @@ -79,8 +79,8 @@ public class UnixPathStrategy : IUnixPathStrategy /// /// The path to be combined. /// The name to be combined with the path. - /// An containing the combined path, or an error. - public ErrorOr CombinePath(FileSystemPathId path, string name) + /// An containing the combined path, or an error. + public Result CombinePath(FileSystemPathId path, string name) { if (string.IsNullOrWhiteSpace(name)) return Errors.FileSystemManagement.NameCannotBeEmpty; @@ -96,15 +96,15 @@ public class UnixPathStrategy : IUnixPathStrategy /// Parses into path segments. /// /// The path to be parsed. - /// An containing the path segments, or an error. - public ErrorOr> ParsePath(FileSystemPathId path) + /// An containing the path segments, or an error. + public Result> ParsePath(FileSystemPathId path) { // if path starts with anything other than '/', it's considered relative and invalid for this parser if (!path.Path.StartsWith(PathSeparator)) return Errors.FileSystemManagement.InvalidPath; // get the path segments List splitSegments = [.. path.Path.Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries)]; - IEnumerable> segmentsResults = splitSegments.Select((segment, index) => + IEnumerable> segmentsResults = splitSegments.Select((segment, index) => { bool isDirectory; if (segment.Contains('.')) @@ -113,18 +113,18 @@ public class UnixPathStrategy : IUnixPathStrategy isDirectory = true; return PathSegment.Create(segment, isDirectory, isDrive: false); }).Prepend(PathSegment.Create(PathSeparator.ToString(), isDirectory: false, isDrive: true)); // UNIX paths have '/' as "root drive" - foreach (ErrorOr segment in segmentsResults) - if (segment.IsError) + foreach (Result segment in segmentsResults) + if (segment.IsFailure) return segment.Errors; - return ErrorOrFactory.From(segmentsResults.Select(segmentResult => segmentResult.Value)); + return Result.From(segmentsResults.Select(segmentResult => segmentResult.Value)); } /// /// Goes up one level from , and returns the path segments. /// /// The path from which to navigate up one level. - /// An containing the path segments of the path up one level from , or an error. - public ErrorOr> GoUpOneLevel(FileSystemPathId path) + /// An containing the path segments of the path up one level from , or an error. + public Result> GoUpOneLevel(FileSystemPathId path) { // validation: ensure the path is not null or empty if (!IsValidPath(path)) @@ -139,8 +139,8 @@ public class UnixPathStrategy : IUnixPathStrategy if (lastIndex < 0) return Errors.FileSystemManagement.CannotNavigateUp; // return the path up to the last slash, or, if there's only the root slash, return that one instead - ErrorOr newPathResult = FileSystemPathId.Create(lastIndex > 0 ? tempPath[..lastIndex] : tempPath[..1]); - if (newPathResult.IsError) + Result newPathResult = FileSystemPathId.Create(lastIndex > 0 ? tempPath[..lastIndex] : tempPath[..1]); + if (newPathResult.IsFailure) return newPathResult.Errors; return ParsePath(newPathResult.Value); } @@ -158,8 +158,8 @@ public class UnixPathStrategy : IUnixPathStrategy /// Returns the root portion of the given path. /// /// The path for which to get the root. - /// An containing the root of , or an error. - public ErrorOr GetPathRoot(FileSystemPathId path) + /// An containing the root of , or an error. + public Result GetPathRoot(FileSystemPathId path) { if (!IsValidPath(path)) return Errors.FileSystemManagement.InvalidPath; diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs index ad5ad112..6639883c 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; @@ -78,8 +78,8 @@ public class WindowsPathStrategy : IWindowsPathStrategy /// /// The path to be combined. /// The name to be combined with the path. - /// An containing the combined path, or an error. - public ErrorOr CombinePath(FileSystemPathId path, string name) + /// An containing the combined path, or an error. + public Result CombinePath(FileSystemPathId path, string name) { if (name == null) return Errors.FileSystemManagement.NameCannotBeEmpty; @@ -95,18 +95,18 @@ public class WindowsPathStrategy : IWindowsPathStrategy /// Parses into path segments. /// /// The path to be parsed. - /// An containing the path segments, or an error. - public ErrorOr> ParsePath(FileSystemPathId path) + /// An containing the path segments, or an error. + public Result> ParsePath(FileSystemPathId path) { // Windows paths usually start with a drive letter and colon, e.g., "C:", or "\\" (UNC paths) if (!(path.Path.StartsWith(@"\\") || (path.Path.Length >= 3 && char.IsLetter(path.Path[0]) && path.Path[1] == ':' && path.Path[2] == PathSeparator))) return Errors.FileSystemManagement.InvalidPath; - IEnumerable> getPathSegmentsResults = GetPathSegments(); - foreach (ErrorOr getPathSegmentsResult in getPathSegmentsResults) - if (getPathSegmentsResult.IsError) + IEnumerable> getPathSegmentsResults = GetPathSegments(); + foreach (Result getPathSegmentsResult in getPathSegmentsResults) + if (getPathSegmentsResult.IsFailure) return getPathSegmentsResult.Errors; - return ErrorOrFactory.From(getPathSegmentsResults.Select(getPathSegmentsResult => getPathSegmentsResult.Value)); - IEnumerable> GetPathSegments() + return Result.From(getPathSegmentsResults.Select(getPathSegmentsResult => getPathSegmentsResult.Value)); + IEnumerable> GetPathSegments() { if (path.Path.StartsWith(@"\\")) { @@ -135,7 +135,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy } } } - ErrorOr CreatePathSegment(string segment, int index, int totalSegments) + Result CreatePathSegment(string segment, int index, int totalSegments) { bool isDirectory = segment.Contains('.') ? index != totalSegments - 1 || path.Path.EndsWith(PathSeparator) @@ -148,8 +148,8 @@ public class WindowsPathStrategy : IWindowsPathStrategy /// Goes up one level from , and returns the path segments. /// /// The path from which to navigate up one level. - /// An containing the path segments of the path up one level from , or an error. - public ErrorOr> GoUpOneLevel(FileSystemPathId path) + /// An containing the path segments of the path up one level from , or an error. + public Result> GoUpOneLevel(FileSystemPathId path) { // validation: ensure the path is not null or empty if (!IsValidPath(path)) @@ -174,8 +174,8 @@ public class WindowsPathStrategy : IWindowsPathStrategy if (lastIndex <= 2) return ParsePath(FileSystemPathId.Create(tempPath[..3]).Value); // return the path up to the last backslash - ErrorOr newPathResult = FileSystemPathId.Create(tempPath[..lastIndex]); - if (newPathResult.IsError) + Result newPathResult = FileSystemPathId.Create(tempPath[..lastIndex]); + if (newPathResult.IsFailure) return newPathResult.Errors; return ParsePath(newPathResult.Value); @@ -194,8 +194,8 @@ public class WindowsPathStrategy : IWindowsPathStrategy /// Returns the root portion of the given path. /// /// The path for which to get the root. - /// An containing the root of , or an error. - public ErrorOr GetPathRoot(FileSystemPathId path) + /// An containing the root of , or an error. + public Result GetPathRoot(FileSystemPathId path) { if (!IsValidPath(path)) return Errors.FileSystemManagement.InvalidPath; diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/FileSystemPathId.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/FileSystemPathId.cs index 8f61595e..5da6c0ac 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/FileSystemPathId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/FileSystemPathId.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using System.Collections.Generic; using System.Diagnostics; @@ -39,9 +39,9 @@ public sealed class FileSystemPathId : ValueObject /// /// The path of the file system item. /// - /// An containing either a successfully created or an error message. + /// An containing either a successfully created or an error message. /// - public static ErrorOr Create(string path) + public static Result Create(string path) { if (string.IsNullOrWhiteSpace(path)) return Errors.FileSystemManagement.InvalidPath; diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/PathSegment.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/PathSegment.cs index d7f7f637..cb47e666 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/PathSegment.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/PathSegment.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using System.Collections.Generic; using System.Diagnostics; @@ -49,9 +49,9 @@ public class PathSegment : ValueObject /// Value indicating if the current path segment is a file system directory or not. /// Value indicating if the current path segment is a file system drive or not. /// - /// An containing either a successfully created or an error message. + /// An containing either a successfully created or an error message. /// - public static ErrorOr Create(string name, bool isDirectory, bool isDrive) + public static Result Create(string name, bool isDirectory, bool isDrive) { if (string.IsNullOrWhiteSpace(name)) return Errors.FileSystemManagement.NameCannotBeEmpty; diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/StreamInfo.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/StreamInfo.cs index eebdbc06..e0a48e5b 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/StreamInfo.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/StreamInfo.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; -using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; + using System.Collections.Generic; using System.Diagnostics; #endregion @@ -98,9 +98,9 @@ public class StreamInfo : ValueObject /// The sample rate of the stream (for audio). /// The number of channels (for audio). /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( string streamId, string mimeType, int bitrate, diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs index 90ccd67a..445d175c 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; @@ -143,9 +143,9 @@ public class Library : AggregateRoot /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. /// The list of objects representing the unique identifier of scans of the media library. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( UserId userId, string title, LibraryType libraryType, @@ -162,8 +162,8 @@ public class Library : AggregateRoot // go through all the file system paths that make up the media library and create domain objects from them foreach (string contentLocation in contentLocations) { - ErrorOr contentLocationResult = FileSystemPathId.Create(contentLocation); - if (contentLocationResult.IsError) + Result contentLocationResult = FileSystemPathId.Create(contentLocation); + if (contentLocationResult.IsFailure) return contentLocationResult.Errors; tempContentLocations.Add(contentLocationResult.Value); } @@ -199,9 +199,9 @@ public class Library : AggregateRoot /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. /// The list of objects representing the unique identifier of scans of the media library. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( LibraryId id, UserId userId, string title, @@ -219,8 +219,8 @@ public class Library : AggregateRoot // go through all the file system paths that make up the media library and create domain objects from them foreach (string contentLocation in contentLocations) { - ErrorOr contentLocationResult = FileSystemPathId.Create(contentLocation); - if (contentLocationResult.IsError) + Result contentLocationResult = FileSystemPathId.Create(contentLocation); + if (contentLocationResult.IsFailure) return contentLocationResult.Errors; tempContentLocations.Add(contentLocationResult.Value); } @@ -260,8 +260,8 @@ public class Library : AggregateRoot /// /// Marks the current library as deleted. /// - /// An representing either a successful operation, or an error. - public ErrorOr Delete() + /// An representing either a successful operation, or an error. + public Result Delete() { // clear all existing events since they become irrelevant when the entity is deleted, and they dont need to be processed _domainEvents.Clear(); diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScan.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScan.cs index a92c0dc1..fa9d105e 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScan.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScan.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; @@ -61,9 +61,9 @@ public class LibraryScan : AggregateRoot /// The object representing the unique identifier of the user initiating the media library scan. /// The list of past media library scans the library identified by had. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create(LibraryId libraryId, UserId userId, List pastScans) + public static Result Create(LibraryId libraryId, UserId userId, List pastScans) { return new LibraryScan(ScanId.CreateUnique(), libraryId, userId, LibraryScanJobStatus.Pending, pastScans); } @@ -77,9 +77,9 @@ public class LibraryScan : AggregateRoot /// The status of the media library scan. /// The list of past media library scans the library identified by had. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create(ScanId id, LibraryId libraryId, UserId userId, LibraryScanJobStatus status, List pastScans) + public static Result Create(ScanId id, LibraryId libraryId, UserId userId, LibraryScanJobStatus status, List pastScans) { return new LibraryScan(id, libraryId, userId, status, pastScans); } @@ -87,8 +87,8 @@ public class LibraryScan : AggregateRoot /// /// Queues a media library scan. /// - /// An representing either a successful operation, or an error. - public ErrorOr QueueScan() + /// An representing either a successful operation, or an error. + public Result QueueScan() { // there must be no active scan for this library in the past 30 days if (_pastScans.Any(libraryScan => libraryScan.Status == LibraryScanJobStatus.Running || libraryScan.Status == LibraryScanJobStatus.Pending)) @@ -102,8 +102,8 @@ public class LibraryScan : AggregateRoot /// /// Starts the media library scan. /// - /// An representing either a successful operation, or an error. - public ErrorOr StartScan() + /// An representing either a successful operation, or an error. + public Result StartScan() { if (Status == LibraryScanJobStatus.Pending) Status = LibraryScanJobStatus.Running; @@ -122,8 +122,8 @@ public class LibraryScan : AggregateRoot /// /// Finishes the media library scan. /// - /// An representing either a successful operation, or an error. - public ErrorOr FinishScan() + /// An representing either a successful operation, or an error. + public Result FinishScan() { if (Status == LibraryScanJobStatus.Running) Status = LibraryScanJobStatus.Completed; @@ -136,8 +136,8 @@ public class LibraryScan : AggregateRoot /// /// Cancels the media library scan. /// - /// An representing either a successful operation, or an error. - public ErrorOr CancelScan() + /// An representing either a successful operation, or an error. + public Result CancelScan() { if (Status == LibraryScanJobStatus.Running) Status = LibraryScanJobStatus.Canceled; @@ -152,8 +152,8 @@ public class LibraryScan : AggregateRoot /// /// Marks the media library scan as failed. /// - /// An representing either a successful operation, or an error. - public ErrorOr FailScan() + /// An representing either a successful operation, or an error. + public Result FailScan() { if (Status == LibraryScanJobStatus.Running) Status = LibraryScanJobStatus.Failed; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs index d35e9c6b..e50f05f1 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System.Threading; using System.Threading.Tasks; @@ -19,13 +19,13 @@ public interface IMediaLibraryScanningService /// The type of the media library to be scanned. /// Whether the library permits downloading data from the web, or not. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, bool downloadMetadataFromWeb, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, bool downloadMetadataFromWeb, CancellationToken cancellationToken); /// /// Cancels . /// /// The scan to cancel. - /// An representing either a successful operation, or an error. - ErrorOr CancelScan(LibraryScan scan); + /// An representing either a successful operation, or an error. + Result CancelScan(LibraryScan scan); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs index 2c019b7e..2132a9da 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; @@ -57,12 +57,12 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService /// The type of the media library to be scanned. /// Whether the library permits downloading data from the web, or not. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, bool downloadMetadataFromWeb, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, bool downloadMetadataFromWeb, CancellationToken cancellationToken) { // mark the scan itself as started - ErrorOr startScanResult = scan.StartScan(); - if (startScanResult.IsError) + Result startScanResult = scan.StartScan(); + if (startScanResult.IsFailure) return startScanResult.Errors; foreach (IDomainEvent domainEvent in scan.GetDomainEvents()) @@ -103,8 +103,8 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService /// Cancels . /// /// The media library scan to cancel. - /// An representing either a successful operation, or an error. - public ErrorOr CancelScan(LibraryScan scan) + /// An representing either a successful operation, or an error. + public Result CancelScan(LibraryScan scan) { // trigger the process that cancels the jobs of the scan _mediaLibrariesScanCancellationTracker.CancelScan(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId)); diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/IMediaLibrariesScanProgressTracker.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/IMediaLibrariesScanProgressTracker.cs index be0333d2..1c64364d 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/IMediaLibrariesScanProgressTracker.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/IMediaLibrariesScanProgressTracker.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; #endregion @@ -17,16 +17,16 @@ public interface IMediaLibrariesScanProgressTracker /// The object representing the unique identifier of the media library being scanned. /// Model for tracking media library scans. /// The total number of jobs that this media library scan contains. - /// An representing either a successful operation, or an error. - ErrorOr InitializeScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId, int totalJobs); + /// An representing either a successful operation, or an error. + Result InitializeScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId, int totalJobs); /// /// Updates the progress tracking of the media library scan by incrementing the number of completed scan jobs. /// /// The object representing the unique identifier of the media library being scanned. /// Model for tracking media library scans. - /// An representing either a successful operation, or an error. - ErrorOr UpdateScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId); + /// An representing either a successful operation, or an error. + Result UpdateScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId); /// /// Updates the progress tracking of the media library scan by incrementing the number of completed items of a scan job. @@ -34,24 +34,24 @@ public interface IMediaLibrariesScanProgressTracker /// The object representing the unique identifier of the media library being scanned. /// Model for tracking media library scans. /// The object representing the progress of the media library scan job. - /// An representing either a successful operation, or an error. - ErrorOr UpdateScanJobProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId, MediaLibraryScanJobProgress progress); + /// An representing either a successful operation, or an error. + Result UpdateScanJobProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId, MediaLibraryScanJobProgress progress); /// /// Gets the progress of a media library scan. /// /// Model for tracking media library scans. /// - /// An containing either a , or an error message. + /// An containing either a , or an error message. /// - ErrorOr GetScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId); + Result GetScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId); /// /// Removes the progress of a media library scan. /// /// Model for tracking media library scans. /// - /// An containing either a , or an error message. + /// An containing either a , or an error message. /// - ErrorOr RemoveScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId); + Result RemoveScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTracker.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTracker.cs index 2c5f36f8..2f604053 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTracker.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTracker.cs @@ -1,10 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System.Collections.Concurrent; #endregion @@ -23,14 +22,14 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr /// The object representing the unique identifier of the media library being scanned. /// Model for tracking media library scans. /// The total number of jobs that this media library scan contains. - /// An representing either a successful operation, or an error. - public ErrorOr InitializeScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId, int totalJobs) + /// An representing either a successful operation, or an error. + public Result InitializeScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId, int totalJobs) { - ErrorOr createLibraryScanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 0, "Initializing"); - if (createLibraryScanJobProgressResult.IsError) + Result createLibraryScanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 0, "Initializing"); + if (createLibraryScanJobProgressResult.IsFailure) return createLibraryScanJobProgressResult.Errors; - ErrorOr createScanProgressResult = MediaLibraryScanProgress.Create( + Result createScanProgressResult = MediaLibraryScanProgress.Create( mediaLibraryScanCompositeId.ScanId, mediaLibraryScanCompositeId.UserId, libraryId, @@ -39,7 +38,7 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr LibraryScanJobStatus.Pending, Optional.Some(createLibraryScanJobProgressResult.Value) ); - if (createScanProgressResult.IsError) + if (createScanProgressResult.IsFailure) return createScanProgressResult.Errors; _scanProgresses[mediaLibraryScanCompositeId] = createScanProgressResult.Value; @@ -52,12 +51,12 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr /// /// The object representing the unique identifier of the media library being scanned. /// Model for tracking media library scans. - /// An representing either a successful operation, or an error. - public ErrorOr UpdateScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId) + /// An representing either a successful operation, or an error. + public Result UpdateScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId) { if (_scanProgresses.TryGetValue(mediaLibraryScanCompositeId, out MediaLibraryScanProgress? progress)) { - ErrorOr createScanProgressResult = MediaLibraryScanProgress.Create( + Result createScanProgressResult = MediaLibraryScanProgress.Create( mediaLibraryScanCompositeId.ScanId, mediaLibraryScanCompositeId.UserId, libraryId, @@ -66,7 +65,7 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr progress.CompletedJobs + 1 == progress.TotalJobs ? LibraryScanJobStatus.Completed : LibraryScanJobStatus.Running, progress.CurrentJobProgress ); - if (createScanProgressResult.IsError) + if (createScanProgressResult.IsFailure) return createScanProgressResult.Errors; _scanProgresses[mediaLibraryScanCompositeId] = createScanProgressResult.Value; @@ -80,12 +79,12 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr /// The object representing the unique identifier of the media library being scanned. /// Model for tracking media library scans. /// The object representing the progress of the media library scan job. - /// An representing either a successful operation, or an error. - public ErrorOr UpdateScanJobProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId, MediaLibraryScanJobProgress progress) + /// An representing either a successful operation, or an error. + public Result UpdateScanJobProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId, MediaLibraryScanJobProgress progress) { if (_scanProgresses.TryGetValue(mediaLibraryScanCompositeId, out MediaLibraryScanProgress? scanProgress)) { - ErrorOr createScanProgressResult = MediaLibraryScanProgress.Create( + Result createScanProgressResult = MediaLibraryScanProgress.Create( mediaLibraryScanCompositeId.ScanId, mediaLibraryScanCompositeId.UserId, libraryId, @@ -94,7 +93,7 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr scanProgress.Status, Optional.Some(progress) ); - if (createScanProgressResult.IsError) + if (createScanProgressResult.IsFailure) return createScanProgressResult.Errors; _scanProgresses[mediaLibraryScanCompositeId] = createScanProgressResult.Value; @@ -108,9 +107,9 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr /// /// Model for tracking media library scans. /// - /// An containing either a , or an error message. + /// An containing either a , or an error message. /// - public ErrorOr GetScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId) + public Result GetScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId) { if (_scanProgresses.TryGetValue(mediaLibraryScanCompositeId, out MediaLibraryScanProgress? progress)) return progress; @@ -122,9 +121,9 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr /// /// Model for tracking media library scans. /// - /// An containing either a , or an error message. + /// An containing either a , or an error message. /// - public ErrorOr RemoveScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId) + public Result RemoveScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId) { if (_scanProgresses.TryRemove(mediaLibraryScanCompositeId, out MediaLibraryScanProgress? progress)) return progress; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanJobProgress.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanJobProgress.cs index 4a463844..72673403 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanJobProgress.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanJobProgress.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using System.Collections.Generic; using System.Diagnostics; @@ -54,9 +54,9 @@ public sealed class MediaLibraryScanJobProgress : ValueObject /// The total number of items of the media library scan job. /// The current operation being performed by the media library scan job. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create(int completedItems, int totalItems, string currentOperation) + public static Result Create(int completedItems, int totalItems, string currentOperation) { if (totalItems < 0) return Errors.LibraryScanning.TotalScanJobItemsCountMustBePositive; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs index 5050f0b4..868357cf 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs @@ -1,11 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System.Collections.Generic; using System.Diagnostics; #endregion @@ -97,9 +96,9 @@ public sealed class MediaLibraryScanProgress : ValueObject /// The status of the media library scan. /// The optional current job progress of the media library scan. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( ScanId scanId, UserId userId, LibraryId libraryId, diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributor.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributor.cs index 52252ab0..4794bb2a 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributor.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributor.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; @@ -68,7 +67,7 @@ public class MediaContributor : AggregateRoot /// /// The name of the contributor. /// The created instance. - public static ErrorOr Create(MediaContributorName name) + public static Result Create(MediaContributorName name) { // TODO: enforce invariants throw new NotImplementedException(); @@ -81,7 +80,7 @@ public class MediaContributor : AggregateRoot /// The unique identifier of the contributor. /// The name of the contributor. /// The created instance. - public static ErrorOr Create( + public static Result Create( MediaContributorId id, MediaContributorName name, MediaContributorRole role, diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/ContributorName.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/ContributorName.cs index 902cc27e..4677e699 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/ContributorName.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/ContributorName.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; @@ -41,7 +40,7 @@ public sealed class MediaContributorName : ValueObject /// The name by which the contributor is popularly known. /// The legal name of the contributor. /// The created instance. - public static ErrorOr Create(string displayName, Optional legalName) + public static Result Create(string displayName, Optional legalName) { // TODO: enforce invariants return new MediaContributorName(displayName, legalName); diff --git a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/User.cs b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/User.cs index d70f771d..4944217c 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/User.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/User.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using System.Diagnostics; @@ -33,9 +33,9 @@ public sealed class User : AggregateRoot /// /// The username of the user. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create(string username) + public static Result Create(string username) { return new User(UserId.CreateUnique(), username); } @@ -46,9 +46,9 @@ public sealed class User : AggregateRoot /// The object representing the unique identifier of the user. /// The username of the user. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create(UserId id, string username) + public static Result Create(UserId id, string username) { return new User(id, username); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Movie.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Movie.cs index e7d163e2..c2160a53 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Movie.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Movie.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; @@ -56,7 +56,7 @@ public sealed class Movie : Entity /// The list of media contributors of the movie. /// The list of ratings for the movie. /// The created . - public static ErrorOr Create(VideoMetadata metadata, List contributors, List ratings) + public static Result Create(VideoMetadata metadata, List contributors, List ratings) { // TODO: enforce invariants return new Movie(MovieId.CreateUnique(), metadata, contributors, ratings); @@ -70,7 +70,7 @@ public sealed class Movie : Entity /// The list of media contributors of the movie. /// The list of ratings for the movie. /// The created . - public static ErrorOr Create(MovieId id, VideoMetadata metadata, List contributors, List ratings) + public static Result Create(MovieId id, VideoMetadata metadata, List contributors, List ratings) { // TODO: enforce invariants return new Movie(id, metadata, contributors, ratings); diff --git a/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs index 23eff432..6bf2b187 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using System; @@ -96,9 +95,9 @@ public class VideoMetadata : BaseMetadata /// The genres of the video. /// The tags associated with the video. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( string title, Optional originalTitle, int durationInSeconds, @@ -128,4 +127,4 @@ public class VideoMetadata : BaseMetadata yield return VideoCodec; yield return AudioCodec; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Entities/BookSeries.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Entities/BookSeries.cs index 20fadd53..80245f37 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Entities/BookSeries.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Entities/BookSeries.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using System.Collections.Generic; @@ -56,9 +56,9 @@ public sealed class BookSeries : Entity /// The current status of the book series. /// The books of the book series. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( BookSeriesId id, WrittenContentMetadata metadata, bool isComplete, @@ -80,9 +80,9 @@ public sealed class BookSeries : Entity /// The current status of the book series. /// The books of the book series. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( WrittenContentMetadata metadata, bool isComplete, List books) @@ -99,8 +99,8 @@ public sealed class BookSeries : Entity /// Adds a book to the series. /// /// The book to be added. - /// An representing either a successful operation, or an error. - public ErrorOr AddBook(Book book) + /// An representing either a successful operation, or an error. + public Result AddBook(Book book) { if (_books.Contains(book)) return Errors.WrittenContent.TheBookIsAlreadyInTheSeries; @@ -112,8 +112,8 @@ public sealed class BookSeries : Entity /// Removes a book from the series. /// /// The book to be removed. - /// An representing either a successful operation, or an error. - public ErrorOr RemoveBook(Book book) + /// An representing either a successful operation, or an error. + public Result RemoveBook(Book book) { if (!_books.Contains(book)) return Errors.WrittenContent.TheBookIsNotInTheSeries; diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryId.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryId.cs index 4d855c5a..97a9b1f4 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryId.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Models.Core; using System; using System.Collections.Generic; @@ -26,7 +26,7 @@ public sealed class BookLibraryId : EntityId // TODO: to be removed /// Creates a new instance of the class. /// /// The created instance. - public static ErrorOr CreateUnique() + public static Result CreateUnique() { // TODO: enforce invariants return new BookLibraryId(Guid.NewGuid()); @@ -37,7 +37,7 @@ public sealed class BookLibraryId : EntityId // TODO: to be removed /// /// The value used to create the instance. /// The created instance. - public static ErrorOr Create(Guid value) + public static Result Create(Guid value) { // TODO: enforce invariants return new BookLibraryId(value); diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRating.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRating.cs index 8ad4797f..54518548 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRating.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRating.cs @@ -1,9 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System.Collections.Generic; using System.Diagnostics; #endregion @@ -42,9 +41,9 @@ public class BookRating : Rating /// The optional source of the rating. /// The optional number of votes or reviews. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create(decimal value, decimal maxValue, Optional source, Optional voteCount) + public static Result Create(decimal value, decimal maxValue, Optional source, Optional voteCount) { if (maxValue < 0 || value < 0) return Errors.Metadata.RatingValueMustBePositive; diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/Isbn.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/Isbn.cs index eff0ca46..ce5cbdba 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/Isbn.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/Isbn.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using System.Collections.Generic; using System.Diagnostics; @@ -46,7 +46,7 @@ public sealed class Isbn : ValueObject /// The value representing this object. /// The format of the ISBN representing this object. /// The created instance. - public static ErrorOr Create(string? value, IsbnFormat format) + public static Result Create(string? value, IsbnFormat format) { // enforce invariants if (string.IsNullOrWhiteSpace(value)) diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs index b1452946..6f47ad70 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs @@ -1,6 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using System.Collections.Generic; @@ -69,9 +67,9 @@ public class WrittenContentMetadata : BaseMetadata /// The publisher of the written content, if applicable. /// The number of pages in the written content, if applicable. /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( + public static Result Create( string title, Optional originalTitle, Optional description, diff --git a/src/Lumina.Domain/Lumina.Domain.csproj b/src/Lumina.Domain/Lumina.Domain.csproj index bff52acd..7c45fad6 100644 --- a/src/Lumina.Domain/Lumina.Domain.csproj +++ b/src/Lumina.Domain/Lumina.Domain.csproj @@ -14,7 +14,6 @@ - diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs index 493f5595..a2625302 100644 --- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion namespace Lumina.Infrastructure.Common.Errors; diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.LibraryScanning.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.LibraryScanning.cs index 29538e04..40653d00 100644 --- a/src/Lumina.Infrastructure/Common/Errors/Errors.LibraryScanning.cs +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.LibraryScanning.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; #endregion namespace Lumina.Infrastructure.Common.Errors; diff --git a/src/Lumina.Infrastructure/Common/Validation/ValidationOptions.cs b/src/Lumina.Infrastructure/Common/Validation/ValidationOptions.cs index d7018a30..e6a87a75 100644 --- a/src/Lumina.Infrastructure/Common/Validation/ValidationOptions.cs +++ b/src/Lumina.Infrastructure/Common/Validation/ValidationOptions.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.Infrastructure.Validation; using Microsoft.Extensions.Options; using System; diff --git a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs index 0b6422ee..be8a5cd3 100644 --- a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs +++ b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; @@ -7,7 +7,7 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory; using System; using System.Collections.Generic; @@ -46,8 +46,8 @@ public class AuthorizationService : IAuthorizationService /// if the user has the specified permission, otherwise. public async Task HasPermissionAsync(Guid userId, AuthorizationPermission permission, CancellationToken cancellationToken) { - ErrorOr getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); - if (getUserResult.IsError || getUserResult.Value is null) + Result getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsFailure || getUserResult.Value is null) return false; // check if the user has the permission directly @@ -68,8 +68,8 @@ public class AuthorizationService : IAuthorizationService /// if the user is in the specified role, otherwise. public async Task IsInRoleAsync(Guid userId, string role, CancellationToken cancellationToken) { - ErrorOr getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); - if (getUserResult.IsError || getUserResult.Value is null) + Result getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsFailure || getUserResult.Value is null) return false; return getUserResult.Value.UserRole?.Role.RoleName == role; } @@ -93,12 +93,12 @@ public class AuthorizationService : IAuthorizationService /// /// The id of the user for whom to retrieve the authorization roles and permissions. /// Cancellation token that can be used to stop the execution. - /// An containing either a , or an error. - public async Task> GetUserAuthorizationAsync(Guid userId, CancellationToken cancellationToken) + /// An containing either a , or an error. + public async Task> GetUserAuthorizationAsync(Guid userId, CancellationToken cancellationToken) { - ErrorOr getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); - if (getUserResult.IsError) + if (getUserResult.IsFailure) return getUserResult.Errors; if (getUserResult.Value is null) diff --git a/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs b/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs index 4a1a6008..9ce98ec6 100644 --- a/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs +++ b/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; @@ -39,8 +39,8 @@ public class Over18Policy : IOver18Policy /// if the policy evaluation succeeds, otherwise. public async Task EvaluateAsync(Guid userId, CancellationToken cancellationToken) { - ErrorOr getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); - if (getUserResult.IsError || getUserResult.Value is null) + Result getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsFailure || getUserResult.Value is null) return false; // TODO: uncomment when Date of Birth is implemented for users registration diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs index 2b4d92cd..97931b63 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; @@ -64,18 +64,18 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // set the initial progress of the scan job, it's a 1 step job - comparing the discovered files against the media library scan snapshot - ErrorOr publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); // mark the staging results against the media library scan snapshot of the previous scan - ErrorOr markChangesResult = await stagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (markChangesResult.IsError) + Result markChangesResult = await stagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (markChangesResult.IsFailure) throw new InvalidOperationException(markChangesResult.FirstError.Description); // increment the number of processed elements progress publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) + if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); // this job finished, increment the number of processed jobs progress @@ -108,11 +108,11 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra /// The current job progress. /// The total job progress. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) { - ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ComparingFileHashes"); - if (scanJobProgressResult.IsError) + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ComparingFileHashes"); + if (scanJobProgressResult.IsFailure) return scanJobProgressResult.Errors; await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs index 418be23c..c983bcc9 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Security; @@ -69,14 +69,14 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // count the files that need hashing, for progress reporting purposes - ErrorOr getFilesToHashCountResult = await stagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); - if (getFilesToHashCountResult.IsError) + Result getFilesToHashCountResult = await stagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getFilesToHashCountResult.IsFailure) throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description); int totalFilesToHash = getFilesToHashCountResult.Value; // set the initial progress of the scan job - ErrorOr publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); DateTime lastUpdateTime = DateTime.UtcNow; @@ -89,8 +89,8 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra { cancellationToken.ThrowIfCancellationRequested(); - ErrorOr> getFilesToHashPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false); - if (getFilesToHashPageResult.IsError) + Result> getFilesToHashPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getFilesToHashPageResult.IsFailure) throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description); IReadOnlyList filesToHashPage = getFilesToHashPageResult.Value; if (filesToHashPage.Count == 0) @@ -105,15 +105,15 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra { // increment the number of processed elements progress publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) + if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); lastUpdateTime = now; } }, cancellationToken).ConfigureAwait(false); // write the computed hashes back to the staging results - ErrorOr updateHashesResult = await stagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false); - if (updateHashesResult.IsError) + Result updateHashesResult = await stagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false); + if (updateHashesResult.IsFailure) throw new InvalidOperationException(updateHashesResult.FirstError.Description); lastPath = filesToHashPage[^1].Path; @@ -149,11 +149,11 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra /// The current job progress. /// The total job progress. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) { - ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "HashingFileContents"); - if (scanJobProgressResult.IsError) + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "HashingFileContents"); + if (scanJobProgressResult.IsFailure) return scanJobProgressResult.Errors; await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs index 07fa670c..bd152ae3 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Books; @@ -81,8 +81,8 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // get the metadata providers configured for the media library, in their configured order, that support the media library type - ErrorOr> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getConfigurationsResult.IsError) + Result> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) throw new InvalidOperationException(getConfigurationsResult.FirstError.Description); List providers = []; foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) @@ -96,14 +96,14 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo } // count the books that need their metadata enriched, for progress reporting purposes - ErrorOr getBooksToEnrichCountResult = await bookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getBooksToEnrichCountResult.IsError) + Result getBooksToEnrichCountResult = await bookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getBooksToEnrichCountResult.IsFailure) throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); int totalBooksToEnrich = getBooksToEnrichCountResult.Value; // set the initial progress of the scan job - ErrorOr publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); DateTime lastUpdateTime = DateTime.UtcNow; @@ -116,8 +116,8 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo { cancellationToken.ThrowIfCancellationRequested(); - ErrorOr> getBooksPageResult = await bookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); - if (getBooksPageResult.IsError) + Result> getBooksPageResult = await bookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getBooksPageResult.IsFailure) throw new InvalidOperationException(getBooksPageResult.FirstError.Description); IReadOnlyList booksPage = getBooksPageResult.Value; if (booksPage.Count == 0) @@ -135,7 +135,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo { // increment the number of processed elements progress publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) + if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); lastUpdateTime = now; } @@ -178,8 +178,8 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo private static async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList providers, IBookRepository bookRepository, CancellationToken cancellationToken) { // convert the book to a domain object - ErrorOr getBookResult = bookEntity.ToDomainEntity(); - if (getBookResult.IsError) + Result getBookResult = bookEntity.ToDomainEntity(); + if (getBookResult.IsFailure) return; Book book = getBookResult.Value; @@ -202,12 +202,12 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata)) continue; - ErrorOr applyMetadataResult = book.ApplyMetadata(bookMetadata, provider.Name, DateTime.UtcNow); - if (applyMetadataResult.IsError) + Result applyMetadataResult = book.ApplyMetadata(bookMetadata, provider.Name, DateTime.UtcNow); + if (applyMetadataResult.IsFailure) continue; - ErrorOr updateBookResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); - if (updateBookResult.IsError) + Result updateBookResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateBookResult.IsFailure) continue; return; @@ -247,11 +247,11 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo /// The current job progress. /// The total job progress. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) { - ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "EnrichingMetadata"); - if (scanJobProgressResult.IsError) + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "EnrichingMetadata"); + if (scanJobProgressResult.IsFailure) return scanJobProgressResult.Errors; await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs index 1053b7ab..7513b0e5 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; @@ -71,18 +71,18 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // set the initial progress of the scan job, it's a 1 step job - applying the scan results to the storage medium - ErrorOr publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); // get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them - ErrorOr> getDeletedPathsResult = await libraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false); - if (getDeletedPathsResult.IsError) + Result> getDeletedPathsResult = await libraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getDeletedPathsResult.IsFailure) throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description); // apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan - ErrorOr applySnapshotSwapResult = await libraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false); - if (applySnapshotSwapResult.IsError) + Result applySnapshotSwapResult = await libraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false); + if (applySnapshotSwapResult.IsFailure) throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description); // raise a deletion event for every media library scan snapshot item that is no longer present on disk @@ -93,29 +93,29 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed } // materialize the books of the media library from the scan snapshot, so that they are browsable even without web metadata - ErrorOr> getPathsResult = await libraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getPathsResult.IsError) + Result> getPathsResult = await libraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getPathsResult.IsFailure) throw new InvalidOperationException(getPathsResult.FirstError.Description); IBookRepository bookRepository = unitOfWork.GetRepository(); foreach (string path in getPathsResult.Value) { cancellationToken.ThrowIfCancellationRequested(); - ErrorOr getExistingBookResult = await bookRepository.GetByPathAsync(LibraryId.Value, path, cancellationToken).ConfigureAwait(false); - if (getExistingBookResult.IsError) + Result getExistingBookResult = await bookRepository.GetByPathAsync(LibraryId.Value, path, cancellationToken).ConfigureAwait(false); + if (getExistingBookResult.IsFailure) throw new InvalidOperationException(getExistingBookResult.FirstError.Description); if (getExistingBookResult.Value is not null) continue; - ErrorOr insertBookResult = await bookRepository.InsertAsync(CreateShellBookEntity(LibraryId.Value, path), cancellationToken).ConfigureAwait(false); - if (insertBookResult.IsError) + Result insertBookResult = await bookRepository.InsertAsync(CreateShellBookEntity(LibraryId.Value, path), cancellationToken).ConfigureAwait(false); + if (insertBookResult.IsFailure) throw new InvalidOperationException(insertBookResult.FirstError.Description); } await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // increment the number of processed elements progress publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) + if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); Status = LibraryScanJobStatus.Completed; @@ -149,11 +149,11 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed /// The current job progress. /// The total job progress. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) { - ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "SavingScanData"); - if (scanJobProgressResult.IsError) + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "SavingScanData"); + if (scanJobProgressResult.IsFailure) return scanJobProgressResult.Errors; await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs index cfe925dc..86af2b48 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; @@ -86,28 +86,28 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // get the library from the repository - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsError || getLibraryResult.Value is null) - throw new InvalidOperationException(getLibraryResult.IsError ? getLibraryResult.FirstError.Description : "The media library was not found."); + Result getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); // convert it to a domain object - ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); - if (domainLibraryResult.IsError) + Result domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsFailure) throw new InvalidOperationException(domainLibraryResult.FirstError.Description); // when the fast skip is enabled, load the directory scan fingerprints of the library, used to skip the directories that have not changed since the last scan Dictionary? fingerprintsByPath = null; if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan) { - ErrorOr> getFingerprintsResult = await directoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getFingerprintsResult.IsError) + Result> getFingerprintsResult = await directoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getFingerprintsResult.IsFailure) throw new InvalidOperationException(getFingerprintsResult.FirstError.Description); fingerprintsByPath = getFingerprintsResult.Value; } // set the initial progress of the scan job - ErrorOr publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1); @@ -139,7 +139,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF { publishJobProgressResult = await PublishJobProgressAsync( domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) + if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); lastHeartbeat = now; } @@ -148,14 +148,14 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF // flush any remaining discovered files and directory scan fingerprints that did not reach the batch size if (stagingBatch.Count > 0) { - ErrorOr insertResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); - if (insertResult.IsError) + Result insertResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); + if (insertResult.IsFailure) throw new InvalidOperationException(insertResult.FirstError.Description); } if (fingerprintBatch.Count > 0) { - ErrorOr upsertResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false); - if (upsertResult.IsError) + Result upsertResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) throw new InvalidOperationException(upsertResult.FirstError.Description); } @@ -235,8 +235,8 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF // flush the collected directory scan fingerprints in bounded batches, so that the memory usage stays proportional to the batch size, no matter how many directories the library has if (fingerprintBatch.Count >= STAGING_BATCH_SIZE) { - ErrorOr upsertFingerprintsResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false); - if (upsertFingerprintsResult.IsError) + Result upsertFingerprintsResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false); + if (upsertFingerprintsResult.IsFailure) throw new InvalidOperationException(upsertFingerprintsResult.FirstError.Description); fingerprintBatch.Clear(); } @@ -275,8 +275,8 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF }); if (stagingBatch.Count >= STAGING_BATCH_SIZE) { - ErrorOr insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); - if (insertBatchResult.IsError) + Result insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); + if (insertBatchResult.IsFailure) throw new InvalidOperationException(insertBatchResult.FirstError.Description); stagingBatch.Clear(); } @@ -326,11 +326,11 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF /// The current job progress. /// The total job progress. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) { - ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "DiscoveringFiles"); - if (scanJobProgressResult.IsError) + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "DiscoveringFiles"); + if (scanJobProgressResult.IsFailure) return scanJobProgressResult.Errors; await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifier.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifier.cs index ea1bf1c7..a06de708 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifier.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifier.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using DebounceThrottle; -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Progress; using Lumina.Contracts.Responses.MediaLibrary.Management; @@ -54,8 +54,8 @@ public sealed class DebouncedMediaLibraryScanProgressNotifier : IMediaLibrarySca if (cancellationToken.IsCancellationRequested) return; - ErrorOr progressResult = _mediaLibrariesScanProgressTracker.GetScanProgress(mediaLibraryScanCompositeId); - if (progressResult.IsError) + Result progressResult = _mediaLibrariesScanProgressTracker.GetScanProgress(mediaLibraryScanCompositeId); + if (progressResult.IsFailure) return; MediaLibraryScanProgressResponse progress = progressResult.Value.ToResponse(); @@ -72,11 +72,11 @@ public sealed class DebouncedMediaLibraryScanProgressNotifier : IMediaLibrarySca { if (cancellationToken.IsCancellationRequested) return; - ErrorOr progressResult = _mediaLibrariesScanProgressTracker.RemoveScanProgress(mediaLibraryScanCompositeId); + Result progressResult = _mediaLibrariesScanProgressTracker.RemoveScanProgress(mediaLibraryScanCompositeId); CleanupDebouncer(mediaLibraryScanCompositeId); - if (!progressResult.IsError) + if (!progressResult.IsFailure) { MediaLibraryScanProgressResponse progress = progressResult.Value.ToResponse(); await _hubContext.Clients.Group(mediaLibraryScanCompositeId.ToString()).SendAsync( @@ -93,11 +93,11 @@ public sealed class DebouncedMediaLibraryScanProgressNotifier : IMediaLibrarySca { if (cancellationToken.IsCancellationRequested) return; - ErrorOr progressResult = _mediaLibrariesScanProgressTracker.RemoveScanProgress(mediaLibraryScanCompositeId); + Result progressResult = _mediaLibrariesScanProgressTracker.RemoveScanProgress(mediaLibraryScanCompositeId); CleanupDebouncer(mediaLibraryScanCompositeId); - if (!progressResult.IsError) + if (!progressResult.IsFailure) { MediaLibraryScanProgressResponse progress = progressResult.Value.ToResponse(); await _hubContext.Clients.Group(mediaLibraryScanCompositeId.ToString()).SendAsync( diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs index 25f0ab67..b8aa903e 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; @@ -66,8 +66,8 @@ internal sealed class PluginDetectionSyncJob : BackgroundService CreatedBy = default, UpdatedBy = default }; - ErrorOr upsertResult = await pluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false); - if (upsertResult.IsError) + Result upsertResult = await pluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false); + if (upsertResult.IsFailure) _logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", plugin.Name, upsertResult.FirstError.Description); } diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs index d0ef241b..6eb5a33f 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; @@ -37,8 +37,8 @@ internal sealed class PluginSettingsStore : IPluginSettingsStore public async Task?> GetSettingsAsync(Guid pluginId, CancellationToken cancellationToken) { IPluginRepository pluginRepository = _unitOfWork.GetRepository(); - ErrorOr getPluginResult = await pluginRepository.GetByIdAsync(pluginId, cancellationToken).ConfigureAwait(false); - if (getPluginResult.IsError) + Result getPluginResult = await pluginRepository.GetByIdAsync(pluginId, cancellationToken).ConfigureAwait(false); + if (getPluginResult.IsFailure) { _logger.LogWarning("Failed to read the settings of the plugin with Id '{PluginId}': {Error}", pluginId, getPluginResult.FirstError.Description); return null; diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpoint.cs index 30f5c9e4..130ad1d5 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpoint.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Permissions /// public class GetPermissionsEndpoint : BaseEndpoint { - private readonly IQueryHandler>> _getPermissionsQueryHandler; + private readonly IQueryHandler>> _getPermissionsQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get permissions queries. - public GetPermissionsEndpoint(IQueryHandler>> getPermissionsQueryHandler) + public GetPermissionsEndpoint(IQueryHandler>> getPermissionsQueryHandler) { _getPermissionsQueryHandler = getPermissionsQueryHandler; } @@ -47,7 +47,7 @@ public class GetPermissionsEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr> result = await _getPermissionsQueryHandler.HandleAsync(new GetPermissionsQuery(), cancellationToken).ConfigureAwait(false); + Result> result = await _getPermissionsQueryHandler.HandleAsync(new GetPermissionsQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs index d8754a30..8d0bd33a 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.AddRo /// public class AddRoleEndpoint : BaseEndpoint { - private readonly ICommandHandler> _addRoleCommandHandler; + private readonly ICommandHandler> _addRoleCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling add role commands. - public AddRoleEndpoint(ICommandHandler> addRoleCommandHandler) + public AddRoleEndpoint(ICommandHandler> addRoleCommandHandler) { _addRoleCommandHandler = addRoleCommandHandler; } @@ -48,7 +48,7 @@ public class AddRoleEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(AddRoleRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _addRoleCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _addRoleCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs index 16f7d9b9..e3a6dc87 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; @@ -18,13 +18,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.Delet /// public class DeleteRoleEndpoint : BaseEndpoint { - private readonly ICommandHandler> _deleteRoleCommandHandler; + private readonly ICommandHandler> _deleteRoleCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling delete role commands. - public DeleteRoleEndpoint(ICommandHandler> deleteRoleCommandHandler) + public DeleteRoleEndpoint(ICommandHandler> deleteRoleCommandHandler) { _deleteRoleCommandHandler = deleteRoleCommandHandler; } @@ -47,7 +47,7 @@ public class DeleteRoleEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(DeleteRoleRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _deleteRoleCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _deleteRoleCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.NoContent(), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs index bf158a74..32a95a2e 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.GetRo /// public class GetRolePermissionsEndpoint : BaseEndpoint { - private readonly IQueryHandler> _addRoleQueryHandler; + private readonly IQueryHandler> _addRoleQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling add role commands. - public GetRolePermissionsEndpoint(IQueryHandler> addRoleQueryHandler) + public GetRolePermissionsEndpoint(IQueryHandler> addRoleQueryHandler) { _addRoleQueryHandler = addRoleQueryHandler; } @@ -48,7 +48,7 @@ public class GetRolePermissionsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetRolePermissionsRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _addRoleQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result result = await _addRoleQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpoint.cs index 836acc82..1bf4de5b 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpoint.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.GetRo /// public class GetRolesEndpoint : BaseEndpoint { - private readonly IQueryHandler>> _getRolesQueryHandler; + private readonly IQueryHandler>> _getRolesQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get roles queries. - public GetRolesEndpoint(IQueryHandler>> getRolesQueryHandler) + public GetRolesEndpoint(IQueryHandler>> getRolesQueryHandler) { _getRolesQueryHandler = getRolesQueryHandler; } @@ -47,7 +47,7 @@ public class GetRolesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr> result = await _getRolesQueryHandler.HandleAsync(new GetRolesQuery(), cancellationToken).ConfigureAwait(false); + Result> result = await _getRolesQueryHandler.HandleAsync(new GetRolesQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpoint.cs index 375918d8..712c7b23 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpoint.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.Updat /// public class UpdateRoleEndpoint : BaseEndpoint { - private readonly ICommandHandler> _updateRoleCommandHandler; + private readonly ICommandHandler> _updateRoleCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling update role commands. - public UpdateRoleEndpoint(ICommandHandler> updateRoleCommandHandler) + public UpdateRoleEndpoint(ICommandHandler> updateRoleCommandHandler) { _updateRoleCommandHandler = updateRoleCommandHandler; } @@ -48,7 +48,7 @@ public class UpdateRoleEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdateRoleRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _updateRoleCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _updateRoleCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs index baad5781..2074be09 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; using Lumina.Presentation.Api.Common.Http; using Microsoft.AspNetCore.Http; using System.Collections.Generic; diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs index a029dc4d..1830b5e7 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs @@ -1,17 +1,18 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; -using Lumina.Contracts.Requests.FileSystemManagement.Directories; using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using Lumina.Contracts.Responses.FileSystemManagement.Directories; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using System.Collections.Generic; -using Lumina.Contracts.Responses.FileSystemManagement.Directories; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; @@ -21,13 +22,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directorie /// public class GetDirectoriesEndpoint : BaseEndpoint { - private readonly IQueryHandler>> _getDirectoriesQueryHandler; + private readonly IQueryHandler>> _getDirectoriesQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get directories queries. - public GetDirectoriesEndpoint(IQueryHandler>> getDirectoriesQueryHandler) + public GetDirectoriesEndpoint(IQueryHandler>> getDirectoriesQueryHandler) { _getDirectoriesQueryHandler = getDirectoriesQueryHandler; } @@ -37,7 +38,7 @@ public class GetDirectoriesEndpoint : BaseEndpoint public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Directories.GET_DIRECTORIES); Version(1); DontCatchExceptions(); @@ -50,7 +51,7 @@ public class GetDirectoriesEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetDirectoriesRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _getDirectoriesQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result> result = await _getDirectoriesQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpoint.cs index 270c61be..250491b6 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpoint.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.Get /// public class GetDrivesEndpoint : BaseEndpoint { - private readonly IQueryHandler>> _getDrivesQueryHandler; + private readonly IQueryHandler>> _getDrivesQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get drives queries. - public GetDrivesEndpoint(IQueryHandler>> getDrivesQueryHandler) + public GetDrivesEndpoint(IQueryHandler>> getDrivesQueryHandler) { _getDrivesQueryHandler = getDrivesQueryHandler; } @@ -35,7 +35,7 @@ public class GetDrivesEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Drives.GET_DRIVES); Version(1); DontCatchExceptions(); @@ -47,7 +47,7 @@ public class GetDrivesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr> result = await _getDrivesQueryHandler.HandleAsync(new GetDrivesQuery(), cancellationToken).ConfigureAwait(false); + Result> result = await _getDrivesQueryHandler.HandleAsync(new GetDrivesQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpoint.cs index f82b41f1..535d0dac 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpoint.cs @@ -1,15 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.FileSystemManagement.Files; using Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; -using Lumina.Contracts.Requests.FileSystemManagement.Files; using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -37,7 +33,7 @@ public class GetTypeEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.FileSystem.GET_TYPES); Version(1); DontCatchExceptions(); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs index ff65bb6f..6c964381 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Files; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; using Lumina.Contracts.Requests.FileSystemManagement.Files; using Lumina.Contracts.Responses.FileSystemManagement.Files; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -20,13 +21,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetF /// public class GetFilesEndpoint : BaseEndpoint { - private readonly IQueryHandler>> _getFilesQueryHandler; + private readonly IQueryHandler>> _getFilesQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get files queries. - public GetFilesEndpoint(IQueryHandler>> getFilesQueryHandler) + public GetFilesEndpoint(IQueryHandler>> getFilesQueryHandler) { _getFilesQueryHandler = getFilesQueryHandler; } @@ -36,7 +37,7 @@ public class GetFilesEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Files.GET_FILES); Version(1); DontCatchExceptions(); @@ -49,7 +50,7 @@ public class GetFilesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetFilesRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _getFilesQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result> result = await _getFilesQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs index faf6b0d5..3983d847 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Files; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; using Lumina.Contracts.Requests.FileSystemManagement.Files; using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -20,13 +21,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetT /// public class GetTreeFilesEndpoint : BaseEndpoint { - private readonly IQueryHandler>> _getTreeFilesQueryHandler; + private readonly IQueryHandler>> _getTreeFilesQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get tree files queries. - public GetTreeFilesEndpoint(IQueryHandler>> getTreeFilesQueryHandler) + public GetTreeFilesEndpoint(IQueryHandler>> getTreeFilesQueryHandler) { _getTreeFilesQueryHandler = getTreeFilesQueryHandler; } @@ -36,7 +37,7 @@ public class GetTreeFilesEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Files.GET_TREE_FILES); Version(1); DontCatchExceptions(); @@ -49,7 +50,7 @@ public class GetTreeFilesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetTreeFilesRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _getTreeFilesQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result> result = await _getTreeFilesQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs index f4cc6448..e6509a27 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +20,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.Check /// public class CheckPathExistsEndpoint : BaseEndpoint { - private readonly IQueryHandler> _checkPathExistsQueryHandler; + private readonly IQueryHandler> _checkPathExistsQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling check path exists queries. - public CheckPathExistsEndpoint(IQueryHandler> checkPathExistsQueryHandler) + public CheckPathExistsEndpoint(IQueryHandler> checkPathExistsQueryHandler) { _checkPathExistsQueryHandler = checkPathExistsQueryHandler; } @@ -35,7 +36,7 @@ public class CheckPathExistsEndpoint : BaseEndpoint public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Path.CHECK_PATH_EXISTS); Version(1); DontCatchExceptions(); @@ -48,7 +49,7 @@ public class CheckPathExistsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(CheckPathExistsRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _checkPathExistsQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result result = await _checkPathExistsQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpoint.cs index 885b6664..8cc7e443 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpoint.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.Combi /// public class CombinePathEndpoint : BaseEndpoint { - private readonly ICommandHandler> _combinePathCommandHandler; + private readonly ICommandHandler> _combinePathCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling combine path commands. - public CombinePathEndpoint(ICommandHandler> combinePathCommandHandler) + public CombinePathEndpoint(ICommandHandler> combinePathCommandHandler) { _combinePathCommandHandler = combinePathCommandHandler; } @@ -48,7 +48,7 @@ public class CombinePathEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(CombinePathRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _combinePathCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _combinePathCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpoint.cs index 33d83018..f41e48f7 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpoint.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -20,13 +21,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPa /// public class GetPathParentEndpoint : BaseEndpoint { - private readonly IQueryHandler>> _getPathParentQueryHandler; + private readonly IQueryHandler>> _getPathParentQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get path parent queries. - public GetPathParentEndpoint(IQueryHandler>> getPathParentQueryHandler) + public GetPathParentEndpoint(IQueryHandler>> getPathParentQueryHandler) { _getPathParentQueryHandler = getPathParentQueryHandler; } @@ -36,7 +37,7 @@ public class GetPathParentEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Path.GET_PATH_PARENT); Version(1); DontCatchExceptions(); @@ -49,7 +50,7 @@ public class GetPathParentEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetPathParentRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _getPathParentQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result> result = await _getPathParentQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpoint.cs index fd31534e..34d22aad 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpoint.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +20,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPa /// public class GetPathRootEndpoint : BaseEndpoint { - private readonly IQueryHandler> _getPathRootQueryHandler; + private readonly IQueryHandler> _getPathRootQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get path root queries. - public GetPathRootEndpoint(IQueryHandler> getPathRootQueryHandler) + public GetPathRootEndpoint(IQueryHandler> getPathRootQueryHandler) { _getPathRootQueryHandler = getPathRootQueryHandler; } @@ -35,7 +36,7 @@ public class GetPathRootEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Path.GET_PATH_ROOT); Version(1); DontCatchExceptions(); @@ -48,7 +49,7 @@ public class GetPathRootEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetPathRootRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _getPathRootQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result result = await _getPathRootQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpoint.cs index 0d33f95a..4a80b900 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpoint.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; @@ -20,13 +20,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.Split /// public class SplitPathEndpoint : BaseEndpoint { - private readonly ICommandHandler>> _splitPathCommandHandler; + private readonly ICommandHandler>> _splitPathCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling split path commands. - public SplitPathEndpoint(ICommandHandler>> splitPathCommandHandler) + public SplitPathEndpoint(ICommandHandler>> splitPathCommandHandler) { _splitPathCommandHandler = splitPathCommandHandler; } @@ -49,7 +49,7 @@ public class SplitPathEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(SplitPathRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _splitPathCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result> result = await _splitPathCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpoint.cs index eded7fa9..c8cf8acb 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpoint.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +20,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.Valid /// public class ValidatePathEndpoint : BaseEndpoint { - private readonly IQueryHandler> _validatePathQueryHandler; + private readonly IQueryHandler> _validatePathQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling validate path queries. - public ValidatePathEndpoint(IQueryHandler> validatePathQueryHandler) + public ValidatePathEndpoint(IQueryHandler> validatePathQueryHandler) { _validatePathQueryHandler = validatePathQueryHandler; } @@ -35,7 +36,7 @@ public class ValidatePathEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Path.VALIDATE); Version(1); DontCatchExceptions(); @@ -48,7 +49,7 @@ public class ValidatePathEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(ValidatePathRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _validatePathQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result result = await _validatePathQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs index 68ad8c74..91e37b15 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs @@ -1,11 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.FileSystemManagement.Files; using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails; using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; using Lumina.Presentation.Api.Common.Utilities; using Lumina.Presentation.Api.Core.Endpoints.Common; @@ -21,13 +22,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails /// public class GetThumbnailEndpoint : BaseEndpoint { - private readonly IQueryHandler> _getThumbnailQueryHandler; + private readonly IQueryHandler> _getThumbnailQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get thumbnail queries. - public GetThumbnailEndpoint(IQueryHandler> getThumbnailQueryHandler) + public GetThumbnailEndpoint(IQueryHandler> getThumbnailQueryHandler) { _getThumbnailQueryHandler = getThumbnailQueryHandler; } @@ -37,7 +38,7 @@ public class GetThumbnailEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Thumbnails.GET_THUMBNAIL); Version(1); DontCatchExceptions(); @@ -50,7 +51,7 @@ public class GetThumbnailEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetThumbnailRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _getThumbnailQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result result = await _getThumbnailQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.File(success.Bytes, MimeTypes.GetMimeType(success.Type)), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs index d9c9a336..f980f5c2 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.AddLibrary; /// public class AddLibraryEndpoint : BaseEndpoint { - private readonly ICommandHandler> _addLibraryCommandHandler; + private readonly ICommandHandler> _addLibraryCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling add library commands. - public AddLibraryEndpoint(ICommandHandler> addLibraryCommandHandler) + public AddLibraryEndpoint(ICommandHandler> addLibraryCommandHandler) { _addLibraryCommandHandler = addLibraryCommandHandler; } @@ -48,7 +48,7 @@ public class AddLibraryEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(AddLibraryRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _addLibraryCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _addLibraryCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Libraries.ADD_LIBRARY}/{result.Value.Id}", result.Value), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs index 7364d233..6b33c512 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; @@ -17,13 +17,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.CancelLibrar /// public class CancelLibrariesScanEndpoint : BaseEndpoint { - private readonly Lumina.Application.Common.CQRS.ICommandHandler> _cancelLibrariesScanCommandHandler; + private readonly Lumina.Application.Common.CQRS.ICommandHandler> _cancelLibrariesScanCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling cancel libraries scan commands. - public CancelLibrariesScanEndpoint(Lumina.Application.Common.CQRS.ICommandHandler> cancelLibrariesScanCommandHandler) + public CancelLibrariesScanEndpoint(Lumina.Application.Common.CQRS.ICommandHandler> cancelLibrariesScanCommandHandler) { _cancelLibrariesScanCommandHandler = cancelLibrariesScanCommandHandler; } @@ -33,7 +33,7 @@ public class CancelLibrariesScanEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.POST); + Verbs(Http.POST); Routes(ApiRoutes.Libraries.CANCEL_LIBRARIES_SCAN); Version(1); DontCatchExceptions(); @@ -45,7 +45,7 @@ public class CancelLibrariesScanEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr result = await _cancelLibrariesScanCommandHandler.HandleAsync(new CancelLibrariesScanCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _cancelLibrariesScanCommandHandler.HandleAsync(new CancelLibrariesScanCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.NoContent(), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs index 8d3c5549..9c60751c 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs @@ -1,10 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.Management; -using Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; using Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibraryScan; using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +18,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.CancelLibrar /// public class CancelLibraryScanEndpoint : BaseEndpoint { - private readonly ICommandHandler> _cancelLibraryScanCommandHandler; + private readonly ICommandHandler> _cancelLibraryScanCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling cancel library scan commands. - public CancelLibraryScanEndpoint(ICommandHandler> cancelLibraryScanCommandHandler) + public CancelLibraryScanEndpoint(ICommandHandler> cancelLibraryScanCommandHandler) { _cancelLibraryScanCommandHandler = cancelLibraryScanCommandHandler; } @@ -47,7 +46,7 @@ public class CancelLibraryScanEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(CancelLibraryScanRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _cancelLibraryScanCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _cancelLibraryScanCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.NoContent(), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs index 96ae891f..d3c1e824 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; -using Lumina.Application.Common.Mapping.MediaLibrary.Management; -using Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary; using System.Threading; using System.Threading.Tasks; #endregion @@ -18,13 +18,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.DeleteLibrar /// public class DeleteLibraryEndpoint : BaseEndpoint { - private readonly ICommandHandler> _deleteLibraryCommandHandler; + private readonly ICommandHandler> _deleteLibraryCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling delete library commands. - public DeleteLibraryEndpoint(ICommandHandler> deleteLibraryCommandHandler) + public DeleteLibraryEndpoint(ICommandHandler> deleteLibraryCommandHandler) { _deleteLibraryCommandHandler = deleteLibraryCommandHandler; } @@ -47,7 +47,7 @@ public class DeleteLibraryEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(DeleteLibraryRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _deleteLibraryCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _deleteLibraryCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpoint.cs index e1863623..d06966a9 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpoint.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibraries; using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -18,13 +18,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetEnabledLi /// public class GetEnabledLibrariesEndpoint : BaseEndpoint { - private readonly IQueryHandler> _getEnabledLibrariesQueryHandler; + private readonly IQueryHandler> _getEnabledLibrariesQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get enabled libraries queries. - public GetEnabledLibrariesEndpoint(IQueryHandler> getEnabledLibrariesQueryHandler) + public GetEnabledLibrariesEndpoint(IQueryHandler> getEnabledLibrariesQueryHandler) { _getEnabledLibrariesQueryHandler = getEnabledLibrariesQueryHandler; } @@ -34,7 +34,7 @@ public class GetEnabledLibrariesEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Libraries.GET_ENABLED_LIBRARIES); Version(1); DontCatchExceptions(); @@ -46,7 +46,7 @@ public class GetEnabledLibrariesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr result = await _getEnabledLibrariesQueryHandler.HandleAsync(new GetEnabledLibrariesQuery(), cancellationToken).ConfigureAwait(false); + Result result = await _getEnabledLibrariesQueryHandler.HandleAsync(new GetEnabledLibrariesQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpoint.cs index ced03ede..a6e7262e 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpoint.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries; using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -18,13 +18,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraries /// public class GetLibrariesEndpoint : BaseEndpoint { - private readonly IQueryHandler> _getLibrariesQueryHandler; + private readonly IQueryHandler> _getLibrariesQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get libraries queries. - public GetLibrariesEndpoint(IQueryHandler> getLibrariesQueryHandler) + public GetLibrariesEndpoint(IQueryHandler> getLibrariesQueryHandler) { _getLibrariesQueryHandler = getLibrariesQueryHandler; } @@ -34,7 +34,7 @@ public class GetLibrariesEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Libraries.GET_LIBRARIES); Version(1); DontCatchExceptions(); @@ -46,7 +46,7 @@ public class GetLibrariesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr result = await _getLibrariesQueryHandler.HandleAsync(new GetLibrariesQuery(), cancellationToken).ConfigureAwait(false); + Result result = await _getLibrariesQueryHandler.HandleAsync(new GetLibrariesQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpoint.cs index 560aa619..8dd9c0ae 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpoint.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +20,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibrary; /// public class GetLibraryEndpoint : BaseEndpoint { - private readonly IQueryHandler> _getLibraryQueryHandler; + private readonly IQueryHandler> _getLibraryQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get library queries. - public GetLibraryEndpoint(IQueryHandler> getLibraryQueryHandler) + public GetLibraryEndpoint(IQueryHandler> getLibraryQueryHandler) { _getLibraryQueryHandler = getLibraryQueryHandler; } @@ -35,7 +36,7 @@ public class GetLibraryEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Libraries.GET_LIBRARY_BY_ID); Version(1); DontCatchExceptions(); @@ -48,7 +49,7 @@ public class GetLibraryEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetLibraryRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _getLibraryQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result result = await _getLibraryQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpoint.cs index ea5f73c4..6d8268c4 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpoint.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScanProgress; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +20,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibrarySc /// public class GetLibraryScanProgressEndpoint : BaseEndpoint { - private readonly IQueryHandler> _getLibraryScanProgressQueryHandler; + private readonly IQueryHandler> _getLibraryScanProgressQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get library scan progress queries. - public GetLibraryScanProgressEndpoint(IQueryHandler> getLibraryScanProgressQueryHandler) + public GetLibraryScanProgressEndpoint(IQueryHandler> getLibraryScanProgressQueryHandler) { _getLibraryScanProgressQueryHandler = getLibraryScanProgressQueryHandler; } @@ -35,7 +36,7 @@ public class GetLibraryScanProgressEndpoint : BaseEndpoint public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Libraries.LIBRARY_SCAN_PROGRESS); Version(1); DontCatchExceptions(); @@ -48,7 +49,7 @@ public class GetLibraryScanProgressEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetLibraryScanProgressRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _getLibraryScanProgressQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result result = await _getLibraryScanProgressQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpoint.cs index fa9e8e2b..1fb92cbd 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpoint.cs @@ -1,10 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans; using Lumina.Contracts.Responses.MediaLibrary.Management; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -20,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetRunningLi /// public class GetRunningLibraryScansEndpoint : BaseEndpoint { - private readonly IQueryHandler>> _getRunningLibraryScansQueryHandler; + private readonly IQueryHandler>> _getRunningLibraryScansQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get running library scans queries. - public GetRunningLibraryScansEndpoint(IQueryHandler>> getRunningLibraryScansQueryHandler) + public GetRunningLibraryScansEndpoint(IQueryHandler>> getRunningLibraryScansQueryHandler) { _getRunningLibraryScansQueryHandler = getRunningLibraryScansQueryHandler; } @@ -36,7 +35,7 @@ public class GetRunningLibraryScansEndpoint : BaseEndpoint public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Libraries.GET_RUNNING_LIBRARIES_SCAN); Version(1); DontCatchExceptions(); @@ -48,7 +47,7 @@ public class GetRunningLibraryScansEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr> result = await _getRunningLibraryScansQueryHandler.HandleAsync(new GetRunningLibraryScansQuery(), cancellationToken).ConfigureAwait(false); + Result> result = await _getRunningLibraryScansQueryHandler.HandleAsync(new GetRunningLibraryScansQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs index 34920a12..51e00320 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries; using Lumina.Contracts.Responses.MediaLibrary.Management; @@ -18,13 +18,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibrarie /// public class ScanLibrariesEndpoint : BaseEndpoint { - private readonly ICommandHandler>> _scanLibrariesCommandHandler; + private readonly ICommandHandler>> _scanLibrariesCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling scan libraries commands. - public ScanLibrariesEndpoint(ICommandHandler>> scanLibrariesCommandHandler) + public ScanLibrariesEndpoint(ICommandHandler>> scanLibrariesCommandHandler) { _scanLibrariesCommandHandler = scanLibrariesCommandHandler; } @@ -46,7 +46,7 @@ public class ScanLibrariesEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(FastEndpoints.EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr> result = await _scanLibrariesCommandHandler.HandleAsync(new ScanLibrariesCommand(), cancellationToken).ConfigureAwait(false); + Result> result = await _scanLibrariesCommandHandler.HandleAsync(new ScanLibrariesCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs index 4904c11d..d7f54d39 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibrary; /// public class ScanLibraryEndpoint : BaseEndpoint { - private readonly ICommandHandler> _scanLibraryCommandHandler; + private readonly ICommandHandler> _scanLibraryCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling scan library commands. - public ScanLibraryEndpoint(ICommandHandler> scanLibraryCommandHandler) + public ScanLibraryEndpoint(ICommandHandler> scanLibraryCommandHandler) { _scanLibraryCommandHandler = scanLibraryCommandHandler; } @@ -47,7 +47,7 @@ public class ScanLibraryEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(ScanLibraryRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _scanLibraryCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _scanLibraryCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpoint.cs index b615725b..ffcd0b86 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpoint.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.UpdateLibrar /// public class UpdateLibraryEndpoint : BaseEndpoint { - private readonly ICommandHandler> _updateLibraryCommandHandler; + private readonly ICommandHandler> _updateLibraryCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling update library commands. - public UpdateLibraryEndpoint(ICommandHandler> updateLibraryCommandHandler) + public UpdateLibraryEndpoint(ICommandHandler> updateLibraryCommandHandler) { _updateLibraryCommandHandler = updateLibraryCommandHandler; } @@ -48,7 +48,7 @@ public class UpdateLibraryEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdateLibraryRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _updateLibraryCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _updateLibraryCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs index de77dcd6..18ac473f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B /// public class AddBookEndpoint : BaseEndpoint { - private readonly ICommandHandler> _addBookCommandHandler; + private readonly ICommandHandler> _addBookCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling add book commands. - public AddBookEndpoint(ICommandHandler> addBookCommandHandler) + public AddBookEndpoint(ICommandHandler> addBookCommandHandler) { _addBookCommandHandler = addBookCommandHandler; } @@ -48,7 +48,7 @@ public class AddBookEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(AddBookRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _addBookCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _addBookCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Books.ADD_BOOK}/{result.Value.Id}", result.Value), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpoint.cs index 10d2d9b1..85e6b2e0 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpoint.cs @@ -33,7 +33,7 @@ public class GetBookEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetBookRequest request, CancellationToken cancellationToken) { - //ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + //Result result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); //return result.Match(success => TypedResults.CreatedAtRoute($"/api/v1/books/{success.Id}", success), Problem); return await Task.FromResult(TypedResults.Ok()); } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs index 53f86381..ad4d2407 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -20,13 +21,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B /// public class GetBooksEndpoint : BaseEndpoint { - private readonly IQueryHandler>> _getBooksQueryHandler; + private readonly IQueryHandler>> _getBooksQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get books queries. - public GetBooksEndpoint(IQueryHandler>> getBooksQueryHandler) + public GetBooksEndpoint(IQueryHandler>> getBooksQueryHandler) { _getBooksQueryHandler = getBooksQueryHandler; } @@ -36,7 +37,7 @@ public class GetBooksEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Books.GET_BOOKS); Version(1); DontCatchExceptions(); @@ -49,7 +50,7 @@ public class GetBooksEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetBooksRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _getBooksQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result> result = await _getBooksQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs index 195ceaff..92c3790f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs @@ -1,15 +1,15 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; -using Lumina.Contracts.Requests.Authentication; -using Lumina.Contracts.Responses.Authentication; using Lumina.Application.Common.Mapping.Authentication; using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Maintenance; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; -using Lumina.Presentation.Api.Common.Routes.Maintenance; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; /// public class SetupApplicationEndpoint : BaseEndpoint { - private readonly ICommandHandler> _setupApplicationCommandHandler; + private readonly ICommandHandler> _setupApplicationCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling setup application commands. - public SetupApplicationEndpoint(ICommandHandler> setupApplicationCommandHandler) + public SetupApplicationEndpoint(ICommandHandler> setupApplicationCommandHandler) { _setupApplicationCommandHandler = setupApplicationCommandHandler; } @@ -49,7 +49,7 @@ public class SetupApplicationEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _setupApplicationCommandHandler.HandleAsync(request.ToSetupCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _setupApplicationCommandHandler.HandleAsync(request.ToSetupCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{Api.Common.Routes.UsersManagement.ApiRoutes.Users.GET_USER_BY_ID.Replace("{id}", success.Id.ToString())}", result.Value), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpoint.cs index b5260a14..1e8e48bc 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpoint.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Plugins; using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; using Lumina.Contracts.Requests.Plugins; using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -20,13 +21,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryMetadataProvi /// public class GetLibraryMetadataProvidersEndpoint : BaseEndpoint { - private readonly IQueryHandler>> _getLibraryMetadataProvidersQueryHandler; + private readonly IQueryHandler>> _getLibraryMetadataProvidersQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get library metadata providers queries. - public GetLibraryMetadataProvidersEndpoint(IQueryHandler>> getLibraryMetadataProvidersQueryHandler) + public GetLibraryMetadataProvidersEndpoint(IQueryHandler>> getLibraryMetadataProvidersQueryHandler) { _getLibraryMetadataProvidersQueryHandler = getLibraryMetadataProvidersQueryHandler; } @@ -36,7 +37,7 @@ public class GetLibraryMetadataProvidersEndpoint : BaseEndpoint public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Libraries.GET_LIBRARY_METADATA_PROVIDERS); Version(1); DontCatchExceptions(); @@ -49,7 +50,7 @@ public class GetLibraryMetadataProvidersEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetLibraryMetadataProvidersRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _getLibraryMetadataProvidersQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result> result = await _getLibraryMetadataProvidersQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs index 4d256e64..4f85ffd7 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs @@ -1,10 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Plugins; using Lumina.Application.Core.Plugins.Queries.GetPluginSettings; using Lumina.Contracts.Requests.Plugins; using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Plugins; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +20,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPluginSettings; /// public class GetPluginSettingsEndpoint : BaseEndpoint { - private readonly IQueryHandler> _getPluginSettingsQueryHandler; + private readonly IQueryHandler> _getPluginSettingsQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get plugin settings queries. - public GetPluginSettingsEndpoint(IQueryHandler> getPluginSettingsQueryHandler) + public GetPluginSettingsEndpoint(IQueryHandler> getPluginSettingsQueryHandler) { _getPluginSettingsQueryHandler = getPluginSettingsQueryHandler; } @@ -35,7 +36,7 @@ public class GetPluginSettingsEndpoint : BaseEndpoint public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Plugins.GET_PLUGIN_SETTINGS); Version(1); DontCatchExceptions(); @@ -48,7 +49,7 @@ public class GetPluginSettingsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetPluginSettingsRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _getPluginSettingsQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result result = await _getPluginSettingsQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs index fb276ae9..2dd0a159 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Plugins.Queries.GetPlugins; using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Plugins; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPlugins; /// public class GetPluginsEndpoint : BaseEndpoint { - private readonly IQueryHandler>> _getPluginsQueryHandler; + private readonly IQueryHandler>> _getPluginsQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get plugins queries. - public GetPluginsEndpoint(IQueryHandler>> getPluginsQueryHandler) + public GetPluginsEndpoint(IQueryHandler>> getPluginsQueryHandler) { _getPluginsQueryHandler = getPluginsQueryHandler; } @@ -35,7 +35,7 @@ public class GetPluginsEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Plugins.GET_PLUGINS); Version(1); DontCatchExceptions(); @@ -47,7 +47,7 @@ public class GetPluginsEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr> result = await _getPluginsQueryHandler.HandleAsync(new GetPluginsQuery(), cancellationToken).ConfigureAwait(false); + Result> result = await _getPluginsQueryHandler.HandleAsync(new GetPluginsQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs index 4623c080..c07e7016 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Plugins; using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -18,13 +18,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataP /// public class ReorderLibraryMetadataProvidersEndpoint : BaseEndpoint { - private readonly ICommandHandler> _reorderLibraryMetadataProvidersCommandHandler; + private readonly ICommandHandler> _reorderLibraryMetadataProvidersCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling reorder library metadata providers commands. - public ReorderLibraryMetadataProvidersEndpoint(ICommandHandler> reorderLibraryMetadataProvidersCommandHandler) + public ReorderLibraryMetadataProvidersEndpoint(ICommandHandler> reorderLibraryMetadataProvidersCommandHandler) { _reorderLibraryMetadataProvidersCommandHandler = reorderLibraryMetadataProvidersCommandHandler; } @@ -47,7 +47,7 @@ public class ReorderLibraryMetadataProvidersEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(ReorderLibraryMetadataProvidersRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _reorderLibraryMetadataProvidersCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _reorderLibraryMetadataProvidersCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs index fc331dd1..d3d490e3 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Plugins; using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -18,13 +18,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProvi /// public class SetLibraryMetadataProviderEnabledEndpoint : BaseEndpoint { - private readonly ICommandHandler> _setLibraryMetadataProviderEnabledCommandHandler; + private readonly ICommandHandler> _setLibraryMetadataProviderEnabledCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling set library metadata provider enabled commands. - public SetLibraryMetadataProviderEnabledEndpoint(ICommandHandler> setLibraryMetadataProviderEnabledCommandHandler) + public SetLibraryMetadataProviderEnabledEndpoint(ICommandHandler> setLibraryMetadataProviderEnabledCommandHandler) { _setLibraryMetadataProviderEnabledCommandHandler = setLibraryMetadataProviderEnabledCommandHandler; } @@ -47,7 +47,7 @@ public class SetLibraryMetadataProviderEnabledEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(SetLibraryMetadataProviderEnabledRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _setLibraryMetadataProviderEnabledCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _setLibraryMetadataProviderEnabledCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs index 9045a879..876731a9 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Plugins; using Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Plugins; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -18,13 +18,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.UpdatePluginSettings; /// public class UpdatePluginSettingsEndpoint : BaseEndpoint { - private readonly ICommandHandler> _updatePluginSettingsCommandHandler; + private readonly ICommandHandler> _updatePluginSettingsCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling update plugin settings commands. - public UpdatePluginSettingsEndpoint(ICommandHandler> updatePluginSettingsCommandHandler) + public UpdatePluginSettingsEndpoint(ICommandHandler> updatePluginSettingsCommandHandler) { _updatePluginSettingsCommandHandler = updatePluginSettingsCommandHandler; } @@ -47,7 +47,7 @@ public class UpdatePluginSettingsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdatePluginSettingsRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _updatePluginSettingsCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _updatePluginSettingsCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs index dc3352ca..da85177d 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authentication; using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication. /// public class ChangePasswordEndpoint : BaseEndpoint { - private readonly ICommandHandler> _changePasswordCommandHandler; + private readonly ICommandHandler> _changePasswordCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling change password commands. - public ChangePasswordEndpoint(ICommandHandler> changePasswordCommandHandler) + public ChangePasswordEndpoint(ICommandHandler> changePasswordCommandHandler) { _changePasswordCommandHandler = changePasswordCommandHandler; } @@ -48,7 +48,7 @@ public class ChangePasswordEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(ChangePasswordRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _changePasswordCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _changePasswordCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpoint.cs index b68fb6ed..ebd1343d 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpoint.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUsers; using Lumina.Contracts.Responses.UsersManagement.Users; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication. /// public class GetUsersEndpoint : BaseEndpoint { - private readonly IQueryHandler>> _getUsersQueryHandler; + private readonly IQueryHandler>> _getUsersQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get users queries. - public GetUsersEndpoint(IQueryHandler>> getUsersQueryHandler) + public GetUsersEndpoint(IQueryHandler>> getUsersQueryHandler) { _getUsersQueryHandler = getUsersQueryHandler; } @@ -35,7 +35,7 @@ public class GetUsersEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Authentication.USERS); Version(1); DontCatchExceptions(); @@ -47,7 +47,7 @@ public class GetUsersEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr> result = await _getUsersQueryHandler.HandleAsync(new GetUsersQuery(), cancellationToken).ConfigureAwait(false); + Result> result = await _getUsersQueryHandler.HandleAsync(new GetUsersQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs index fde99824..d3bd7ea2 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs @@ -1,17 +1,15 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Errors; using Lumina.Application.Common.Mapping.Authentication; using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Caching.Memory; -using System; using System.Threading; using System.Threading.Tasks; #endregion @@ -23,13 +21,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication. /// public class LoginEndpoint : BaseEndpoint { - private readonly IQueryHandler> _loginQueryHandler; + private readonly IQueryHandler> _loginQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling login queries. - public LoginEndpoint(IQueryHandler> loginQueryHandler) + public LoginEndpoint(IQueryHandler> loginQueryHandler) { _loginQueryHandler = loginQueryHandler; } @@ -39,7 +37,7 @@ public class LoginEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.POST); + Verbs(Http.POST); Routes(ApiRoutes.Authentication.LOGIN_ACCOUNT); Version(1); AllowAnonymous(); @@ -54,7 +52,7 @@ public class LoginEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(LoginRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _loginQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result result = await _loginQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs index 5a33a86c..2077b918 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authentication; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Builder; @@ -20,13 +20,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication. /// public class RecoverPasswordEndpoint : BaseEndpoint { - private readonly ICommandHandler> _recoverPasswordCommandHandler; + private readonly ICommandHandler> _recoverPasswordCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling recover password commands. - public RecoverPasswordEndpoint(ICommandHandler> recoverPasswordCommandHandler) + public RecoverPasswordEndpoint(ICommandHandler> recoverPasswordCommandHandler) { _recoverPasswordCommandHandler = recoverPasswordCommandHandler; } @@ -51,7 +51,7 @@ public class RecoverPasswordEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(RecoverPasswordRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _recoverPasswordCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _recoverPasswordCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs index e55ae991..0af9ce38 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authentication; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Builder; @@ -20,13 +20,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication. /// public class RegisterEndpoint : BaseEndpoint { - private readonly ICommandHandler> _registerUserCommandHandler; + private readonly ICommandHandler> _registerUserCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling register user commands. - public RegisterEndpoint(ICommandHandler> registerUserCommandHandler) + public RegisterEndpoint(ICommandHandler> registerUserCommandHandler) { _registerUserCommandHandler = registerUserCommandHandler; } @@ -51,7 +51,7 @@ public class RegisterEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _registerUserCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _registerUserCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Users.GET_USER_BY_ID.Replace("{id}", success.Id.ToString())}", result.Value), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpoint.cs index 3f31c974..1acafcb9 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpoint.cs @@ -1,11 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authentication; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -20,13 +21,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.G /// public class GetAuthorizationEndpoint : BaseEndpoint { - private readonly IQueryHandler> _getAuthorizationQueryHandler; + private readonly IQueryHandler> _getAuthorizationQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get authorization queries. - public GetAuthorizationEndpoint(IQueryHandler> getAuthorizationQueryHandler) + public GetAuthorizationEndpoint(IQueryHandler> getAuthorizationQueryHandler) { _getAuthorizationQueryHandler = getAuthorizationQueryHandler; } @@ -36,7 +37,7 @@ public class GetAuthorizationEndpoint : BaseEndpoint public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Authorization.GET_AUTHORIZATION); Version(1); DontCatchExceptions(); @@ -49,7 +50,7 @@ public class GetAuthorizationEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetAuthorizationRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _getAuthorizationQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result result = await _getAuthorizationQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpoint.cs index 1539c716..a7c9d60c 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpoint.cs @@ -1,11 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authentication; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -21,13 +22,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.G /// public class GetUserPermissionsEndpoint : BaseEndpoint { - private readonly IQueryHandler>> _getUserPermissionsQueryHandler; + private readonly IQueryHandler>> _getUserPermissionsQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get user permissions queries. - public GetUserPermissionsEndpoint(IQueryHandler>> getUserPermissionsQueryHandler) + public GetUserPermissionsEndpoint(IQueryHandler>> getUserPermissionsQueryHandler) { _getUserPermissionsQueryHandler = getUserPermissionsQueryHandler; } @@ -37,7 +38,7 @@ public class GetUserPermissionsEndpoint : BaseEndpoint public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Authorization.GET_USER_PERMISSIONS_BY_USER_ID); Version(1); DontCatchExceptions(); @@ -50,7 +51,7 @@ public class GetUserPermissionsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetUserPermissionsRequest request, CancellationToken cancellationToken) { - ErrorOr> result = await _getUserPermissionsQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result> result = await _getUserPermissionsQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpoint.cs index 072ba2fe..a4245295 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpoint.cs @@ -1,15 +1,15 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authentication; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -21,13 +21,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.G /// public class GetUserRoleEndpoint : BaseEndpoint { - private readonly IQueryHandler> _getUserRoleQueryHandler; + private readonly IQueryHandler> _getUserRoleQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get user role queries. - public GetUserRoleEndpoint(IQueryHandler> getUserRoleQueryHandler) + public GetUserRoleEndpoint(IQueryHandler> getUserRoleQueryHandler) { _getUserRoleQueryHandler = getUserRoleQueryHandler; } @@ -37,7 +37,7 @@ public class GetUserRoleEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Authorization.GET_USER_ROLE_BY_USER_ID); Version(1); DontCatchExceptions(); @@ -50,7 +50,7 @@ public class GetUserRoleEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetUserRoleRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _getUserRoleQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + Result result = await _getUserRoleQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpoint.cs index 5ef4af57..55ce3ac6 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpoint.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -19,13 +19,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.U /// public class UpdateUserRoleAndPermissionsEndpoint : BaseEndpoint { - private readonly ICommandHandler> _updateUserRoleAndPermissionsCommandHandler; + private readonly ICommandHandler> _updateUserRoleAndPermissionsCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling update user role and permissions commands. - public UpdateUserRoleAndPermissionsEndpoint(ICommandHandler> updateUserRoleAndPermissionsCommandHandler) + public UpdateUserRoleAndPermissionsEndpoint(ICommandHandler> updateUserRoleAndPermissionsCommandHandler) { _updateUserRoleAndPermissionsCommandHandler = updateUserRoleAndPermissionsCommandHandler; } @@ -48,7 +48,7 @@ public class UpdateUserRoleAndPermissionsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdateUserRoleAndPermissionsRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _updateUserRoleAndPermissionsCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + Result result = await _updateUserRoleAndPermissionsCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index 9f663160..0cd26d06 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.DependencyInjection; using Lumina.DataAccess.Common.DependencyInjection; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.DependencyInjection; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Infrastructure.Common.DependencyInjection; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; @@ -151,8 +151,8 @@ public class Program { IServiceProvider services = scope.ServiceProvider; IFileSystemStructureSeedService context = services.GetRequiredService(); - ErrorOr setDefaultDirectoriesResult = context.SetDefaultDirectories(mediaRootPath); - if (setDefaultDirectoriesResult.IsError) + Result setDefaultDirectoriesResult = context.SetDefaultDirectories(mediaRootPath); + if (setDefaultDirectoriesResult.IsFailure) throw new InvalidOperationException("Could not create default file system directories structure: " + setDefaultDirectoriesResult.FirstError.Description); } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs index d2eb2e7d..3c9ecec0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs @@ -67,7 +67,7 @@ public class BookJsonConverter : JsonConverter List contributorIds = DeserializeContributorIds(root.GetProperty("contributors")); List ratings = DeserializeRatings(root.GetProperty("ratings")); - ErrorOr.ErrorOr createBookResult = Book.Create( + Result createBookResult = Book.Create( BookId.Create(id), LibraryId.Create(libraryId), path, @@ -91,7 +91,7 @@ public class BookJsonConverter : JsonConverter contributorIds, ratings: ratings ); - if (createBookResult.IsError) + if (createBookResult.IsFailure) throw new JsonException($"Failed to create Book: {string.Join(", ", createBookResult.Errors)}"); return createBookResult.Value; } @@ -128,7 +128,7 @@ public class BookJsonConverter : JsonConverter if (element.TryGetProperty("pageCount", out JsonElement pageCountElement)) if (pageCountElement.ValueKind != JsonValueKind.Null) pageCount = pageCountElement.GetInt32(); - ErrorOr.ErrorOr metadataResult = WrittenContentMetadata.Create( + Result metadataResult = WrittenContentMetadata.Create( title!, Optional.FromNullable(originalTitle), Optional.FromNullable(description), @@ -141,7 +141,7 @@ public class BookJsonConverter : JsonConverter Optional.FromNullable(pageCount) ); - if (metadataResult.IsError) + if (metadataResult.IsFailure) throw new JsonException($"Failed to create WrittenContentMetadata: {string.Join(", ", metadataResult.Errors)}"); return metadataResult.Value; } @@ -166,7 +166,7 @@ public class BookJsonConverter : JsonConverter string? releaseVersion = element.TryGetProperty("releaseVersion", out JsonElement rvElement) ? rvElement.GetString() : null; - ErrorOr.ErrorOr releaseInfoResult = ReleaseInfo.Create( + Result releaseInfoResult = ReleaseInfo.Create( Optional.FromNullable(originalReleaseDate), Optional.FromNullable(originalReleaseYear), Optional.FromNullable(reReleaseDate), @@ -175,7 +175,7 @@ public class BookJsonConverter : JsonConverter Optional.FromNullable(releaseVersion) ); - if (releaseInfoResult.IsError) + if (releaseInfoResult.IsFailure) throw new JsonException($"Failed to create ReleaseInfo: {string.Join(", ", releaseInfoResult.Errors)}"); return releaseInfoResult.Value; } @@ -187,9 +187,7 @@ public class BookJsonConverter : JsonConverter /// The deserialized list of . private static List DeserializeGenres(JsonElement element) { - return element.EnumerateArray() - .Select(g => Genre.Create(g.GetProperty("name").GetString()!).Value) - .ToList(); + return [.. element.EnumerateArray().Select(g => Genre.Create(g.GetProperty("name").GetString()!).Value)]; } /// @@ -199,9 +197,7 @@ public class BookJsonConverter : JsonConverter /// The deserialized list of . private static List DeserializeTags(JsonElement element) { - return element.EnumerateArray() - .Select(t => Tag.Create(t.GetProperty("name").GetString()!).Value) - .ToList(); + return [.. element.EnumerateArray().Select(t => Tag.Create(t.GetProperty("name").GetString()!).Value)]; } /// @@ -217,13 +213,13 @@ public class BookJsonConverter : JsonConverter string? languageName = element.GetProperty("languageName").GetString(); string? nativeName = element.TryGetProperty("nativeName", out JsonElement nnElement) ? nnElement.GetString() : null; - ErrorOr.ErrorOr languageInfoResult = LanguageInfo.Create( + Result languageInfoResult = LanguageInfo.Create( languageCode!, languageName!, Optional.FromNullable(nativeName) ); - if (languageInfoResult.IsError) + if (languageInfoResult.IsFailure) throw new JsonException($"Failed to create LanguageInfo: {string.Join(", ", languageInfoResult.Errors)}"); return languageInfoResult.Value; } @@ -249,10 +245,9 @@ public class BookJsonConverter : JsonConverter /// The deserialized list of . private static List DeserializeIsbns(JsonElement element) { - return element.EnumerateArray() + return [.. element.EnumerateArray() .Select(i => Isbn.Create(i.GetProperty("value").GetString()!, - Enum.Parse(i.GetProperty("format").GetString()!)).Value) - .ToList(); + Enum.Parse(i.GetProperty("format").GetString()!)).Value)]; } /// @@ -273,7 +268,7 @@ public class BookJsonConverter : JsonConverter /// The deserialized list of . private static List DeserializeRatings(JsonElement element) { - return element.EnumerateArray() + return [.. element.EnumerateArray() .Select(r => BookRating.Create( r.GetProperty("value").GetInt32(), r.GetProperty("maxValue").GetInt32(), @@ -282,7 +277,6 @@ public class BookJsonConverter : JsonConverter r.TryGetProperty("voteCount", out JsonElement voteCountElement) && voteCountElement.ValueKind != JsonValueKind.Null ? voteCountElement.GetInt32() : (int?)null) - ).Value) - .ToList(); + ).Value)]; } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs index 3b02863d..4fcae2db 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Presentation.Api.IntegrationTests.Common.Converters; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.Fixtures; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreDtoMappingTests.cs index 77d5aaa5..36f3fa80 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreDtoMappingTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -23,10 +23,10 @@ public class GenreDtoMappingTests GenreDto genreDto = new("Rock"); // Act - ErrorOr result = genreDto.ToDomainEntity(); + Result result = genreDto.ToDomainEntity(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(genreDto.Name, result.Value.Name); } @@ -42,10 +42,10 @@ public class GenreDtoMappingTests GenreDto genreDto = new(name); // Act - ErrorOr result = genreDto.ToDomainEntity(); + Result result = genreDto.ToDomainEntity(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(genreDto.Name, result.Value.Name); } @@ -60,10 +60,10 @@ public class GenreDtoMappingTests GenreDto genreDto = new(invalidName); // Act - ErrorOr result = genreDto.ToDomainEntity(); + Result result = genreDto.ToDomainEntity(); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); } [Fact] @@ -79,16 +79,16 @@ public class GenreDtoMappingTests ]; // Act - IEnumerable> results = genreDtos.ToDomainEntities(); + IEnumerable> results = genreDtos.ToDomainEntities(); // Assert Assert.NotNull(results); Assert.Equal(genreDtos.Count, results.Count()); - List> resultList = results.ToList(); + List> resultList = results.ToList(); for (int i = 0; i < genreDtos.Count; i++) { - Assert.False(resultList[i].IsError); + Assert.False(resultList[i].IsFailure); Assert.Equal(genreDtos[i].Name, resultList[i].Value.Name); } } @@ -106,21 +106,21 @@ public class GenreDtoMappingTests ]; // Act - IEnumerable> results = genreDtos.ToDomainEntities(); + IEnumerable> results = genreDtos.ToDomainEntities(); // Assert Assert.NotNull(results); Assert.Equal(genreDtos.Count, results.Count()); - List> resultList = results.ToList(); - Assert.False(resultList[0].IsError); + List> resultList = results.ToList(); + Assert.False(resultList[0].IsFailure); Assert.Equal("Rock", resultList[0].Value.Name); - Assert.True(resultList[1].IsError); + Assert.True(resultList[1].IsFailure); - Assert.False(resultList[2].IsError); + Assert.False(resultList[2].IsFailure); Assert.Equal("Jazz", resultList[2].Value.Name); - Assert.True(resultList[3].IsError); + Assert.True(resultList[3].IsFailure); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreEntityMappingTests.cs index 46402149..37e7f560 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreEntityMappingTests.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; -using Lumina.Domain.SharedKernel.Common.Errors; #endregion namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; @@ -73,10 +73,10 @@ public class GenreEntityMappingTests GenreEntity entity = new("Fiction"); // Act - ErrorOr result = entity.ToDomainEntity(); + Result result = entity.ToDomainEntity(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(entity.Name, result.Value.Name); } @@ -91,10 +91,10 @@ public class GenreEntityMappingTests GenreEntity entity = new(invalidName); // Act - ErrorOr result = entity.ToDomainEntity(); + Result result = entity.ToDomainEntity(); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, result.FirstError); } @@ -111,16 +111,16 @@ public class GenreEntityMappingTests ]; // Act - IEnumerable> results = entities.ToDomainEntities(); + IEnumerable> results = entities.ToDomainEntities(); // Assert Assert.NotNull(results); Assert.Equal(entities.Count, results.Count()); - List> resultList = results.ToList(); + List> resultList = results.ToList(); for (int i = 0; i < entities.Count; i++) { - Assert.False(resultList[i].IsError); + Assert.False(resultList[i].IsFailure); Assert.Equal(entities[i].Name, resultList[i].Value.Name); } } @@ -146,8 +146,6 @@ public class GenreEntityMappingTests List resultList = results.ToList(); for (int i = 0; i < entities.Count; i++) - { Assert.Equal(entities[i].Name, resultList[i].Name); - } } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreMappingTests.cs index f5b49c6a..2f2b3fe8 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreMappingTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -20,8 +20,8 @@ public class GenreMappingTests public void ToRepositoryEntity_WhenMappingGenre_ShouldMapCorrectly() { // Arrange - ErrorOr createResult = Genre.Create("Rock"); - Assert.False(createResult.IsError); + Result createResult = Genre.Create("Rock"); + Assert.False(createResult.IsFailure); Genre genre = createResult.Value; // Act @@ -40,8 +40,8 @@ public class GenreMappingTests public void ToRepositoryEntity_WhenMappingDifferentGenres_ShouldMapCorrectly(string name) { // Arrange - ErrorOr createResult = Genre.Create(name); - Assert.False(createResult.IsError); + Result createResult = Genre.Create(name); + Assert.False(createResult.IsFailure); Genre genre = createResult.Value; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagDtoMappingTests.cs index fb5fe200..c2c4de9d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagDtoMappingTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -23,10 +23,10 @@ public class TagDtoMappingTests TagDto tagDto = new("indie"); // Act - ErrorOr result = tagDto.ToDomainEntity(); + Result result = tagDto.ToDomainEntity(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(tagDto.Name, result.Value.Name); } @@ -43,10 +43,10 @@ public class TagDtoMappingTests TagDto tagDto = new(name); // Act - ErrorOr result = tagDto.ToDomainEntity(); + Result result = tagDto.ToDomainEntity(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(tagDto.Name, result.Value.Name); } @@ -61,10 +61,10 @@ public class TagDtoMappingTests TagDto tagDto = new(invalidName); // Act - ErrorOr result = tagDto.ToDomainEntity(); + Result result = tagDto.ToDomainEntity(); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); } [Fact] @@ -80,16 +80,16 @@ public class TagDtoMappingTests ]; // Act - IEnumerable> results = tagDtos.ToDomainEntities(); + IEnumerable> results = tagDtos.ToDomainEntities(); // Assert Assert.NotNull(results); Assert.Equal(tagDtos.Count, results.Count()); - List> resultList = results.ToList(); + List> resultList = [.. results]; for (int i = 0; i < tagDtos.Count; i++) { - Assert.False(resultList[i].IsError); + Assert.False(resultList[i].IsFailure); Assert.Equal(tagDtos[i].Name, resultList[i].Value.Name); } } @@ -107,21 +107,21 @@ public class TagDtoMappingTests ]; // Act - IEnumerable> results = tagDtos.ToDomainEntities(); + IEnumerable> results = tagDtos.ToDomainEntities(); // Assert Assert.NotNull(results); Assert.Equal(tagDtos.Count, results.Count()); - List> resultList = results.ToList(); - Assert.False(resultList[0].IsError); + List> resultList = [.. results]; + Assert.False(resultList[0].IsFailure); Assert.Equal("indie", resultList[0].Value.Name); - Assert.True(resultList[1].IsError); + Assert.True(resultList[1].IsFailure); - Assert.False(resultList[2].IsError); + Assert.False(resultList[2].IsFailure); Assert.Equal("electronic", resultList[2].Value.Name); - Assert.True(resultList[3].IsError); + Assert.True(resultList[3].IsFailure); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagEntityMappingTests.cs index 7a0b7d7c..a731b2bd 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagEntityMappingTests.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; -using Lumina.Domain.SharedKernel.Common.Errors; #endregion namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; @@ -73,10 +73,10 @@ public class TagEntityMappingTests TagEntity entity = new("Fantasy"); // Act - ErrorOr result = entity.ToDomainEntity(); + Result result = entity.ToDomainEntity(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(entity.Name, result.Value.Name); } @@ -91,10 +91,10 @@ public class TagEntityMappingTests TagEntity entity = new(invalidName); // Act - ErrorOr result = entity.ToDomainEntity(); + Result result = entity.ToDomainEntity(); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, result.FirstError); } @@ -111,16 +111,16 @@ public class TagEntityMappingTests ]; // Act - IEnumerable> results = entities.ToDomainEntities(); + IEnumerable> results = entities.ToDomainEntities(); // Assert Assert.NotNull(results); Assert.Equal(entities.Count, results.Count()); - List> resultList = results.ToList(); + List> resultList = [.. results]; for (int i = 0; i < entities.Count; i++) { - Assert.False(resultList[i].IsError); + Assert.False(resultList[i].IsFailure); Assert.Equal(entities[i].Name, resultList[i].Value.Name); } } @@ -144,7 +144,7 @@ public class TagEntityMappingTests Assert.NotNull(results); Assert.Equal(entities.Count, results.Count()); - List resultList = results.ToList(); + List resultList = [.. results]; for (int i = 0; i < entities.Count; i++) Assert.Equal(entities[i].Name, resultList[i].Name); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagMappingTests.cs index fc89d886..4e327b3f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagMappingTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -20,8 +20,8 @@ public class TagMappingTests public void ToRepositoryEntity_WhenMappingTag_ShouldMapCorrectly() { // Arrange - ErrorOr createResult = Tag.Create("indie"); - Assert.False(createResult.IsError); + Result createResult = Tag.Create("indie"); + Assert.False(createResult.IsFailure); Tag tag = createResult.Value; // Act @@ -41,8 +41,8 @@ public class TagMappingTests public void ToRepositoryEntity_WhenMappingDifferentTags_ShouldMapCorrectly(string name) { // Arrange - ErrorOr createResult = Tag.Create(name); - Assert.False(createResult.IsError); + Result createResult = Tag.Create(name); + Assert.False(createResult.IsFailure); Tag tag = createResult.Value; // Act @@ -72,7 +72,7 @@ public class TagMappingTests // Assert Assert.NotNull(results); Assert.Equal(tags.Count, results.Count()); - List resultList = results.ToList(); + List resultList = [.. results]; for (int i = 0; i < tags.Count; i++) Assert.Equal(tags[i].Name, resultList[i].Name); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMappingTests.cs index cf2beb7c..74a81a4b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMappingTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Mapping.FileSystemManagement.Common; using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System.Diagnostics.CodeAnalysis; #endregion @@ -33,10 +33,10 @@ public class FileSystemTreeNodeResponseMappingTests FileSystemTreeNodeResponse response = _fileSystemTreeNodeResponseFixture.Create(); // Act - ErrorOr result = response.ToWindowsRootItem(); + Result result = response.ToWindowsRootItem(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(response.Path, result.Value.Id.Path); Assert.Equal(response.Name, result.Value.Name); @@ -50,10 +50,10 @@ public class FileSystemTreeNodeResponseMappingTests FileSystemTreeNodeResponse response = _fileSystemTreeNodeResponseFixture.Create(); // Act - ErrorOr result = response.ToUnixRootItem(); + Result result = response.ToUnixRootItem(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(FileSystemItemStatus.Accessible, result.Value.Status); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMappingTests.cs index 121a1327..4baff100 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMappingTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System.Diagnostics.CodeAnalysis; #endregion @@ -19,8 +19,8 @@ public class UnixRootItemMappingTests public void ToTreeNodeResponse_WhenMappingUnixRootItem_ShouldMapCorrectly() { // Arrange - ErrorOr createResult = UnixRootItem.Create(); - Assert.False(createResult.IsError); + Result createResult = UnixRootItem.Create(); + Assert.False(createResult.IsFailure); UnixRootItem domainModel = createResult.Value; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMappingTests.cs index 0166a96b..50beb89a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMappingTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System.Diagnostics.CodeAnalysis; #endregion @@ -21,8 +21,8 @@ public class WindowsRootItemMappingTests // Arrange string path = "C:\\"; string name = "C:"; - ErrorOr createResult = WindowsRootItem.Create(path, name); - Assert.False(createResult.IsError); + Result createResult = WindowsRootItem.Create(path, name); + Assert.False(createResult.IsFailure); WindowsRootItem domainModel = createResult.Value; // Act @@ -45,8 +45,8 @@ public class WindowsRootItemMappingTests string path = "D:\\"; string name = "D:"; FileSystemItemStatus customStatus = FileSystemItemStatus.Inaccessible; - ErrorOr createResult = WindowsRootItem.Create(path, name, customStatus); - Assert.False(createResult.IsError); + Result createResult = WindowsRootItem.Create(path, name, customStatus); + Assert.False(createResult.IsFailure); WindowsRootItem domainModel = createResult.Value; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/PathSegmentMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/PathSegmentMappingTests.cs index de4dfccf..e3ffa525 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/PathSegmentMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/PathSegmentMappingTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -20,8 +20,8 @@ public class PathSegmentMappingTests public void ToResponse_WhenMappingPathSegment_ShouldMapCorrectly() { // Arrange - ErrorOr createResult = PathSegment.Create("TestSegment", true, false); - Assert.False(createResult.IsError); + Result createResult = PathSegment.Create("TestSegment", true, false); + Assert.False(createResult.IsFailure); PathSegment pathSegment = createResult.Value; // Act @@ -39,8 +39,8 @@ public class PathSegmentMappingTests public void ToResponse_WhenMappingDifferentPathSegmentTypes_ShouldMapCorrectly(string name, bool isDirectory, bool isDrive) { // Arrange - ErrorOr createResult = PathSegment.Create(name, isDirectory, isDrive); - Assert.False(createResult.IsError); + Result createResult = PathSegment.Create(name, isDirectory, isDrive); + Assert.False(createResult.IsFailure); PathSegment pathSegment = createResult.Value; // Act @@ -69,7 +69,7 @@ public class PathSegmentMappingTests // Assert Assert.NotNull(results); Assert.Equal(pathSegments.Count, results.Count()); - List resultList = results.ToList(); + List resultList = [.. results]; for (int i = 0; i < pathSegments.Count; i++) Assert.Equal(pathSegments[i].Name, resultList[i].Path); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs index 56b3e5a2..ddf36d96 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -25,7 +25,7 @@ public class LibraryMappingTests public void ToRepositoryEntity_WhenMappingValidLibrary_ShouldMapCorrectly() { // Arrange - ErrorOr libraryResult = Library.Create( + Result libraryResult = Library.Create( UserId.CreateUnique(), "Test Library", LibraryType.Book, @@ -64,7 +64,7 @@ public class LibraryMappingTests public void ToRepositoryEntity_WhenMappingLibraryWithEmptyContentLocations_ShouldMapCorrectly() { // Arrange - ErrorOr libraryResult = Library.Create( + Result libraryResult = Library.Create( UserId.CreateUnique(), "Empty Library", LibraryType.Book, @@ -96,7 +96,7 @@ public class LibraryMappingTests public void ToRepositoryEntity_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType) { // Arrange - ErrorOr libraryResult = Library.Create( + Result libraryResult = Library.Create( UserId.CreateUnique(), "Test Library", libraryType, @@ -136,7 +136,7 @@ public class LibraryMappingTests "F:/Reading Material" ]; - ErrorOr libraryResult = Library.Create( + Result libraryResult = Library.Create( UserId.CreateUnique(), "Test Library", LibraryType.Book, @@ -170,7 +170,7 @@ public class LibraryMappingTests "D:/Books" ]; - ErrorOr libraryResult = Library.Create( + Result libraryResult = Library.Create( UserId.CreateUnique(), "Test Library", LibraryType.Book, @@ -204,7 +204,7 @@ public class LibraryMappingTests "D:/Books" ]; - ErrorOr libraryResult = Library.Create( + Result libraryResult = Library.Create( UserId.CreateUnique(), "Test Library", LibraryType.Book, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs index 8a09e1ca..5a4aa400 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -37,10 +37,10 @@ public class BookEntityMappingTests BookEntity bookEntity = _bookEntityFixture.CreateBook(); // Act - ErrorOr result = bookEntity.ToDomainEntity(); + Result result = bookEntity.ToDomainEntity(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(bookEntity.Id, result.Value.Id.Value); Assert.Equal(bookEntity.Title, result.Value.Metadata.Title); @@ -325,12 +325,12 @@ public class BookEntityMappingTests ]; // Act - IEnumerable> results = bookEntities.ToDomainEntities(); + IEnumerable> results = bookEntities.ToDomainEntities(); // Assert Assert.NotNull(results); Assert.Equal(bookEntities.Count, results.Count()); - Assert.All(results, result => Assert.False(result.IsError)); + Assert.All(results, result => Assert.False(result.IsFailure)); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs index 33c584ac..453c8a41 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; @@ -26,10 +26,10 @@ public class BookMetadataDtoMappingTests BookMetadataDto metadata = CreateBookMetadata("The Fellowship of the Ring", "3"); // Act - ErrorOr result = book.ApplyMetadata(metadata, "Goodreads", DateTime.UtcNow); + Result result = book.ApplyMetadata(metadata, "Goodreads", DateTime.UtcNow); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal("The Fellowship of the Ring", book.Metadata.Title); Assert.Equal("3", book.GoodreadsId.Value); Assert.Equal("The first part of J.R.R. Tolkien's epic adventure.", book.Metadata.Description.Value); @@ -51,10 +51,10 @@ public class BookMetadataDtoMappingTests }; // Act - ErrorOr result = book.ApplyMetadata(metadata, "Goodreads", DateTime.UtcNow); + Result result = book.ApplyMetadata(metadata, "Goodreads", DateTime.UtcNow); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(MetadataStatus.Pending, book.MetadataStatus); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMappingTests.cs index d21f43d2..33735503 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMappingTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -35,10 +35,10 @@ public class BookRatingDtoMappingTests BookRatingDto dto = _bookRatingDtoFixture.CreateComplete(); // Act - ErrorOr result = dto.ToDomainEntity(); + Result result = dto.ToDomainEntity(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(dto.Value!.Value, result.Value.Value); Assert.Equal(dto.MaxValue!.Value, result.Value.MaxValue); @@ -67,10 +67,10 @@ public class BookRatingDtoMappingTests BookRatingDto dto = _bookRatingDtoFixture.CreateMinimal(); // Act - ErrorOr result = dto.ToDomainEntity(); + Result result = dto.ToDomainEntity(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(dto.Value!.Value, result.Value.Value); Assert.Equal(dto.MaxValue!.Value, result.Value.MaxValue); @@ -85,10 +85,10 @@ public class BookRatingDtoMappingTests BookRatingDto dto = _bookRatingDtoFixture.CreateInvalid(); // Act - ErrorOr result = dto.ToDomainEntity(); + Result result = dto.ToDomainEntity(); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); } [Fact] @@ -102,15 +102,15 @@ public class BookRatingDtoMappingTests ]; // Act - IEnumerable> results = dtos.ToDomainEntities(); + IEnumerable> results = dtos.ToDomainEntities(); // Assert Assert.NotNull(results); Assert.Equal(dtos.Count, results.Count()); - List> resultList = results.ToList(); - foreach (ErrorOr result in resultList) - Assert.False(result.IsError); + List> resultList = [.. results]; + foreach (Result result in resultList) + Assert.False(result.IsFailure); // complete rating Assert.Equal(dtos[0].Value!.Value, resultList[0].Value.Value); @@ -137,16 +137,16 @@ public class BookRatingDtoMappingTests ]; // Act - IEnumerable> results = dtos.ToDomainEntities(); + IEnumerable> results = dtos.ToDomainEntities(); // Assert Assert.NotNull(results); Assert.Equal(dtos.Count, results.Count()); - List> resultList = results.ToList(); + List> resultList = [.. results]; - Assert.False(resultList[0].IsError); - Assert.True(resultList[1].IsError); - Assert.False(resultList[2].IsError); + Assert.False(resultList[0].IsFailure); + Assert.True(resultList[1].IsFailure); + Assert.False(resultList[2].IsFailure); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMappingTests.cs index 83905083..b54392d6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMappingTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -95,10 +95,10 @@ public class BookRatingEntityMappingTests BookRatingEntity entity = _fixture.CreateBookRating(); // Act - ErrorOr result = entity.ToDomainEntity(); + Result result = entity.ToDomainEntity(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(entity.Value, result.Value.Value); Assert.Equal(entity.MaxValue, result.Value.MaxValue); @@ -113,10 +113,10 @@ public class BookRatingEntityMappingTests BookRatingEntity entity = _fixture.CreateInvalidBookRating(); // Act - ErrorOr result = entity.ToDomainEntity(); + Result result = entity.ToDomainEntity(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(default, result.Value.Value); Assert.Equal(default, result.Value.MaxValue); @@ -135,14 +135,14 @@ public class BookRatingEntityMappingTests ]; // Act - IEnumerable> results = entities.ToDomainEntities(); + IEnumerable> results = entities.ToDomainEntities(); // Assert Assert.NotNull(results); Assert.Equal(entities.Count, results.Count()); - foreach (ErrorOr result in results) + foreach (Result result in results) { - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.InRange(result.Value.Value, 1, 5); Assert.Equal(5, result.Value.MaxValue); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMappingTests.cs index d8510d2c..7bee8e6e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMappingTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -36,10 +36,10 @@ public class IsbnDtoMappingTests IsbnDto dto = _isbnDtoFixture.CreateIsbn10(); // Act - ErrorOr result = dto.ToDomainEntity(); + Result result = dto.ToDomainEntity(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(dto.Value, result.Value.Value); Assert.Equal(dto.Format!.Value, result.Value.Format); @@ -52,10 +52,10 @@ public class IsbnDtoMappingTests IsbnDto dto = _isbnDtoFixture.CreateIsbn13(); // Act - ErrorOr result = dto.ToDomainEntity(); + Result result = dto.ToDomainEntity(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(dto.Value, result.Value.Value); Assert.Equal(dto.Format!.Value, result.Value.Format); @@ -68,10 +68,10 @@ public class IsbnDtoMappingTests IsbnDto dto = _isbnDtoFixture.CreateWithoutFormat(); // Act - ErrorOr result = dto.ToDomainEntity(); + Result result = dto.ToDomainEntity(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(dto.Value, result.Value.Value); Assert.Equal(IsbnFormat.Isbn13, result.Value.Format); // default format @@ -84,10 +84,10 @@ public class IsbnDtoMappingTests IsbnDto dto = _isbnDtoFixture.CreateInvalid(); // Act - ErrorOr result = dto.ToDomainEntity(); + Result result = dto.ToDomainEntity(); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); } [Fact] @@ -102,14 +102,14 @@ public class IsbnDtoMappingTests ]; // Act - IEnumerable> results = dtos.ToDomainEntities(); + IEnumerable> results = dtos.ToDomainEntities(); // Assert Assert.NotNull(results); Assert.Equal(dtos.Count, results.Count()); - List> resultList = results.ToList(); - Assert.All(resultList, result => Assert.False(result.IsError)); + List> resultList = [.. results]; + Assert.All(resultList, result => Assert.False(result.IsFailure)); Assert.Equal(dtos[0].Value, resultList[0].Value.Value); Assert.Equal(dtos[0].Format!.Value, resultList[0].Value.Format); @@ -133,20 +133,20 @@ public class IsbnDtoMappingTests ]; // Act - IEnumerable> results = dtos.ToDomainEntities(); + IEnumerable> results = dtos.ToDomainEntities(); // Assert Assert.NotNull(results); Assert.Equal(dtos.Count, results.Count()); - List> resultList = results.ToList(); + List> resultList = [.. results]; - Assert.False(resultList[0].IsError); + Assert.False(resultList[0].IsFailure); Assert.Equal(dtos[0].Value, resultList[0].Value.Value); - Assert.True(resultList[1].IsError); + Assert.True(resultList[1].IsFailure); - Assert.False(resultList[2].IsError); + Assert.False(resultList[2].IsFailure); Assert.Equal(dtos[2].Value, resultList[2].Value.Value); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMappingTests.cs index 10ac45c7..9fb56684 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMappingTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -75,10 +75,10 @@ public class IsbnEntityMappingTests IsbnEntity entity = new("0-7475-3269-9", IsbnFormat.Isbn10); // Act - ErrorOr result = entity.ToDomainEntity(); + Result result = entity.ToDomainEntity(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(entity.Value, result.Value.Value); Assert.Equal(entity.Format, result.Value.Format); @@ -94,10 +94,10 @@ public class IsbnEntityMappingTests IsbnEntity entity = new(invalidValue, null); // Act - ErrorOr result = entity.ToDomainEntity(); + Result result = entity.ToDomainEntity(); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); } [Fact] @@ -111,16 +111,16 @@ public class IsbnEntityMappingTests ]; // Act - IEnumerable> results = entities.ToDomainEntities(); + IEnumerable> results = entities.ToDomainEntities(); // Assert Assert.NotNull(results); Assert.Equal(entities.Count, results.Count()); - List> resultList = results.ToList(); + List> resultList = [.. results]; for (int i = 0; i < entities.Count; i++) { - Assert.False(resultList[i].IsError); + Assert.False(resultList[i].IsFailure); Assert.Equal(entities[i].Value, resultList[i].Value.Value); Assert.Equal(entities[i].Format, resultList[i].Value.Format); } @@ -143,7 +143,7 @@ public class IsbnEntityMappingTests Assert.NotNull(results); Assert.Equal(entities.Count, results.Count()); - List resultList = results.ToList(); + List resultList = [.. results]; for (int i = 0; i < entities.Count; i++) { Assert.Equal(entities[i].Value, resultList[i].Value); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs index bc7b3506..cc9acf45 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs index bd6fe545..839ef23b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; @@ -8,6 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using NSubstitute; using System; @@ -67,13 +67,13 @@ public class GetPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); _mockPermissionRepository.GetAllAsync(Arg.Any()) - .Returns(ErrorOrFactory.From(permissions)); + .Returns(Result.From(permissions)); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); await _mockAuthorizationService.Received(1).IsInRoleAsync(_userId, "Admin", Arg.Any()); await _mockPermissionRepository.Received(1).GetAllAsync(Arg.Any()); @@ -89,10 +89,10 @@ public class GetPermissionsQueryHandlerTests .Returns(false); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.Received(1).IsInRoleAsync(_userId, "Admin", Arg.Any()); await _mockPermissionRepository.DidNotReceive().GetAllAsync(Arg.Any()); @@ -111,10 +111,10 @@ public class GetPermissionsQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockAuthorizationService.Received(1).IsInRoleAsync(_userId, "Admin", Arg.Any()); await _mockPermissionRepository.Received(1).GetAllAsync(Arg.Any()); @@ -134,13 +134,13 @@ public class GetPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); _mockPermissionRepository.GetAllAsync(Arg.Any()) - .Returns(ErrorOrFactory.From(permissions)); + .Returns(Result.From(permissions)); // Act - ErrorOr> result = await _sut.HandleAsync(query, cancellationToken); + Result> result = await _sut.HandleAsync(query, cancellationToken); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(result.Value); await _mockAuthorizationService.Received(1).IsInRoleAsync(_userId, "Admin", Arg.Any()); await _mockPermissionRepository.Received(1).GetAllAsync(Arg.Any()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs index 9360cef3..85dd0206 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; @@ -10,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.AddRole.Fixtures; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using NSubstitute; using System; @@ -69,10 +69,10 @@ public class AddRoleCommandHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockRoleRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); } @@ -90,10 +90,10 @@ public class AddRoleCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -113,10 +113,10 @@ public class AddRoleCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); } @@ -134,10 +134,10 @@ public class AddRoleCommandHandlerTests .Returns((RoleEntity?)null); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Persistence.ErrorPersistingAuthorizationRole, result.FirstError); } @@ -172,10 +172,10 @@ public class AddRoleCommandHandlerTests .Returns(role); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(command.RoleName, result.Value.Role.RoleName); Assert.Equal(command.Permissions.Count, result.Value.Permissions.Length); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs index 818773ac..47eb0c52 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.AddRole.Fixtures; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs index fd583879..6f572422 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; @@ -9,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.DeleteRole.Fixtures; +using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -66,10 +66,10 @@ public class DeleteRoleCommandHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockRoleRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); } @@ -86,10 +86,10 @@ public class DeleteRoleCommandHandlerTests .Returns((RoleEntity?)null); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.RoleNotFound, result.FirstError); await _mockRoleRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); } @@ -107,10 +107,10 @@ public class DeleteRoleCommandHandlerTests .Returns(adminRole); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.AdminRoleCannotBeDeleted, result.FirstError); await _mockRoleRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); } @@ -128,10 +128,10 @@ public class DeleteRoleCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockRoleRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); } @@ -152,10 +152,10 @@ public class DeleteRoleCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -175,10 +175,10 @@ public class DeleteRoleCommandHandlerTests .Returns(Result.Deleted); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs index 4df71485..4f0203ad 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs index a9f585d6..04ee7836 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; @@ -10,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.UpdateRole.Fixtures; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using NSubstitute; using System; @@ -69,10 +69,10 @@ public class UpdateRoleCommandHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockRoleRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); } @@ -90,10 +90,10 @@ public class UpdateRoleCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -113,10 +113,10 @@ public class UpdateRoleCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); } @@ -134,10 +134,10 @@ public class UpdateRoleCommandHandlerTests .Returns((RoleEntity?)null); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Persistence.ErrorPersistingAuthorizationRole, result.FirstError); } @@ -171,10 +171,10 @@ public class UpdateRoleCommandHandlerTests .Returns(role); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(command.RoleName, result.Value.Role.RoleName); Assert.Equal(command.Permissions.Count, result.Value.Permissions.Length); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs index e42d4bfb..3bdd1653 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.UpdateRole.Fixtures; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs index 8d0516d8..c51c2caf 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; @@ -10,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.GetRolePermissions.Fixtures; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using NSubstitute; using System; @@ -68,10 +68,10 @@ public class GetRolePermissionsQueryHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); } @@ -89,10 +89,10 @@ public class GetRolePermissionsQueryHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); } @@ -108,10 +108,10 @@ public class GetRolePermissionsQueryHandlerTests .Returns((RoleEntity?)null); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.RoleNotFound, result.FirstError); } @@ -146,10 +146,10 @@ public class GetRolePermissionsQueryHandlerTests .Returns(role); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(role.RoleName, result.Value.Role.RoleName); Assert.Single(result.Value.Permissions); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs index 55015c30..041f3e86 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs index 31a3da85..bcf6ae4e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; @@ -9,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.GetRoles.Fixtures; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Collections.Generic; @@ -63,10 +63,10 @@ public class GetRolesQueryHandlerTests .Returns(false); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockRoleRepository.DidNotReceive().GetAllAsync(Arg.Any()); } @@ -84,10 +84,10 @@ public class GetRolesQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); } @@ -105,13 +105,13 @@ public class GetRolesQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); _mockRoleRepository.GetAllAsync(Arg.Any()) - .Returns(ErrorOrFactory.From(roles)); + .Returns(Result.From(roles)); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryFixture.cs index 2a9ce732..46439b3c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryFixture.cs @@ -1,10 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -54,9 +53,9 @@ public class DirectoryFixture dateModified ??= Optional.Some(_faker.Date.Recent()); status ??= _faker.PickRandom(); - ErrorOr directoryResult = Directory.Create(path, name, dateCreated.Value, dateModified.Value, status.Value); + Result directoryResult = Directory.Create(path, name, dateCreated.Value, dateModified.Value, status.Value); - if (directoryResult.IsError) + if (directoryResult.IsFailure) throw new InvalidOperationException("Failed to create Directory: " + string.Join(", ", directoryResult.Errors)); Directory directory = directoryResult.Value; @@ -73,7 +72,7 @@ public class DirectoryFixture /// The created list. public List CreateMany(int count = 3) { - return Enumerable.Range(0, count).Select(_ => CreateDirectory()).ToList(); + return [.. Enumerable.Range(0, count).Select(_ => CreateDirectory())]; } /// @@ -85,7 +84,7 @@ public class DirectoryFixture /// A list of objects with nested structures. public List CreateManyNested(int count = 3, int maxDepth = 3, int maxChildrenPerDirectory = 3) { - return Enumerable.Range(0, count).Select(_ => CreateNestedDirectory(1, maxDepth, maxChildrenPerDirectory)).ToList(); + return [.. Enumerable.Range(0, count).Select(_ => CreateNestedDirectory(1, maxDepth, maxChildrenPerDirectory))]; } /// @@ -106,8 +105,8 @@ public class DirectoryFixture for (int i = 0; i < childCount; i++) { Directory childDirectory = CreateNestedDirectory(currentDepth + 1, maxDepth, maxChildrenPerDirectory); - ErrorOr addResult = childDirectory.SetParent(childDirectory); - if (!addResult.IsError) + Result addResult = childDirectory.SetParent(childDirectory); + if (!addResult.IsFailure) childItems.Add(childDirectory); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs index 02a7b600..87239c91 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures; using Lumina.Contracts.Responses.FileSystemManagement.Directories; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; -using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using NSubstitute; using System; using System.Collections.Generic; @@ -54,18 +54,18 @@ public class GetDirectoriesQueryHandlerTests IEnumerable directories = _directoryFixture.CreateMany(); _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements) - .Returns(ErrorOrFactory.From(directories)); + .Returns(Result.From(directories)); // Act - ErrorOr> result = await _sut.HandleAsync(getDirectoriesQuery, CancellationToken.None); + Result> result = await _sut.HandleAsync(getDirectoriesQuery, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.IsAssignableFrom>(result.Value); Assert.Equal(directories.Count(), result.Value.Count()); - List resultList = result.Value.ToList(); - List directoriesList = directories.ToList(); + List resultList = [.. result.Value]; + List directoriesList = [.. directories]; for (int i = 0; i < resultList.Count; i++) { @@ -88,18 +88,18 @@ public class GetDirectoriesQueryHandlerTests IEnumerable directories = _directoryFixture.CreateMany(); _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements) - .Returns(ErrorOrFactory.From(directories)); + .Returns(Result.From(directories)); // Act - ErrorOr> result = await _sut.HandleAsync(getDirectoriesQuery, CancellationToken.None); + Result> result = await _sut.HandleAsync(getDirectoriesQuery, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.IsAssignableFrom>(result.Value); Assert.Equal(directories.Count(), result.Value.Count()); - List resultList = result.Value.ToList(); - List directoriesList = directories.ToList(); + List resultList = [.. result.Value]; + List directoriesList = [.. directories]; for (int i = 0; i < resultList.Count; i++) { @@ -123,10 +123,10 @@ public class GetDirectoriesQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); _mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements); } @@ -136,15 +136,15 @@ public class GetDirectoriesQueryHandlerTests { // Arrange GetDirectoriesQuery query = _fixture.Create(); - ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); + Result> emptyList = Result.From(Enumerable.Empty()); _mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements) .Returns(emptyList); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Empty(result.Value); _mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs index 78c3fd9f..72e62536 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using Lumina.Domain.SharedKernel.Common.Errors; #endregion namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs index 80b5ce4c..dcde9de5 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -51,18 +51,18 @@ public class GetDrivesQueryHandlerTests ]; _mockDriveService.GetDrives() - .Returns(ErrorOrFactory.From(drives)); + .Returns(Result.From(drives)); // Act - ErrorOr> result = await _sut.HandleAsync(getDrivesQuery, CancellationToken.None); + Result> result = await _sut.HandleAsync(getDrivesQuery, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.IsAssignableFrom>(result.Value); Assert.Equal(drives.Count(), result.Value.Count()); - List resultList = result.Value.ToList(); - List drivesList = drives.ToList(); + List resultList = [.. result.Value]; + List drivesList = [.. drives]; for (int i = 0; i < resultList.Count; i++) { @@ -90,10 +90,10 @@ public class GetDrivesQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); _mockDriveService.Received(1).GetDrives(); } @@ -103,15 +103,15 @@ public class GetDrivesQueryHandlerTests { // Arrange GetDrivesQuery query = _fixture.Create(); - ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); + Result> emptyList = Result.From(Enumerable.Empty()); _mockDriveService.GetDrives() .Returns(emptyList); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Empty(result.Value); _mockDriveService.Received(1).GetDrives(); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/UnixRootItemFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/UnixRootItemFixture.cs index c7235f33..25702e7c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/UnixRootItemFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/UnixRootItemFixture.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -23,10 +23,10 @@ public class UnixRootItemFixture /// The created . public UnixRootItem Create() { - ErrorOr unixRootItemResult = UnixRootItem.Create( + Result unixRootItemResult = UnixRootItem.Create( _faker.PickRandom() ); - if (unixRootItemResult.IsError) + if (unixRootItemResult.IsFailure) throw new InvalidOperationException("Failed to create File: " + string.Join(", ", unixRootItemResult.Errors)); return unixRootItemResult.Value; } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/WindowsRootItemFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/WindowsRootItemFixture.cs index 232a0c9d..7acc0bc8 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/WindowsRootItemFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/WindowsRootItemFixture.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -23,12 +23,12 @@ public class WindowsRootItemFixture /// The created . public WindowsRootItem Create() { - ErrorOr windowsRootItemResult = WindowsRootItem.Create( + Result windowsRootItemResult = WindowsRootItem.Create( _faker.System.FilePath(), _faker.System.FileName(), _faker.PickRandom() ); - if (windowsRootItemResult.IsError) + if (windowsRootItemResult.IsFailure) throw new InvalidOperationException("Failed to create File: " + string.Join(", ", windowsRootItemResult.Errors)); return windowsRootItemResult.Value; } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileFixture.cs index 8a285bfb..10e2e435 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileFixture.cs @@ -1,9 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -47,9 +46,9 @@ public class FileFixture size ??= _faker.Random.Long(); status ??= _faker.PickRandom(); - ErrorOr fileResult = File.Create(path, name, dateCreated.Value, dateModified.Value, size.Value, status.Value); + Result fileResult = File.Create(path, name, dateCreated.Value, dateModified.Value, size.Value, status.Value); - if (fileResult.IsError) + if (fileResult.IsFailure) throw new InvalidOperationException("Failed to create File: " + string.Join(", ", fileResult.Errors)); return fileResult.Value; } @@ -61,7 +60,7 @@ public class FileFixture /// The created list. public List CreateMany(int count = 3) { - return Enumerable.Range(0, count).Select(_ => CreateFile()).ToList(); + return [.. Enumerable.Range(0, count).Select(_ => CreateFile())]; } /// diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs index a24e463d..95e95d31 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures; using Lumina.Contracts.Responses.FileSystemManagement.Files; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System; using System.Collections.Generic; @@ -54,18 +54,18 @@ public class GetFilesQueryHandlerTests IEnumerable files = _fileFixture.CreateMany(); _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements) - .Returns(ErrorOrFactory.From(files)); + .Returns(Result.From(files)); // Act - ErrorOr> result = await _sut.HandleAsync(getFilesQuery, CancellationToken.None); + Result> result = await _sut.HandleAsync(getFilesQuery, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.IsAssignableFrom>(result.Value); Assert.Equal(files.Count(), result.Value.Count()); - List resultList = result.Value.ToList(); - List filesList = files.ToList(); + List resultList = [.. result.Value]; + List filesList = [.. files]; for (int i = 0; i < resultList.Count; i++) { @@ -88,18 +88,18 @@ public class GetFilesQueryHandlerTests IEnumerable files = _fileFixture.CreateMany(); _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements) - .Returns(ErrorOrFactory.From(files)); + .Returns(Result.From(files)); // Act - ErrorOr> result = await _sut.HandleAsync(getFilesQuery, CancellationToken.None); + Result> result = await _sut.HandleAsync(getFilesQuery, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.IsAssignableFrom>(result.Value); Assert.Equal(files.Count(), result.Value.Count()); - List resultList = result.Value.ToList(); - List filesList = files.ToList(); + List resultList = [.. result.Value]; + List filesList = [.. files]; for (int i = 0; i < resultList.Count; i++) { @@ -123,10 +123,10 @@ public class GetFilesQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); _mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements); } @@ -136,15 +136,15 @@ public class GetFilesQueryHandlerTests { // Arrange GetFilesQuery query = _fixture.Create(); - ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); + Result> emptyList = Result.From(Enumerable.Empty()); _mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements) .Returns(emptyList); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Empty(result.Value); _mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs index 94c96481..7b0bcb57 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs index 7e1bfa0c..312c61cf 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs @@ -1,15 +1,15 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -54,18 +54,18 @@ public class GetTreeFilesQueryHandlerTests IEnumerable files = _fileFixture.CreateMany(); _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements) - .Returns(ErrorOrFactory.From(files)); + .Returns(Result.From(files)); // Act - ErrorOr> result = await _sut.HandleAsync(getFilesQuery, CancellationToken.None); + Result> result = await _sut.HandleAsync(getFilesQuery, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.IsAssignableFrom>(result.Value); Assert.Equal(files.Count(), result.Value.Count()); - List resultList = result.Value.ToList(); - List filesList = files.ToList(); + List resultList = [.. result.Value]; + List filesList = [.. files]; for (int i = 0; i < resultList.Count; i++) { @@ -89,18 +89,18 @@ public class GetTreeFilesQueryHandlerTests IEnumerable files = _fileFixture.CreateMany(); _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements) - .Returns(ErrorOrFactory.From(files)); + .Returns(Result.From(files)); // Act - ErrorOr> result = await _sut.HandleAsync(getFilesQuery, CancellationToken.None); + Result> result = await _sut.HandleAsync(getFilesQuery, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.IsAssignableFrom>(result.Value); Assert.Equal(files.Count(), result.Value.Count()); - List resultList = result.Value.ToList(); - List filesList = files.ToList(); + List resultList = [.. result.Value]; + List filesList = [.. files]; for (int i = 0; i < resultList.Count; i++) { @@ -125,10 +125,10 @@ public class GetTreeFilesQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); _mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements); } @@ -138,15 +138,15 @@ public class GetTreeFilesQueryHandlerTests { // Arrange GetTreeFilesQuery query = _fixture.Create(); - ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); + Result> emptyList = Result.From(Enumerable.Empty()); _mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements) .Returns(emptyList); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Empty(result.Value); _mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs index e62ae42d..e46661f3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Fixtures/FileSystemPathIdFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Fixtures/FileSystemPathIdFixture.cs index 3e85e421..e073633a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Fixtures/FileSystemPathIdFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Fixtures/FileSystemPathIdFixture.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; @@ -33,9 +33,9 @@ public class FileSystemPathIdFixture { path ??= _faker.System.FilePath(); - ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); + Result fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) + if (fileSystemPathIdResult.IsFailure) throw new InvalidOperationException("Failed to create FileSystemPathId: " + string.Join(", ", fileSystemPathIdResult.Errors)); return fileSystemPathIdResult.Value; } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs index 3f954981..32a87b9c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; @@ -46,13 +46,13 @@ public class CombinePathCommandHandlerTests string combinedPath = System.IO.Path.Combine(combinePathCommand.OriginalPath!, combinePathCommand.NewPath!); _mockPathService.CombinePath(combinePathCommand.OriginalPath!, combinePathCommand.NewPath!) - .Returns(ErrorOrFactory.From(combinedPath)); + .Returns(Result.From(combinedPath)); // Act - ErrorOr result = await _sut.HandleAsync(combinePathCommand, CancellationToken.None); + Result result = await _sut.HandleAsync(combinePathCommand, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.IsType(result.Value); Assert.Equal(combinedPath, result.Value.Path); _mockPathService.Received(1).CombinePath(combinePathCommand.OriginalPath!, combinePathCommand.NewPath!); @@ -68,10 +68,10 @@ public class CombinePathCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); _mockPathService.Received(1).CombinePath(command.OriginalPath!, command.NewPath!); } @@ -82,13 +82,13 @@ public class CombinePathCommandHandlerTests // Arrange CombinePathCommand command = _fixture.Create(); _mockPathService.CombinePath(command.OriginalPath!, command.NewPath!) - .Returns(ErrorOrFactory.From(string.Empty)); + .Returns(Result.From(string.Empty)); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.IsType(result.Value); Assert.Empty(result.Value.Path); _mockPathService.Received(1).CombinePath(command.OriginalPath!, command.NewPath!); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs index 856582db..5d120a30 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs index 247c5cae..ea388a71 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System; using System.Collections.Generic; @@ -54,18 +54,18 @@ public class SplitPathCommandHandlerTests IEnumerable pathSegments = _pathSegmentFixture.CreateMany(); _mockPathService.ParsePath(splitPathCommand.Path!) - .Returns(ErrorOrFactory.From(pathSegments)); + .Returns(Result.From(pathSegments)); // Act - ErrorOr> result = await _sut.HandleAsync(splitPathCommand, CancellationToken.None); + Result> result = await _sut.HandleAsync(splitPathCommand, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.IsAssignableFrom>(result.Value); Assert.Equal(pathSegments.Count(), result.Value.Count()); - List resultList = result.Value.ToList(); - List segmentsList = pathSegments.ToList(); + List resultList = [.. result.Value]; + List segmentsList = [.. pathSegments]; for (int i = 0; i < resultList.Count; i++) Assert.Equal(segmentsList[i].Name, resultList[i].Path); @@ -82,10 +82,10 @@ public class SplitPathCommandHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.HandleAsync(command, CancellationToken.None); + Result> result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); _mockPathService.Received(1).ParsePath(command.Path!); } @@ -95,15 +95,15 @@ public class SplitPathCommandHandlerTests { // Arrange SplitPathCommand command = _fixture.Create(); - ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); + Result> emptyList = Result.From(Enumerable.Empty()); _mockPathService.ParsePath(command.Path!) .Returns(emptyList); // Act - ErrorOr> result = await _sut.HandleAsync(command, CancellationToken.None); + Result> result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Empty(result.Value); _mockPathService.Received(1).ParsePath(command.Path!); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs index 04e34a2e..ef65ce42 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentFixture.cs index 9104707a..2f0932ff 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentFixture.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; @@ -39,9 +39,9 @@ public class PathSegmentFixture isDirectory ??= true; isDrive ??= false; - ErrorOr pathResult = PathSegment.Create(name, isDirectory.Value, isDrive.Value); + Result pathResult = PathSegment.Create(name, isDirectory.Value, isDrive.Value); - if (pathResult.IsError) + if (pathResult.IsFailure) throw new InvalidOperationException("Failed to create PathSegment: " + string.Join(", ", pathResult.Errors)); return pathResult.Value; } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs index 5c0569a8..e2490c47 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; @@ -42,10 +42,10 @@ public class CheckPathExistsQueryHandlerTests _mockPathService.Exists(query.Path!).Returns(true); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.True(result.Value.Exists); _mockPathService.Received(1).Exists(query.Path!); } @@ -58,10 +58,10 @@ public class CheckPathExistsQueryHandlerTests _mockPathService.Exists(query.Path!).Returns(true); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.True(result.Value.Exists); _mockPathService.Received(1).Exists(query.Path!); } @@ -74,10 +74,10 @@ public class CheckPathExistsQueryHandlerTests _mockPathService.Exists(query.Path!, false).Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.False(result.Value.Exists); _mockPathService.Received(1).Exists(query.Path!, false); } @@ -90,10 +90,10 @@ public class CheckPathExistsQueryHandlerTests _mockPathService.Exists(query.Path!).Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.False(result.Value.Exists); _mockPathService.Received(1).Exists(query.Path!); } @@ -106,10 +106,10 @@ public class CheckPathExistsQueryHandlerTests _mockPathService.Exists(Arg.Any(), Arg.Any()).Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.False(result.Value.Exists); _mockPathService.Received(1).Exists(Arg.Any(), Arg.Any()); } @@ -123,10 +123,10 @@ public class CheckPathExistsQueryHandlerTests CancellationToken cancellationToken = new(true); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.True(result.Value.Exists); _mockPathService.Received(1).Exists(query.Path!); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs index 950bc114..c523476a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs index cf4e7044..96f20b34 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent.Fixtures; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -53,13 +53,13 @@ public class GetPathParentQueryHandlerTests IEnumerable pathSegmentResponses = pathSegments.Select(segment => new PathSegmentResponse(segment.Name)); _mockPathService.GoUpOneLevel(query.Path!) - .Returns(ErrorOrFactory.From(pathSegments)); + .Returns(Result.From(pathSegments)); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.IsAssignableFrom>(result.Value); Assert.Equal(pathSegmentResponses, result.Value); _mockPathService.Received(1).GoUpOneLevel(query.Path!); @@ -75,10 +75,10 @@ public class GetPathParentQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); _mockPathService.Received(1).GoUpOneLevel(query.Path!); } @@ -88,15 +88,15 @@ public class GetPathParentQueryHandlerTests { // Arrange GetPathParentQuery query = _fixture.Create(); - ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); + Result> emptyList = Result.From(Enumerable.Empty()); _mockPathService.GoUpOneLevel(query.Path!) .Returns(emptyList); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Empty(result.Value); _mockPathService.Received(1).GoUpOneLevel(query.Path!); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs index 10685253..bc4959ea 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent.Fixtures; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs index 1fb38b59..b9748e7e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot.Fixtures; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; @@ -46,13 +46,13 @@ public class GetPathRootQueryHandlerTests PathSegment pathSegment = _pathSegmentFixture.CreatePathSegment(isDrive: true); _mockPathService.GetPathRoot(query.Path!) - .Returns(ErrorOrFactory.From(pathSegment)); + .Returns(Result.From(pathSegment)); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(pathSegment.Name, result.Value.Path); _mockPathService.Received(1).GetPathRoot(query.Path!); @@ -68,10 +68,10 @@ public class GetPathRootQueryHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); _mockPathService.Received(1).GetPathRoot(query.Path!); } @@ -84,13 +84,13 @@ public class GetPathRootQueryHandlerTests PathSegment rootPathSegment = _pathSegmentFixture.CreatePathSegment(name: "/", isDirectory: true, isDrive: true); _mockPathService.GetPathRoot(query.Path!) - .Returns(ErrorOrFactory.From(rootPathSegment)); + .Returns(Result.From(rootPathSegment)); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal("/", result.Value.Path); _mockPathService.Received(1).GetPathRoot(query.Path!); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs index 96db357c..8ba380ed 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot.Fixtures; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs index dd62b385..86f705b0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Lumina.Domain.SharedKernel.Common.Errors; using NSubstitute; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -45,10 +44,10 @@ public class ValidatePathQueryHandlerTests _mockPathService.IsValidPath(query.Path!).Returns(true); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.True(result.Value.IsValid); _mockPathService.Received(1).IsValidPath(query.Path!); } @@ -61,10 +60,10 @@ public class ValidatePathQueryHandlerTests _mockPathService.IsValidPath(query.Path!).Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.False(result.Value.IsValid); _mockPathService.Received(1).IsValidPath(query.Path!); } @@ -77,10 +76,10 @@ public class ValidatePathQueryHandlerTests _mockPathService.IsValidPath(Arg.Any()).Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.False(result.Value.IsValid); _mockPathService.Received(1).IsValidPath(Arg.Any()); } @@ -93,10 +92,10 @@ public class ValidatePathQueryHandlerTests _mockPathService.IsValidPath(Arg.Any()).Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.False(result.Value.IsValid); _mockPathService.Received(1).IsValidPath(Arg.Any()); } @@ -110,10 +109,10 @@ public class ValidatePathQueryHandlerTests .Returns([Errors.FileSystemManagement.PathCannotBeEmpty]); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.PathCannotBeEmpty, result.FirstError); _mockPathService.DidNotReceive().IsValidPath(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs index 72cce88c..d9a2e01a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs index b0015000..493a3090 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Application.Common.Infrastructure.Validation; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; @@ -43,13 +43,13 @@ public class GetThumbnailQueryHandlerTests Thumbnail thumbnail = _fixture.Create(); _mockThumbnailService.GetThumbnailAsync(query.Path!, query.Quality, Arg.Any()) - .Returns(ErrorOrFactory.From(thumbnail)); + .Returns(Result.From(thumbnail)); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(thumbnail.Type, result.Value.Type); Assert.Equal(thumbnail.Bytes, result.Value.Bytes); @@ -66,10 +66,10 @@ public class GetThumbnailQueryHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockThumbnailService.Received(1).GetThumbnailAsync(query.Path!, query.Quality, Arg.Any()); } @@ -83,7 +83,7 @@ public class GetThumbnailQueryHandlerTests cts.Cancel(); _mockThumbnailService.GetThumbnailAsync(query.Path!, query.Quality, cts.Token) - .Returns(Task.FromCanceled>(cts.Token)); + .Returns(Task.FromCanceled>(cts.Token)); // Act & Assert await Assert.ThrowsAsync(() => _sut.HandleAsync(query, cts.Token)); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs index 87668442..3af9c041 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs index 62bf4ee3..b25800b3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.Seed; @@ -13,6 +12,7 @@ using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplica using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -80,17 +80,25 @@ public class SetupApplicationCommandHandlerTests string hashedPassword = Uri.EscapeDataString("hashedPassword"); _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); + .Returns(Result.From(Enumerable.Empty())); _mockHashService.HashString(command.Password!) .Returns(hashedPassword); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()) + .Returns(Result.Created); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(command.Username, result.Value.Username); Assert.Null(result.Value.TotpSecret); @@ -111,7 +119,7 @@ public class SetupApplicationCommandHandlerTests string encryptedSecret = "encryptedSecret"; _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); + .Returns(Result.From(Enumerable.Empty())); _mockHashService.HashString(command.Password!) .Returns(hashedPassword); _mockTotpTokenGenerator.GenerateSecret() @@ -122,12 +130,20 @@ public class SetupApplicationCommandHandlerTests .Returns(encryptedSecret); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()) + .Returns(Result.Created); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(command.Username, result.Value.Username); Assert.Equal(qrCodeUri, result.Value.TotpSecret); @@ -148,10 +164,10 @@ public class SetupApplicationCommandHandlerTests .Returns(new[] { existingUser }); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.AdminAccountAlreadyCreated, result.FirstError); await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); @@ -170,10 +186,10 @@ public class SetupApplicationCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); @@ -189,15 +205,15 @@ public class SetupApplicationCommandHandlerTests Error error = Error.Failure("Database.Error", "Failed to insert user"); _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); + .Returns(Result.From(Enumerable.Empty())); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); @@ -213,17 +229,17 @@ public class SetupApplicationCommandHandlerTests Error error = Error.Failure("Database.Error", "Failed to set default permissions"); _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); + .Returns(Result.From(Enumerable.Empty())); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()); @@ -238,7 +254,7 @@ public class SetupApplicationCommandHandlerTests Error error = Error.Failure("Database.Error", "Failed to set default roles"); _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); + .Returns(Result.From(Enumerable.Empty())); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -247,10 +263,10 @@ public class SetupApplicationCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()); @@ -266,7 +282,7 @@ public class SetupApplicationCommandHandlerTests Error error = Error.Failure("Database.Error", "Failed to set admin role permissions"); _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); + .Returns(Result.From(Enumerable.Empty())); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -277,10 +293,10 @@ public class SetupApplicationCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()); @@ -297,7 +313,7 @@ public class SetupApplicationCommandHandlerTests Error error = Error.Failure("Database.Error", "Failed to set admin role to administrator account"); _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); + .Returns(Result.From(Enumerable.Empty())); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -310,10 +326,10 @@ public class SetupApplicationCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()); @@ -329,7 +345,7 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); + .Returns(Result.From(Enumerable.Empty())); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -342,10 +358,10 @@ public class SetupApplicationCommandHandlerTests .Returns(Result.Created); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(command.Username, result.Value.Username); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs index 362ed891..8a2a6400 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs index 3dde8b07..a0f9cf1f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Contracts.Responses.UsersManagement; +using Lumina.Domain.Common.Primitives; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -45,7 +45,7 @@ public class CheckInitializationQueryHandlerTests // Arrange List users = UserEntityFixture.CreateMany(); _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(ErrorOrFactory.From(users.AsEnumerable())); + .Returns(Result.From(users.AsEnumerable())); // Act InitializationResponse result = await _sut.HandleAsync(new CheckInitializationQuery(), CancellationToken.None); @@ -60,7 +60,7 @@ public class CheckInitializationQueryHandlerTests { // Arrange _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); + .Returns(Result.From(Enumerable.Empty())); // Act InitializationResponse result = await _sut.HandleAsync(new CheckInitializationQuery(), CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs index 458933f1..a49b1e28 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; 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 Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -45,7 +45,7 @@ public class DomainLibraryFixture "F:/Content" ]; - ErrorOr library = Library.Create( + Result library = Library.Create( UserId.CreateUnique(), _faker.Random.String2(_faker.Random.Number(1, 50)), _faker.PickRandom(), @@ -76,7 +76,7 @@ public class DomainLibraryFixture bool shouldSkipUnchangedDirectoriesDuringScan = false, IEnumerable? scanIds = null) { - ErrorOr library = id is null ? + Result library = id is null ? Library.Create( userId is not null ? UserId.Create(userId.Value) : UserId.CreateUnique(), title ?? _faker.Random.String2(_faker.Random.Number(1, 50)), diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs index d667c227..7ec8e91a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; @@ -12,8 +11,9 @@ using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.Books using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -66,10 +66,10 @@ public class AddBookCommandHandlerTests .Returns(Result.Created); // Act - ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.IsType(result.Value); await _mockBookRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); @@ -85,10 +85,10 @@ public class AddBookCommandHandlerTests .Returns(Errors.WrittenContent.BookAlreadyExists); // Act - ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Contains(Errors.WrittenContent.BookAlreadyExists, result.Errors); await _mockBookRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); @@ -102,10 +102,10 @@ public class AddBookCommandHandlerTests bookCommand = bookCommand with { ISBNs = [new IsbnDto("invalid", IsbnFormat.Isbn13)] }; // Act - ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Contains(result.Errors, e => e.Description == Errors.WrittenContent.InvalidIsbn13Format.Description); await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); @@ -119,10 +119,10 @@ public class AddBookCommandHandlerTests bookCommand = bookCommand with { Ratings = [new BookRatingDto(-1, 5, null, null)] }; // Act - ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.RatingValueMustBePositive.Description); await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); @@ -142,10 +142,10 @@ public class AddBookCommandHandlerTests }; // Act - ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); @@ -165,10 +165,10 @@ public class AddBookCommandHandlerTests }; // Act - ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.TagNameCannotBeEmpty.Description); await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); @@ -195,10 +195,10 @@ public class AddBookCommandHandlerTests }; // Act - ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description); await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); @@ -218,10 +218,10 @@ public class AddBookCommandHandlerTests }; // Act - ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.LanguageCodeCannotBeEmpty.Description); await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); @@ -241,10 +241,10 @@ public class AddBookCommandHandlerTests }; // Act - ErrorOr result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.LanguageCodeCannotBeEmpty.Description); await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs index c08354e8..44ab26e7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using ErrorOr; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -409,7 +409,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = bookCommand.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = string.Empty } : genre).ToList() } }; + bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = [.. bookCommand.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = string.Empty } : genre)] } }; // Act List result = _validator.TestValidate(bookCommand); @@ -423,7 +423,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = bookCommand.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = new Faker().Random.String2(51) } : genre).ToList() } }; + bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = [.. bookCommand.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = new Faker().Random.String2(51) } : genre)] } }; // Act List result = _validator.TestValidate(bookCommand); @@ -441,7 +441,7 @@ public class AddBookCommandValidatorTests { Metadata = bookCommand.Metadata! with { - Genres = bookCommand.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = new Faker().Random.String2(50) } : genre).ToList() + Genres = [.. bookCommand.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = new Faker().Random.String2(50) } : genre)] } }; @@ -471,7 +471,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = bookCommand.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = string.Empty } : tag).ToList() } }; + bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = [.. bookCommand.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = string.Empty } : tag)] } }; // Act List result = _validator.TestValidate(bookCommand); @@ -485,7 +485,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = bookCommand.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = new Faker().Random.String2(51) } : tag).ToList() } }; + bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = [.. bookCommand.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = new Faker().Random.String2(51) } : tag)] } }; // Act List result = _validator.TestValidate(bookCommand); @@ -503,7 +503,7 @@ public class AddBookCommandValidatorTests { Metadata = bookCommand.Metadata! with { - Tags = bookCommand.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = new Faker().Random.String2(50) } : tag).ToList() + Tags = [.. bookCommand.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = new Faker().Random.String2(50) } : tag)] } }; @@ -1569,7 +1569,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = null! } : isbn).ToList() }; + bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = null! } : isbn)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1583,7 +1583,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn10 } : isbn).ToList() }; + bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn10 } : isbn)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1597,7 +1597,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn13 } : isbn).ToList() }; + bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn13 } : isbn)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1611,7 +1611,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Format = (IsbnFormat)99 } : isbn).ToList() }; + bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Format = (IsbnFormat)99 } : isbn)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1625,7 +1625,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = "0-306-40615-2", Format = IsbnFormat.Isbn10 } : isbn).ToList() }; + bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = "0-306-40615-2", Format = IsbnFormat.Isbn10 } : isbn)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1639,7 +1639,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = "978-3-16-148410-0", Format = IsbnFormat.Isbn13 } : isbn).ToList() }; + bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = "978-3-16-148410-0", Format = IsbnFormat.Isbn13 } : isbn)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1667,7 +1667,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = null! } : contributor).ToList() }; + bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = null! } : contributor)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1681,7 +1681,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = new Faker().Random.String2(101) } } : contributor).ToList() }; + bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = new Faker().Random.String2(101) } } : contributor)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1695,7 +1695,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = null! } } : contributor).ToList() }; + bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = null! } } : contributor)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1709,7 +1709,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { LegalName = new Faker().Random.String2(101) } } : contributor).ToList() }; + bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { LegalName = new Faker().Random.String2(101) } } : contributor)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1723,7 +1723,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = null! } : contributor).ToList() }; + bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = null! } : contributor)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1737,7 +1737,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Name = null! } } : contributor).ToList() }; + bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Name = null! } } : contributor)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1751,7 +1751,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Name = new Faker().Random.String2(51) } } : contributor).ToList() }; + bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Name = new Faker().Random.String2(51) } } : contributor)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1765,7 +1765,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Category = null! } } : contributor).ToList() }; + bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Category = null! } } : contributor)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1779,7 +1779,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Category = new Faker().Random.String2(51) } } : contributor).ToList() }; + bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Category = new Faker().Random.String2(51) } } : contributor)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1807,7 +1807,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = -1 } : rating).ToList() }; + bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = -1 } : rating)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1821,7 +1821,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = 6, MaxValue = 5 } : rating).ToList() }; + bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = 6, MaxValue = 5 } : rating)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1835,7 +1835,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { MaxValue = -1 } : rating).ToList() }; + bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { MaxValue = -1 } : rating)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1849,7 +1849,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = -1 } : rating).ToList() }; + bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = -1 } : rating)] }; // Act List result = _validator.TestValidate(bookCommand); @@ -1865,9 +1865,9 @@ public class AddBookCommandValidatorTests AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { - Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating + Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with - { Value = 4, MaxValue = 5, VoteCount = 100 } : rating).ToList() + { Value = 4, MaxValue = 5, VoteCount = 100 } : rating)] }; // Act @@ -1882,7 +1882,7 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = null } : rating).ToList() }; + bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = null } : rating)] }; // Act List result = _validator.TestValidate(bookCommand); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookFixture.cs index 8bf03b72..3886a9df 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookFixture.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; @@ -9,6 +9,7 @@ using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.Boo using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -24,6 +25,8 @@ namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.B public class BookFixture { private readonly Fixture _fixture; + private readonly IsbnFixture _isbnFixture; + private readonly BookRatingFixture _bookRatingFixture; /// /// Initializes a new instance of the class. @@ -33,6 +36,8 @@ public class BookFixture _fixture = new Fixture(); _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); + _isbnFixture = new IsbnFixture(); + _bookRatingFixture = new BookRatingFixture(); ConfigureCustomDomainTypes(); } @@ -106,16 +111,8 @@ public class BookFixture _fixture.Create>() ).Value); - _fixture.Register(() => Isbn.Create( - _fixture.Create(), - _fixture.Create() - ).Value); + _fixture.Register(() => _isbnFixture.CreateIsbn13()); - _fixture.Register(() => BookRating.Create( - _fixture.Create(), - _fixture.Create(), - _fixture.Create>(), - _fixture.Create>() - ).Value); + _fixture.Register(() => _bookRatingFixture.CreateBookRating()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs index 90558a6b..a1b432dc 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; using Lumina.DataAccess.UnitTests.Core.Repositories.Plugins.Fixtures; +using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Collections.Generic; @@ -52,10 +52,10 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests .Returns(Result.Updated); // Act - ErrorOr result = await _sut.HandleAsync(new ReorderLibraryMetadataProvidersCommand(libraryId, [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None); + Result result = await _sut.HandleAsync(new ReorderLibraryMetadataProvidersCommand(libraryId, [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); await _mockConfigurationRepository.Received(1).UpsertAsync( Arg.Is(configuration => configuration.PluginId == secondProvider.PluginId && configuration.Rank == 1), Arg.Any()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs index 3fcc7f80..1c449a57 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; +using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Collections.Generic; @@ -51,10 +51,10 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests .Returns(Result.Updated); // Act - ErrorOr result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(libraryId, pluginId, true), CancellationToken.None); + Result result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(libraryId, pluginId, true), CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); await _mockConfigurationRepository.Received(1).UpsertAsync( Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 1), Arg.Any()); @@ -81,10 +81,10 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests .Returns(Result.Updated); // Act - ErrorOr result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(existingConfiguration.LibraryId, existingConfiguration.PluginId, true), CancellationToken.None); + Result result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(existingConfiguration.LibraryId, existingConfiguration.PluginId, true), CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); await _mockConfigurationRepository.Received(1).UpsertAsync( Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 2), Arg.Any()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs index 1d83a6f3..32727552 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; +using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Collections.Generic; @@ -46,10 +46,10 @@ public class UpdatePluginSettingsCommandHandlerTests .Returns(Result.Updated); // Act - ErrorOr result = await _sut.HandleAsync(new UpdatePluginSettingsCommand(pluginId, settings), CancellationToken.None); + Result result = await _sut.HandleAsync(new UpdatePluginSettingsCommand(pluginId, settings), CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); await _mockPluginRepository.Received(1).UpdateSettingsAsync(pluginId, Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs index ea3c0498..f54e2a98 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Core.Plugins.Queries.GetPlugins; using Lumina.Contracts.Responses.Plugins; using Lumina.DataAccess.UnitTests.Core.Repositories.Plugins.Fixtures; +using Lumina.Domain.Common.Primitives; using NSubstitute; -using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -44,10 +43,10 @@ public class GetPluginsQueryHandlerTests _mockPluginRepository.GetAllAsync(Arg.Any()).Returns(plugins); // Act - ErrorOr> result = await _sut.HandleAsync(new GetPluginsQuery(), CancellationToken.None); + Result> result = await _sut.HandleAsync(new GetPluginsQuery(), CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count); Assert.Equal(plugins[0].Name, result.Value[0].Name); Assert.Equal(plugins[0].Id, result.Value[0].Id); @@ -61,9 +60,9 @@ public class GetPluginsQueryHandlerTests .Returns(Error.Failure(description: "Failed to get plugins")); // Act - ErrorOr> result = await _sut.HandleAsync(new GetPluginsQuery(), CancellationToken.None); + Result> result = await _sut.HandleAsync(new GetPluginsQuery(), CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs index 50e07f8d..59a92aac 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; @@ -9,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -68,7 +68,7 @@ public class ChangePasswordCommandHandlerTests newPassword); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); _mockHashService.CheckStringAgainstHash(currentPassword, "hashedCurrentPassword") .Returns(true); _mockHashService.HashString(newPassword) @@ -77,10 +77,10 @@ public class ChangePasswordCommandHandlerTests .Returns(Result.Updated); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.True(result.Value.IsPasswordChanged); await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); @@ -97,13 +97,13 @@ public class ChangePasswordCommandHandlerTests ChangePasswordCommand command = new("nonexistentUser", "oldPass", "newPass", "newPass"); _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) - .Returns(ErrorOrFactory.From(null)); + .Returns(Result.From(null)); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.UsernameDoesNotExist, result.FirstError); await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); @@ -125,15 +125,15 @@ public class ChangePasswordCommandHandlerTests "newPass"); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); _mockHashService.CheckStringAgainstHash(incorrectPassword, Uri.UnescapeDataString(user.Password)) .Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.InvalidCurrentPassword, result.FirstError); await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); @@ -161,17 +161,17 @@ public class ChangePasswordCommandHandlerTests newPassword); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); _mockHashService.CheckStringAgainstHash(currentPassword, "hashedCurrentPassword") .Returns(true); _mockUserRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); @@ -198,10 +198,10 @@ public class ChangePasswordCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs index 2bab25b2..091fd87e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs index 8e24234c..327a1cad 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; @@ -10,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -72,7 +72,7 @@ public class RecoverPasswordCommandHandlerTests RecoverPasswordCommand command = new(user.Username, totpCode); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); _mockCryptographyService.Decrypt(encryptedTotpSecret) .Returns(decryptedTotpSecret); _mockTotpTokenGenerator.ValidateToken(Arg.Any(), totpCode) @@ -83,10 +83,10 @@ public class RecoverPasswordCommandHandlerTests .Returns(Result.Updated); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.True(result.Value.IsPasswordReset); await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); @@ -103,13 +103,13 @@ public class RecoverPasswordCommandHandlerTests RecoverPasswordCommand command = new("nonexistentUser", "123456"); _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) - .Returns(ErrorOrFactory.From(null)); + .Returns(Result.From(null)); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.UsernameDoesNotExist, result.FirstError); await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); @@ -128,13 +128,13 @@ public class RecoverPasswordCommandHandlerTests RecoverPasswordCommand command = new(user.Username, "123456"); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.PasswordResetAlreadyRequested, result.FirstError); await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); @@ -152,13 +152,13 @@ public class RecoverPasswordCommandHandlerTests RecoverPasswordCommand command = new(user.Username, "123456"); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.InvalidTotpCode, result.FirstError); await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); @@ -180,17 +180,17 @@ public class RecoverPasswordCommandHandlerTests RecoverPasswordCommand command = new(user.Username, totpCode); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); _mockCryptographyService.Decrypt(encryptedTotpSecret) .Returns(decryptedTotpSecret); _mockTotpTokenGenerator.ValidateToken(Arg.Any(), totpCode) .Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.InvalidTotpCode, result.FirstError); await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); @@ -214,7 +214,7 @@ public class RecoverPasswordCommandHandlerTests RecoverPasswordCommand command = new(user.Username, totpCode); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); _mockCryptographyService.Decrypt(encryptedTotpSecret) .Returns(decryptedTotpSecret); _mockTotpTokenGenerator.ValidateToken(Arg.Any(), totpCode) @@ -223,10 +223,10 @@ public class RecoverPasswordCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); @@ -252,10 +252,10 @@ public class RecoverPasswordCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); @@ -275,13 +275,13 @@ public class RecoverPasswordCommandHandlerTests RecoverPasswordCommand command = new(user.Username, null); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.InvalidTotpCode, result.FirstError); await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs index 500be490..28aaaa3a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs index 01d1f8f6..4df769f2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; @@ -12,6 +11,7 @@ using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUs using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -76,7 +76,7 @@ public class RegisterUserCommandHandlerTests string hashedPassword = "hashedPassword"; _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) - .Returns(ErrorOrFactory.From(null)); + .Returns(Result.From(null)); _mockHashService.HashString(command.Password!) .Returns(hashedPassword); _mockTotpTokenGenerator.GenerateSecret() @@ -89,10 +89,10 @@ public class RegisterUserCommandHandlerTests .Returns(Result.Created); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(command.Username, result.Value.Username); Assert.Equal(qrCodeUri, result.Value.TotpSecret); @@ -113,17 +113,17 @@ public class RegisterUserCommandHandlerTests string hashedPassword = "hashedPassword"; _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) - .Returns(ErrorOrFactory.From(null)); + .Returns(Result.From(null)); _mockHashService.HashString(command.Password!) .Returns(hashedPassword); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(command.Username, result.Value.Username); Assert.Null(result.Value.TotpSecret); @@ -144,13 +144,13 @@ public class RegisterUserCommandHandlerTests UserEntity existingUser = UserEntityFixture.CreateUserEntity(); _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) - .Returns(ErrorOrFactory.From(existingUser)); + .Returns(Result.From(existingUser)); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.UsernameAlreadyExists, result.FirstError); await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); @@ -166,15 +166,15 @@ public class RegisterUserCommandHandlerTests Error error = Error.Failure("Database.Error", "Failed to insert user"); _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) - .Returns(ErrorOrFactory.From(null)); + .Returns(Result.From(null)); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); @@ -193,10 +193,10 @@ public class RegisterUserCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs index b517a24e..e289cfe5 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs index ca6631be..e0a7aa41 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; @@ -10,6 +9,7 @@ using Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUsers; using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.GetUsers.Fixtures; using Lumina.Contracts.Responses.UsersManagement.Users; +using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Collections.Generic; @@ -65,10 +65,10 @@ public class GetUsersQueryHandlerTests .Returns(false); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockUserRepository.DidNotReceive().GetAllAsync(Arg.Any()); } @@ -86,10 +86,10 @@ public class GetUsersQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); } @@ -104,13 +104,13 @@ public class GetUsersQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(ErrorOrFactory.From(users)); + .Returns(Result.From(users)); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs index 6d7ab1b0..4a041d28 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; @@ -11,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -79,17 +79,17 @@ public class LoginUserQueryHandlerTests LoginUserQuery query = new(user.Username, password); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); _mockHashService.CheckStringAgainstHash(password, hashedPassword) .Returns(true); _mockJwtTokenGenerator.GenerateToken(user.Id.ToString(), user.Username) .Returns(jwtToken); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(user.Id, result.Value.Id); Assert.Equal(user.Username, result.Value.Username); Assert.Equal(jwtToken, result.Value.Token); @@ -114,7 +114,7 @@ public class LoginUserQueryHandlerTests LoginUserQuery query = new(user.Username, password, totpCode); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); _mockHashService.CheckStringAgainstHash(password, hashedPassword) .Returns(true); _mockJwtTokenGenerator.GenerateToken(user.Id.ToString(), user.Username) @@ -125,10 +125,10 @@ public class LoginUserQueryHandlerTests .Returns(true); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(user.Id, result.Value.Id); Assert.Equal(user.Username, result.Value.Username); Assert.Equal(jwtToken, result.Value.Token); @@ -142,13 +142,13 @@ public class LoginUserQueryHandlerTests LoginUserQuery query = new("nonexistentUser", "password"); _mockUserRepository.GetByUsernameAsync(query.Username!, Arg.Any()) - .Returns(ErrorOrFactory.From(null)); + .Returns(Result.From(null)); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.InvalidUsernameOrPassword, result.FirstError); } @@ -166,15 +166,15 @@ public class LoginUserQueryHandlerTests LoginUserQuery query = new(user.Username, password); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); _mockHashService.CheckStringAgainstHash(password, hashedPassword) .Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.InvalidUsernameOrPassword, result.FirstError); } @@ -194,17 +194,17 @@ public class LoginUserQueryHandlerTests LoginUserQuery query = new(user.Username, password); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); _mockHashService.CheckStringAgainstHash(password, hashedPassword) .Returns(false); _mockHashService.CheckStringAgainstHash(password, hashedTempPassword) .Returns(true); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.TempPasswordExpired, result.FirstError); await _mockUserRepository.Received(1).UpdateAsync(Arg.Is(u => @@ -232,7 +232,7 @@ public class LoginUserQueryHandlerTests LoginUserQuery query = new(user.Username, password); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); _mockHashService.CheckStringAgainstHash(password, hashedPassword) .Returns(false); // Regular password check fails _mockHashService.CheckStringAgainstHash(password, hashedTempPassword) @@ -241,10 +241,10 @@ public class LoginUserQueryHandlerTests .Returns(jwtToken); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(user.Id, result.Value.Id); Assert.Equal(user.Username, result.Value.Username); Assert.Equal(jwtToken, result.Value.Token); @@ -266,15 +266,15 @@ public class LoginUserQueryHandlerTests LoginUserQuery query = new(user.Username, password); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); _mockHashService.CheckStringAgainstHash(password, hashedPassword) .Returns(true); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.InvalidTotpCode, result.FirstError); } @@ -295,7 +295,7 @@ public class LoginUserQueryHandlerTests LoginUserQuery query = new(user.Username, password, totpCode); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); _mockHashService.CheckStringAgainstHash(password, hashedPassword) .Returns(true); _mockCryptographyService.Decrypt(encryptedTotpSecret) @@ -304,10 +304,10 @@ public class LoginUserQueryHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.InvalidTotpCode, result.FirstError); } @@ -322,10 +322,10 @@ public class LoginUserQueryHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); } @@ -345,17 +345,17 @@ public class LoginUserQueryHandlerTests LoginUserQuery query = new(user.Username, password); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); _mockHashService.CheckStringAgainstHash(password, hashedPassword) .Returns(false); // Regular password check fails _mockHashService.CheckStringAgainstHash(password, hashedTempPassword) .Returns(false); // Temp password check also fails // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.InvalidUsernameOrPassword, result.FirstError); _mockHashService.Received(1).CheckStringAgainstHash(password, hashedPassword); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs index 6926bf1a..b1273e49 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.Errors; using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures; +using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs index 61d12cc2..7fda416b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Authorization; @@ -12,6 +11,7 @@ using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserR using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions.Fixtures; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using NSubstitute; using System; @@ -21,7 +21,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; @@ -80,10 +80,10 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); } @@ -99,10 +99,10 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests .Returns((UserEntity?)null); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Users.UserDoesNotExist, result.FirstError); } @@ -121,10 +121,10 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests .Returns((RoleEntity?)null); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.RoleNotFound, result.FirstError); } @@ -164,13 +164,13 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) .Returns(newRole); _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(ErrorOrFactory.From(users)); + .Returns(Result.From(users)); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.CannotRemoveLastAdmin, result.FirstError); } @@ -192,15 +192,15 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) .Returns(role); _mockPermissionRepository.GetByIdsAsync(command.Permissions, Arg.Any()) - .Returns(ErrorOrFactory.From(permissions)); + .Returns(Result.From(permissions)); _mockUserRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -216,7 +216,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests Username = "testUser", Password = "hashedPassword", Libraries = [], - UserPermissions = command.Permissions.Select((p, i) => new UserPermissionEntity + UserPermissions = [.. command.Permissions.Select((p, i) => new UserPermissionEntity { UserId = command.UserId, PermissionId = p, @@ -226,7 +226,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests Id = p, PermissionName = (AuthorizationPermission)(i + 1) } - }).ToList(), + })], UserRole = null, CreatedOnUtc = DateTime.UtcNow, CreatedBy = command.UserId @@ -242,15 +242,15 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) .Returns(role); _mockPermissionRepository.GetByIdsAsync(command.Permissions, Arg.Any()) - .Returns(ErrorOrFactory.From(permissions)); + .Returns(Result.From(permissions)); _mockUserRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(command.UserId, result.Value.UserId); Assert.Equal(role.RoleName, result.Value.Role); Assert.Equal(command.Permissions.Count, result.Value.Permissions.Count); @@ -291,10 +291,10 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); } @@ -326,10 +326,10 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs index c40b203a..90f2cfb4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs index cf54a454..757a8c49 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; @@ -8,6 +7,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization.Fixtures; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -50,13 +50,13 @@ public class GetAuthorizationQueryHandlerTests _mockCurrentUserService.UserId.Returns(userId); _mockAuthorizationService.GetUserAuthorizationAsync(userId, Arg.Any()) - .Returns(ErrorOrFactory.From(authEntity)); + .Returns(Result.From(authEntity)); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(userId, result.Value.UserId); Assert.Equal(authEntity.Role, result.Value.Role); Assert.Equal(authEntity.Permissions, result.Value.Permissions); @@ -74,15 +74,15 @@ public class GetAuthorizationQueryHandlerTests _mockCurrentUserService.UserId.Returns(adminUserId); _mockAuthorizationService.GetUserAuthorizationAsync(adminUserId, Arg.Any()) - .Returns(ErrorOrFactory.From(adminAuthEntity)); + .Returns(Result.From(adminAuthEntity)); _mockAuthorizationService.GetUserAuthorizationAsync(targetUserId, Arg.Any()) - .Returns(ErrorOrFactory.From(targetAuthEntity)); + .Returns(Result.From(targetAuthEntity)); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(targetUserId, result.Value.UserId); Assert.Equal(targetAuthEntity.Role, result.Value.Role); Assert.Equal(targetAuthEntity.Permissions, result.Value.Permissions); @@ -99,13 +99,13 @@ public class GetAuthorizationQueryHandlerTests _mockCurrentUserService.UserId.Returns(currentUserId); _mockAuthorizationService.GetUserAuthorizationAsync(currentUserId, Arg.Any()) - .Returns(ErrorOrFactory.From(currentUserAuth)); + .Returns(Result.From(currentUserAuth)); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); } @@ -123,10 +123,10 @@ public class GetAuthorizationQueryHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); } @@ -142,15 +142,15 @@ public class GetAuthorizationQueryHandlerTests _mockCurrentUserService.UserId.Returns(adminUserId); _mockAuthorizationService.GetUserAuthorizationAsync(adminUserId, Arg.Any()) - .Returns(ErrorOrFactory.From(adminAuthEntity)); + .Returns(Result.From(adminAuthEntity)); _mockAuthorizationService.GetUserAuthorizationAsync(targetUserId, Arg.Any()) .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidatorTests.cs index 55f319d7..77e0cee1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidatorTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization.Fixtures; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs index 4225df62..462d0491 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; @@ -10,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetUserPermissions.Fixtures; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using NSubstitute; using System; @@ -70,10 +70,10 @@ public class GetUserPermissionsQueryHandlerTests .Returns(false); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); } @@ -91,10 +91,10 @@ public class GetUserPermissionsQueryHandlerTests .Returns(error); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); } @@ -110,10 +110,10 @@ public class GetUserPermissionsQueryHandlerTests .Returns((UserEntity?)null); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.UsernameDoesNotExist, result.FirstError); } @@ -149,10 +149,10 @@ public class GetUserPermissionsQueryHandlerTests .Returns(user); // Act - ErrorOr> result = await _sut.HandleAsync(query, CancellationToken.None); + Result> result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(result.Value); Assert.Equal(AuthorizationPermission.CanViewUsers, result.Value.First().PermissionName); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs index 48b5045f..74faf8e4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs index ea7d537c..39f3f7ee 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; @@ -11,6 +10,7 @@ using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetUserRole.Fixtures; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -68,10 +68,10 @@ public class GetUserRoleQueryHandlerTests .Returns(false); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); } @@ -89,10 +89,10 @@ public class GetUserRoleQueryHandlerTests .Returns(error); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); } @@ -108,10 +108,10 @@ public class GetUserRoleQueryHandlerTests .Returns((UserEntity?)null); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authentication.UsernameDoesNotExist, result.FirstError); } @@ -128,10 +128,10 @@ public class GetUserRoleQueryHandlerTests .Returns(user); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Null(result.Value); } @@ -164,10 +164,10 @@ public class GetUserRoleQueryHandlerTests .Returns(user); // Act - ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None); + Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Contains("TestRole", result.Value!.RoleName); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs index 808e6c7e..ecad2004 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/PermissionRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/PermissionRepositoryTests.cs index 76265db5..3046e72b 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/PermissionRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/PermissionRepositoryTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.Errors; using Lumina.DataAccess.Core.Repositories.Authorization; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; +using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using System; @@ -45,10 +45,10 @@ public class PermissionRepositoryTests PermissionEntity permissionModel = _permissionEntityFixture.CreatePermissionModel(); // Act - ErrorOr result = await _sut.InsertAsync(permissionModel, CancellationToken.None); + Result result = await _sut.InsertAsync(permissionModel, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Created, result.Value); // check if the permission was added to the context's ChangeTracker @@ -67,10 +67,10 @@ public class PermissionRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr result = await _sut.InsertAsync(permissionModel, CancellationToken.None); + Result result = await _sut.InsertAsync(permissionModel, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.PermissionAlreadyExists, result.FirstError); Assert.Single(_mockContext.ChangeTracker.Entries()); } @@ -89,10 +89,10 @@ public class PermissionRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(3, result.Value.Count()); Assert.Equal(permissions, result.Value); @@ -102,10 +102,10 @@ public class PermissionRepositoryTests public async Task GetAllAsync_WhenNoPermissionsExist_ShouldReturnEmptyList() { // Act - ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Empty(result.Value); } @@ -123,16 +123,16 @@ public class PermissionRepositoryTests _mockContext.Permissions.AddRange(permissions); await _mockContext.SaveChangesAsync(); - List requestedIds = permissions.Take(2).Select(p => p.Id).ToList(); + List requestedIds = [.. permissions.Take(2).Select(p => p.Id)]; // Act - ErrorOr> result = await _sut.GetByIdsAsync(requestedIds, CancellationToken.None); + Result> result = await _sut.GetByIdsAsync(requestedIds, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(2, result.Value.Count()); - Assert.Equal(requestedIds, result.Value.Select(p => p.Id).ToList()); + Assert.Equal(requestedIds, [.. result.Value.Select(p => p.Id)]); } [Fact] @@ -142,10 +142,10 @@ public class PermissionRepositoryTests List requestedIds = [Guid.NewGuid(), Guid.NewGuid()]; // Act - ErrorOr> result = await _sut.GetByIdsAsync(requestedIds, CancellationToken.None); + Result> result = await _sut.GetByIdsAsync(requestedIds, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Empty(result.Value); } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RolePermissionRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RolePermissionRepositoryTests.cs index 1b2db50e..8051d0c4 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RolePermissionRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RolePermissionRepositoryTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.DataAccess.Core.Repositories.Authorization; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; +using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using System.Diagnostics.CodeAnalysis; @@ -42,10 +42,10 @@ public class RolePermissionRepositoryTests RolePermissionEntity rolePermissionModel = _rolePermissionEntityFixture.CreateRolePermissionModel(); // Act - ErrorOr result = await _sut.InsertAsync(rolePermissionModel, CancellationToken.None); + Result result = await _sut.InsertAsync(rolePermissionModel, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Created, result.Value); // check if the role permission was added to the context's ChangeTracker diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs index 0c8c3ba4..a2c55da3 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs @@ -1,12 +1,11 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.Errors; using Lumina.DataAccess.Core.Repositories.Authorization; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; -using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using System; @@ -50,10 +49,10 @@ public class RoleRepositoryTests }; // Act - ErrorOr result = await _sut.InsertAsync(role, CancellationToken.None); + Result result = await _sut.InsertAsync(role, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Created, result.Value); // Check if the role was added to the context's ChangeTracker @@ -86,10 +85,10 @@ public class RoleRepositoryTests }; // Act - ErrorOr result = await _sut.InsertAsync(newRole, CancellationToken.None); + Result result = await _sut.InsertAsync(newRole, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.RoleAlreadyExists, result.FirstError); Assert.Single(_mockContext.ChangeTracker.Entries()); } @@ -118,10 +117,10 @@ public class RoleRepositoryTests }; // Act - ErrorOr result = await _sut.InsertAsync(newRole, CancellationToken.None); + Result result = await _sut.InsertAsync(newRole, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.RoleAlreadyExists, result.FirstError); Assert.Single(_mockContext.ChangeTracker.Entries()); } @@ -152,10 +151,10 @@ public class RoleRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(2, result.Value.Count()); Assert.Equal(roles, result.Value); @@ -165,10 +164,10 @@ public class RoleRepositoryTests public async Task GetAllAsync_WhenNoRolesExist_ShouldReturnEmptyList() { // Act - ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Empty(result.Value); } @@ -189,10 +188,10 @@ public class RoleRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr result = await _sut.GetByNameAsync("Admin", CancellationToken.None); + Result result = await _sut.GetByNameAsync("Admin", CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(role, result.Value); } @@ -201,10 +200,10 @@ public class RoleRepositoryTests public async Task GetByNameAsync_WhenRoleDoesNotExist_ShouldReturnNull() { // Act - ErrorOr result = await _sut.GetByNameAsync("NonExistentRole", CancellationToken.None); + Result result = await _sut.GetByNameAsync("NonExistentRole", CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Null(result.Value); } @@ -220,10 +219,10 @@ public class RoleRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr result = await _sut.GetByIdAsync(role.Id, CancellationToken.None); + Result result = await _sut.GetByIdAsync(role.Id, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(role.Id, result.Value.Id); Assert.Equal(role.RoleName, result.Value.RoleName); @@ -238,10 +237,10 @@ public class RoleRepositoryTests Guid nonExistentId = Guid.NewGuid(); // Act - ErrorOr result = await _sut.GetByIdAsync(nonExistentId, CancellationToken.None); + Result result = await _sut.GetByIdAsync(nonExistentId, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Null(result.Value); } @@ -271,10 +270,10 @@ public class RoleRepositoryTests }; // Act - ErrorOr result = await _sut.UpdateAsync(updatedRole, CancellationToken.None); + Result result = await _sut.UpdateAsync(updatedRole, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Updated, result.Value); EntityEntry? updatedEntry = _mockContext.ChangeTracker.Entries() @@ -296,10 +295,10 @@ public class RoleRepositoryTests }; // Act - ErrorOr result = await _sut.UpdateAsync(nonExistentRole, CancellationToken.None); + Result result = await _sut.UpdateAsync(nonExistentRole, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.RoleNotFound, result.FirstError); } @@ -328,10 +327,10 @@ public class RoleRepositoryTests }; // Act - ErrorOr result = await _sut.UpdateAsync(updatedRole, CancellationToken.None); + Result result = await _sut.UpdateAsync(updatedRole, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Updated, result.Value); EntityEntry? updatedEntry = _mockContext.ChangeTracker.Entries() @@ -357,10 +356,10 @@ public class RoleRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr result = await _sut.DeleteByIdAsync(existingRole.Id, CancellationToken.None); + Result result = await _sut.DeleteByIdAsync(existingRole.Id, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); EntityEntry? deletedEntry = _mockContext.ChangeTracker.Entries() @@ -376,10 +375,10 @@ public class RoleRepositoryTests Guid nonExistentId = Guid.NewGuid(); // Act - ErrorOr result = await _sut.DeleteByIdAsync(nonExistentId, CancellationToken.None); + Result result = await _sut.DeleteByIdAsync(nonExistentId, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.RoleNotFound, result.FirstError); } @@ -396,10 +395,10 @@ public class RoleRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr result = await _sut.DeleteByIdAsync(existingRole.Id, CancellationToken.None); + Result result = await _sut.DeleteByIdAsync(existingRole.Id, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); EntityEntry? deletedEntry = _mockContext.ChangeTracker.Entries() diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/UserRoleRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/UserRoleRepositoryTests.cs index 04c557eb..825634f9 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/UserRoleRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/UserRoleRepositoryTests.cs @@ -1,16 +1,12 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; -using Lumina.Application.Common.Errors; using Lumina.DataAccess.Core.Repositories.Authorization; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; -using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; @@ -46,10 +42,10 @@ public class UserRoleRepositoryTests UserRoleEntity userRole = _userRoleEntityFixture.CreateUserRoleModel(); // Act - ErrorOr result = await _sut.InsertAsync(userRole, CancellationToken.None); + Result result = await _sut.InsertAsync(userRole, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Created, result.Value); EntityEntry? addedUserRole = _mockContext.ChangeTracker.Entries() diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs index d3ce9192..d38f4cdc 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.DataAccess.Core.Repositories.Books; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using System; @@ -47,10 +47,10 @@ public class BookRepositoryTests BookEntity bookModel = _bookEntityFixture.CreateBookModel(); // Act - ErrorOr result = await _sut.InsertAsync(bookModel, CancellationToken.None); + Result result = await _sut.InsertAsync(bookModel, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Created, result.Value); // check if the book was added to the context's ChangeTracker @@ -69,10 +69,10 @@ public class BookRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr result = await _sut.InsertAsync(bookModel, CancellationToken.None); + Result result = await _sut.InsertAsync(bookModel, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError); Assert.Single(_mockContext.ChangeTracker.Entries()); // only the existing book should be in the context } @@ -89,10 +89,10 @@ public class BookRepositoryTests bookModel.Tags = [new("Existing"), new("New")]; // Act - ErrorOr result = await _sut.InsertAsync(bookModel, CancellationToken.None); + Result result = await _sut.InsertAsync(bookModel, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Created, result.Value); EntityEntry? addedBook = _mockContext.ChangeTracker.Entries() @@ -116,10 +116,10 @@ public class BookRepositoryTests bookModel.Genres = [new("Existing"), new("New")]; // Act - ErrorOr result = await _sut.InsertAsync(bookModel, CancellationToken.None); + Result result = await _sut.InsertAsync(bookModel, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Created, result.Value); EntityEntry? addedBook = _mockContext.ChangeTracker.Entries() @@ -145,10 +145,10 @@ public class BookRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(3, result.Value.Count()); Assert.Equal(books, result.Value); @@ -158,10 +158,10 @@ public class BookRepositoryTests public async Task GetAllAsync_WhenNoBooksExist_ShouldReturnEmptyList() { // Act - ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Empty(result.Value); } @@ -178,10 +178,10 @@ public class BookRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Single(result.Value); BookEntity retrievedBook = result.Value.First(); @@ -203,10 +203,10 @@ public class BookRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None); + Result> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); BookEntity retrievedBook = Assert.Single(result.Value); Assert.Equal(bookOfLibrary.Id, retrievedBook.Id); } @@ -220,10 +220,10 @@ public class BookRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr result = await _sut.GetByPathAsync(book.LibraryId, book.Path, CancellationToken.None); + Result result = await _sut.GetByPathAsync(book.LibraryId, book.Path, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(book.Id, result.Value!.Id); } @@ -236,10 +236,10 @@ public class BookRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr result = await _sut.GetByPathAsync(book.LibraryId, "/books/non-existent.epub", CancellationToken.None); + Result result = await _sut.GetByPathAsync(book.LibraryId, "/books/non-existent.epub", CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Null(result.Value); } @@ -267,10 +267,10 @@ public class BookRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr> result = await _sut.GetBooksNeedingMetadataAsync(libraryId, null, 10, CancellationToken.None); + Result> result = await _sut.GetBooksNeedingMetadataAsync(libraryId, null, 10, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count); Assert.Contains(result.Value, book => book.Id == pendingBook.Id); Assert.Contains(result.Value, book => book.Id == failedBook.Id); @@ -291,10 +291,10 @@ public class BookRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr> result = await _sut.GetBooksNeedingMetadataAsync(libraryId, firstBook.Path, 10, CancellationToken.None); + Result> result = await _sut.GetBooksNeedingMetadataAsync(libraryId, firstBook.Path, 10, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); BookEntity retrievedBook = Assert.Single(result.Value); Assert.Equal(secondBook.Id, retrievedBook.Id); } @@ -310,10 +310,10 @@ public class BookRepositoryTests book.Title = "Updated Title"; // Act - ErrorOr result = await _sut.UpdateAsync(book, CancellationToken.None); + Result result = await _sut.UpdateAsync(book, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Updated, result.Value); BookEntity? retrievedBook = await _mockContext.Books.FindAsync(book.Id); Assert.Equal("Updated Title", retrievedBook!.Title); @@ -326,10 +326,10 @@ public class BookRepositoryTests BookEntity book = _bookEntityFixture.CreateBookModel(); // Act - ErrorOr result = await _sut.UpdateAsync(book, CancellationToken.None); + Result result = await _sut.UpdateAsync(book, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs index 672a5247..5acb3fee 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs @@ -1,11 +1,10 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.DataAccess.Core.Repositories.Plugins; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Core.Repositories.Plugins.Fixtures; -using Microsoft.EntityFrameworkCore; +using Lumina.Domain.Common.Primitives; using System; using System.Linq; using System.Threading; @@ -44,10 +43,10 @@ public class LibraryMetadataProviderConfigurationRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None); + Result> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); LibraryMetadataProviderConfigurationEntity retrievedConfiguration = Assert.Single(result.Value); Assert.Equal(configurationOfLibrary.PluginId, retrievedConfiguration.PluginId); } @@ -61,10 +60,10 @@ public class LibraryMetadataProviderConfigurationRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr result = await _sut.GetByLibraryAndPluginIdAsync(configuration.LibraryId, configuration.PluginId, CancellationToken.None); + Result result = await _sut.GetByLibraryAndPluginIdAsync(configuration.LibraryId, configuration.PluginId, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(configuration.Id, result.Value!.Id); } @@ -75,11 +74,11 @@ public class LibraryMetadataProviderConfigurationRepositoryTests LibraryMetadataProviderConfigurationEntity configuration = _configurationFixture.CreateConfiguration(Guid.NewGuid(), Guid.NewGuid(), 1); // Act - ErrorOr result = await _sut.UpsertAsync(configuration, CancellationToken.None); + Result result = await _sut.UpsertAsync(configuration, CancellationToken.None); await _mockContext.SaveChangesAsync(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(_mockContext.LibraryMetadataProviderConfigurations); } @@ -95,11 +94,11 @@ public class LibraryMetadataProviderConfigurationRepositoryTests updatedConfiguration.IsEnabled = true; // Act - ErrorOr result = await _sut.UpsertAsync(updatedConfiguration, CancellationToken.None); + Result result = await _sut.UpsertAsync(updatedConfiguration, CancellationToken.None); await _mockContext.SaveChangesAsync(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); LibraryMetadataProviderConfigurationEntity retrievedConfiguration = _mockContext.LibraryMetadataProviderConfigurations.Single(); Assert.Equal(5, retrievedConfiguration.Rank); Assert.True(retrievedConfiguration.IsEnabled); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs index 79f3a98f..4f110480 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs @@ -1,12 +1,11 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.DataAccess.Core.Repositories.Plugins; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Core.Repositories.Plugins.Fixtures; -using Lumina.Domain.SharedKernel.Common.Errors; -using Microsoft.EntityFrameworkCore; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using System; using System.Linq; using System.Threading; @@ -43,10 +42,10 @@ public class PluginRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr result = await _sut.GetByIdAsync(plugin.Id, CancellationToken.None); + Result result = await _sut.GetByIdAsync(plugin.Id, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(plugin.Id, result.Value!.Id); } @@ -57,11 +56,11 @@ public class PluginRepositoryTests PluginEntity plugin = _pluginFixture.CreatePluginEntity(); // Act - ErrorOr result = await _sut.UpsertAsync(plugin, CancellationToken.None); + Result result = await _sut.UpsertAsync(plugin, CancellationToken.None); await _mockContext.SaveChangesAsync(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(_mockContext.Plugins); } @@ -79,11 +78,11 @@ public class PluginRepositoryTests updatedPlugin.SettingsJson = null; // the stored settings must be preserved // Act - ErrorOr result = await _sut.UpsertAsync(updatedPlugin, CancellationToken.None); + Result result = await _sut.UpsertAsync(updatedPlugin, CancellationToken.None); await _mockContext.SaveChangesAsync(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); PluginEntity retrievedPlugin = _mockContext.Plugins.Single(); Assert.Equal("Updated Name", retrievedPlugin.Name); Assert.Equal("""{"preferredLanguage":"en"}""", retrievedPlugin.SettingsJson); @@ -98,11 +97,11 @@ public class PluginRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr result = await _sut.UpdateSettingsAsync(plugin.Id, """{"preferredLanguage":"fr"}""", CancellationToken.None); + Result result = await _sut.UpdateSettingsAsync(plugin.Id, """{"preferredLanguage":"fr"}""", CancellationToken.None); await _mockContext.SaveChangesAsync(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal("""{"preferredLanguage":"fr"}""", _mockContext.Plugins.Single().SettingsJson); } @@ -110,10 +109,10 @@ public class PluginRepositoryTests public async Task UpdateSettingsAsync_WhenPluginDoesNotExist_ShouldReturnError() { // Act - ErrorOr result = await _sut.UpdateSettingsAsync(Guid.NewGuid(), null, CancellationToken.None); + Result result = await _sut.UpdateSettingsAsync(Guid.NewGuid(), null, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Plugins.PluginNotFound, result.FirstError); } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs index ab955342..0553791d 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.DataAccess.Core.Repositories.Users; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; using Lumina.DataAccess.UnitTests.Core.Repositories.Users.Fixtures; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using System; @@ -49,10 +49,10 @@ public class UserRepositoryTests UserEntity userModel = _userEntityFixture.CreateUserModel(); // Act - ErrorOr result = await _sut.InsertAsync(userModel, CancellationToken.None); + Result result = await _sut.InsertAsync(userModel, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Created, result.Value); EntityEntry? addedUser = _mockContext.ChangeTracker.Entries() @@ -70,10 +70,10 @@ public class UserRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr result = await _sut.InsertAsync(userModel, CancellationToken.None); + Result result = await _sut.InsertAsync(userModel, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Users.UserAlreadyExists, result.FirstError); Assert.Single(_mockContext.ChangeTracker.Entries()); } @@ -92,10 +92,10 @@ public class UserRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(3, result.Value.Count()); Assert.Equal(users, result.Value); @@ -105,10 +105,10 @@ public class UserRepositoryTests public async Task GetAllAsync_WhenNoUsersExist_ShouldReturnEmptyList() { // Act - ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Empty(result.Value); } @@ -122,10 +122,10 @@ public class UserRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr result = await _sut.GetByUsernameAsync(userModel.Username, CancellationToken.None); + Result result = await _sut.GetByUsernameAsync(userModel.Username, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(userModel, result.Value); } @@ -134,10 +134,10 @@ public class UserRepositoryTests public async Task GetByUsernameAsync_WhenUserDoesNotExist_ShouldReturnNull() { // Act - ErrorOr result = await _sut.GetByUsernameAsync("nonexistent", CancellationToken.None); + Result result = await _sut.GetByUsernameAsync("nonexistent", CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Null(result.Value); } @@ -166,10 +166,10 @@ public class UserRepositoryTests }; // Act - ErrorOr result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); + Result result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Updated, result.Value); UserEntity? modifiedUser = await _mockContext.Users.FirstOrDefaultAsync(u => u.Username == existingUser.Username); @@ -186,10 +186,10 @@ public class UserRepositoryTests UserEntity userModel = _userEntityFixture.CreateUserModel(); // Act - ErrorOr result = await _sut.UpdateAsync(userModel, CancellationToken.None); + Result result = await _sut.UpdateAsync(userModel, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Users.UserDoesNotExist, result.FirstError); } @@ -202,10 +202,10 @@ public class UserRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr result = await _sut.GetByIdAsync(userModel.Id, CancellationToken.None); + Result result = await _sut.GetByIdAsync(userModel.Id, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(userModel.Id, result.Value.Id); Assert.Equal(userModel.Username, result.Value.Username); @@ -222,10 +222,10 @@ public class UserRepositoryTests Guid nonExistentId = Guid.NewGuid(); // Act - ErrorOr result = await _sut.GetByIdAsync(nonExistentId, CancellationToken.None); + Result result = await _sut.GetByIdAsync(nonExistentId, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Null(result.Value); } @@ -268,10 +268,10 @@ public class UserRepositoryTests }; // Act - ErrorOr result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); + Result result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Updated, result.Value); UserEntity? modifiedUser = await _mockContext.Users @@ -333,10 +333,10 @@ public class UserRepositoryTests }; // Act - ErrorOr result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); + Result result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Updated, result.Value); EntityEntry? removedPermission = _mockContext.ChangeTracker @@ -436,10 +436,10 @@ public class UserRepositoryTests }; // Act - ErrorOr result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); + Result result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Updated, result.Value); EntityEntry? removedRole = _mockContext.ChangeTracker @@ -496,10 +496,10 @@ public class UserRepositoryTests }; // Act - ErrorOr result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); + Result result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Updated, result.Value); EntityEntry? removedRole = _mockContext.ChangeTracker diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs index bea9312e..fffba1cb 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Authorization; @@ -9,6 +8,7 @@ using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Time; using Lumina.DataAccess.Core.Seed; using Lumina.DataAccess.UnitTests.Core.Repositories.Users.Fixtures; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using NSubstitute; using System; @@ -58,10 +58,10 @@ public class DataSeedServiceTests .Returns(Result.Created); // Act - ErrorOr result = await _sut.SetDefaultAuthorizationPermissionsAsync(adminId, CancellationToken.None); + Result result = await _sut.SetDefaultAuthorizationPermissionsAsync(adminId, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Created, result.Value); await _mockPermissionRepository @@ -86,10 +86,10 @@ public class DataSeedServiceTests .Returns(expectedError); // Act - ErrorOr result = await _sut.SetDefaultAuthorizationPermissionsAsync(adminId, CancellationToken.None); + Result result = await _sut.SetDefaultAuthorizationPermissionsAsync(adminId, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(expectedError, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); @@ -132,10 +132,10 @@ public class DataSeedServiceTests .Returns(Result.Created); // Act - ErrorOr result = await _sut.SetDefaultAuthorizationRolesAsync(userId, CancellationToken.None); + Result result = await _sut.SetDefaultAuthorizationRolesAsync(userId, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Created, result.Value); await mockRoleRepository @@ -164,10 +164,10 @@ public class DataSeedServiceTests .Returns(expectedError); // Act - ErrorOr result = await _sut.SetDefaultAuthorizationRolesAsync(userId, CancellationToken.None); + Result result = await _sut.SetDefaultAuthorizationRolesAsync(userId, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(expectedError, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); @@ -247,10 +247,10 @@ public class DataSeedServiceTests mockRolePermissionRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); // Act - ErrorOr result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); + Result result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Created, result.Value); await mockRolePermissionRepository @@ -278,10 +278,10 @@ public class DataSeedServiceTests .Returns((RoleEntity?)null); // Act - ErrorOr result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); + Result result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.AdminAccountNotFound, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -304,10 +304,10 @@ public class DataSeedServiceTests mockPermissionRepository.GetAllAsync(Arg.Any()).Returns(expectedError); // Act - ErrorOr result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); + Result result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(expectedError, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); @@ -335,10 +335,10 @@ public class DataSeedServiceTests mockRolePermissionRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(expectedError); // Act - ErrorOr result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); + Result result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(expectedError, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); @@ -359,10 +359,10 @@ public class DataSeedServiceTests .Returns(expectedError); // Act - ErrorOr result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); + Result result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(expectedError, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); @@ -392,10 +392,10 @@ public class DataSeedServiceTests mockUserRoleRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); // Act - ErrorOr result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); + Result result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Created, result.Value); await mockUserRoleRepository @@ -424,10 +424,10 @@ public class DataSeedServiceTests .Returns((RoleEntity?)null); // Act - ErrorOr result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); + Result result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.AdminRoleNotFound, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -449,10 +449,10 @@ public class DataSeedServiceTests mockUserRepository.GetByIdAsync(userId, Arg.Any()).Returns((UserEntity?)null); // Act - ErrorOr result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); + Result result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.AdminAccountNotFound, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); @@ -481,10 +481,10 @@ public class DataSeedServiceTests mockUserRoleRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(expectedError); // Act - ErrorOr result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); + Result result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(expectedError, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); @@ -505,10 +505,10 @@ public class DataSeedServiceTests .Returns(expectedError); // Act - ErrorOr result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); + Result result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(expectedError, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); @@ -532,10 +532,10 @@ public class DataSeedServiceTests mockUserRepository.GetByIdAsync(userId, Arg.Any()).Returns(expectedError); // Act - ErrorOr result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); + Result result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(expectedError, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/BookLibraryAggregate/Fixtures/BookFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/BookLibraryAggregate/Fixtures/BookFixture.cs index 99f91298..32d90ce8 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/BookLibraryAggregate/Fixtures/BookFixture.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/BookLibraryAggregate/Fixtures/BookFixture.cs @@ -1,14 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -26,7 +24,7 @@ public static class BookFixture /// The created domain entity. public static Book CreateValidBook() { - ErrorOr bookResult = Book.Create( + Result bookResult = Book.Create( LibraryId.Create(Guid.NewGuid()), "/books/test.epub", WrittenContentMetadata.Create( @@ -65,7 +63,7 @@ public static class BookFixture [], [] ); - if (bookResult.IsError) + if (bookResult.IsFailure) throw new InvalidOperationException("Failed to create a valid book in the test fixture."); return bookResult.Value; } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/DirectoryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/DirectoryTests.cs index bae6869f..5b01e5ca 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/DirectoryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/DirectoryTests.cs @@ -1,11 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Fixtures; using System; using System.Diagnostics.CodeAnalysis; @@ -29,10 +28,10 @@ public class DirectoryTests Optional dateModified = DateTime.Now; // Act - ErrorOr result = Directory.Create(path, name, dateCreated, dateModified); + Result result = Directory.Create(path, name, dateCreated, dateModified); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(name, result.Value.Name); Assert.Equal(dateCreated, result.Value.DateCreated); @@ -50,10 +49,10 @@ public class DirectoryTests Optional dateModified = DateTime.Now; // Act - ErrorOr result = Directory.Create(invalidPath, name, dateCreated, dateModified); + Result result = Directory.Create(invalidPath, name, dateCreated, dateModified); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -61,18 +60,18 @@ public class DirectoryTests public void Create_WhenCalledWithFileSystemPathId_ShouldReturnSuccessfulResult() { // Arrange - ErrorOr pathIdResult = FileSystemPathId.Create("/valid/path"); - Assert.False(pathIdResult.IsError); + Result pathIdResult = FileSystemPathId.Create("/valid/path"); + Assert.False(pathIdResult.IsFailure); FileSystemPathId pathId = pathIdResult.Value; string name = "TestDirectory"; Optional dateCreated = DateTime.Now; Optional dateModified = DateTime.Now; // Act - ErrorOr result = Directory.Create(pathId, name, dateCreated, dateModified); + Result result = Directory.Create(pathId, name, dateCreated, dateModified); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(pathId, result.Value.Id); Assert.Equal(name, result.Value.Name); @@ -85,16 +84,16 @@ public class DirectoryTests public void UpdateLastModified_WhenCalled_ShouldUpdateDateModified() { // Arrange - ErrorOr directoryResult = Directory.Create("/valid/path", "TestDirectory", Optional.None(), Optional.None()); - Assert.False(directoryResult.IsError); + Result directoryResult = Directory.Create("/valid/path", "TestDirectory", Optional.None(), Optional.None()); + Assert.False(directoryResult.IsFailure); Directory directory = directoryResult.Value; DateTime newDate = DateTime.Now; // Act - ErrorOr result = directory.UpdateLastModified(newDate); + Result result = directory.UpdateLastModified(newDate); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(newDate, directory.DateModified.Value); } @@ -102,16 +101,16 @@ public class DirectoryTests public void AddItem_WhenCalled_ShouldAddItemToCollection() { // Arrange - ErrorOr directoryResult = Directory.Create("/valid/path", "TestDirectory", Optional.None(), Optional.None()); - Assert.False(directoryResult.IsError); + Result directoryResult = Directory.Create("/valid/path", "TestDirectory", Optional.None(), Optional.None()); + Assert.False(directoryResult.IsFailure); Directory directory = directoryResult.Value; FileSystemItem item = new FileSystemItemFixture(FileSystemPathId.Create("/mock/path").Value, "MockItem", FileSystemItemType.File); // Act - ErrorOr result = directory.AddItem(item); + Result result = directory.AddItem(item); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Contains(item, directory.Items); } @@ -119,17 +118,17 @@ public class DirectoryTests public void RemoveItem_WhenCalledWithExistingItem_ShouldRemoveItemFromCollection() { // Arrange - ErrorOr directoryResult = Directory.Create("/valid/path", "TestDirectory", Optional.None(), Optional.None()); - Assert.False(directoryResult.IsError); + Result directoryResult = Directory.Create("/valid/path", "TestDirectory", Optional.None(), Optional.None()); + Assert.False(directoryResult.IsFailure); Directory directory = directoryResult.Value; FileSystemItem item = new FileSystemItemFixture(FileSystemPathId.Create("/mock/path").Value, "MockItem", FileSystemItemType.File); directory.AddItem(item); // Act - ErrorOr result = directory.RemoveItem(item); + Result result = directory.RemoveItem(item); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.DoesNotContain(item, directory.Items); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/FileTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/FileTests.cs index 45d150a3..f84c823a 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/FileTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/FileTests.cs @@ -1,10 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -28,10 +27,10 @@ public class FileTests long size = 1024; // Act - ErrorOr result = File.Create(path, name, dateCreated, dateModified, size); + Result result = File.Create(path, name, dateCreated, dateModified, size); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(name, result.Value.Name); Assert.Equal(dateCreated, result.Value.DateCreated); @@ -51,10 +50,10 @@ public class FileTests long size = 1024; // Act - ErrorOr result = File.Create(invalidPath, name, dateCreated, dateModified, size); + Result result = File.Create(invalidPath, name, dateCreated, dateModified, size); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -62,8 +61,8 @@ public class FileTests public void Create_WhenCalledWithFileSystemPathId_ShouldReturnSuccessfulResult() { // Arrange - ErrorOr pathIdResult = FileSystemPathId.Create("/valid/path/file.txt"); - Assert.False(pathIdResult.IsError); + Result pathIdResult = FileSystemPathId.Create("/valid/path/file.txt"); + Assert.False(pathIdResult.IsFailure); FileSystemPathId pathId = pathIdResult.Value; string name = "file.txt"; Optional dateCreated = DateTime.Now; @@ -71,10 +70,10 @@ public class FileTests long size = 1024; // Act - ErrorOr result = File.Create(pathId, name, dateCreated, dateModified, size); + Result result = File.Create(pathId, name, dateCreated, dateModified, size); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(pathId, result.Value.Id); Assert.Equal(name, result.Value.Name); @@ -88,16 +87,16 @@ public class FileTests public void UpdateLastModified_WhenCalled_ShouldUpdateDateModified() { // Arrange - ErrorOr fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); - Assert.False(fileResult.IsError); + Result fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); + Assert.False(fileResult.IsFailure); File file = fileResult.Value; DateTime newDate = DateTime.Now; // Act - ErrorOr result = file.UpdateLastModified(newDate); + Result result = file.UpdateLastModified(newDate); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(newDate, file.DateModified.Value); } @@ -105,16 +104,16 @@ public class FileTests public void UpdateSize_WhenCalled_ShouldUpdateFileSize() { // Arrange - ErrorOr fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); - Assert.False(fileResult.IsError); + Result fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); + Assert.False(fileResult.IsFailure); File file = fileResult.Value; long newSize = 2048; // Act - ErrorOr result = file.UpdateSize(newSize); + Result result = file.UpdateSize(newSize); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(newSize, file.Size); } @@ -122,16 +121,16 @@ public class FileTests public void Rename_WhenCalledWithValidName_ShouldUpdateFileName() { // Arrange - ErrorOr fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); - Assert.False(fileResult.IsError); + Result fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); + Assert.False(fileResult.IsFailure); File file = fileResult.Value; string newName = "newfile.txt"; // Act - ErrorOr result = file.Rename(newName); + Result result = file.Rename(newName); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(newName, file.Name); } @@ -139,16 +138,16 @@ public class FileTests public void Rename_WhenCalledWithEmptyName_ShouldReturnError() { // Arrange - ErrorOr fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); - Assert.False(fileResult.IsError); + Result fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); + Assert.False(fileResult.IsFailure); File file = fileResult.Value; string emptyName = ""; // Act - ErrorOr result = file.Rename(emptyName); + Result result = file.Rename(emptyName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError); Assert.Equal("file.txt", file.Name); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/DirectoryFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/DirectoryFixture.cs index 7c2079ed..59919282 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/DirectoryFixture.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/DirectoryFixture.cs @@ -1,10 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -54,9 +53,9 @@ public class DirectoryFixture dateModified ??= Optional.Some(_faker.Date.Recent()); status ??= _faker.PickRandom(); - ErrorOr directoryResult = Directory.Create(path, name, dateCreated.Value, dateModified.Value, status.Value); + Result directoryResult = Directory.Create(path, name, dateCreated.Value, dateModified.Value, status.Value); - if (directoryResult.IsError) + if (directoryResult.IsFailure) throw new InvalidOperationException("Failed to create Directory: " + string.Join(", ", directoryResult.Errors)); Directory directory = directoryResult.Value; @@ -73,7 +72,7 @@ public class DirectoryFixture /// The created list. public List CreateMany(int count = 3) { - return Enumerable.Range(0, count).Select(_ => CreateDirectory()).ToList(); + return [.. Enumerable.Range(0, count).Select(_ => CreateDirectory())]; } /// @@ -85,7 +84,7 @@ public class DirectoryFixture /// A list of objects with nested structures. public List CreateManyNested(int count = 3, int maxDepth = 3, int maxChildrenPerDirectory = 3) { - return Enumerable.Range(0, count).Select(_ => CreateNestedDirectory(1, maxDepth, maxChildrenPerDirectory)).ToList(); + return [.. Enumerable.Range(0, count).Select(_ => CreateNestedDirectory(1, maxDepth, maxChildrenPerDirectory))]; } /// diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/FileFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/FileFixture.cs index 45aa0776..c6ba3b4b 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/FileFixture.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/FileFixture.cs @@ -1,9 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -47,9 +46,9 @@ public class FileFixture size ??= _faker.Random.Long(); status ??= _faker.PickRandom(); - ErrorOr fileResult = File.Create(path, name, dateCreated.Value, dateModified.Value, size.Value, status.Value); + Result fileResult = File.Create(path, name, dateCreated.Value, dateModified.Value, size.Value, status.Value); - if (fileResult.IsError) + if (fileResult.IsFailure) throw new InvalidOperationException("Failed to create File: " + string.Join(", ", fileResult.Errors)); return fileResult.Value; } @@ -61,7 +60,7 @@ public class FileFixture /// The created list. public List CreateMany(int count = 3) { - return Enumerable.Range(0, count).Select(_ => CreateFile()).ToList(); + return [.. Enumerable.Range(0, count).Select(_ => CreateFile())]; } /// diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs index b74f2a0d..b6e033c7 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -20,10 +20,10 @@ public class UnixRootItemTests public void Create_WhenCalledWithDefaultStatus_ShouldReturnSuccessfulResult() { // Arrange & Act - ErrorOr result = UnixRootItem.Create(); + Result result = UnixRootItem.Create(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal("/", result.Value.Name); Assert.Equal("/", result.Value.Id.Path); @@ -39,10 +39,10 @@ public class UnixRootItemTests FileSystemItemStatus customStatus = FileSystemItemStatus.Accessible; // Act - ErrorOr result = UnixRootItem.Create(customStatus); + Result result = UnixRootItem.Create(customStatus); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal("/", result.Value.Name); Assert.Equal("/", result.Value.Id.Path); @@ -55,8 +55,8 @@ public class UnixRootItemTests public void Items_WhenAccessed_ShouldReturnEmptyReadOnlyCollection() { // Arrange - ErrorOr createResult = UnixRootItem.Create(); - Assert.False(createResult.IsError); + Result createResult = UnixRootItem.Create(); + Assert.False(createResult.IsFailure); UnixRootItem unixRootItem = createResult.Value; // Act @@ -71,16 +71,16 @@ public class UnixRootItemTests public void SetStatus_WhenCalledWithNewStatus_ShouldUpdateStatus() { // Arrange - ErrorOr createResult = UnixRootItem.Create(); - Assert.False(createResult.IsError); + Result createResult = UnixRootItem.Create(); + Assert.False(createResult.IsFailure); UnixRootItem unixRootItem = createResult.Value; FileSystemItemStatus newStatus = FileSystemItemStatus.Accessible; // Act - ErrorOr result = unixRootItem.SetStatus(newStatus); + Result result = unixRootItem.SetStatus(newStatus); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(newStatus, unixRootItem.Status); } @@ -88,15 +88,15 @@ public class UnixRootItemTests public void SetParent_WhenCalledWithNullParent_ShouldReturnError() { // Arrange - ErrorOr createResult = UnixRootItem.Create(); - Assert.False(createResult.IsError); + Result createResult = UnixRootItem.Create(); + Assert.False(createResult.IsFailure); UnixRootItem unixRootItem = createResult.Value; // Act - ErrorOr result = unixRootItem.SetParent(null!); + Result result = unixRootItem.SetParent(null!); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.ParentNodeCannotBeNull, result.FirstError); Assert.False(unixRootItem.Parent.HasValue); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs index b81e719b..b5454ce0 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -25,10 +25,10 @@ public class WindowsRootItemTests string name = "C:"; // Act - ErrorOr result = WindowsRootItem.Create(path, name); + Result result = WindowsRootItem.Create(path, name); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(name, result.Value.Name); Assert.Equal(path, result.Value.Id.Path); @@ -45,10 +45,10 @@ public class WindowsRootItemTests string name = "Invalid"; // Act - ErrorOr result = WindowsRootItem.Create(invalidPath, name); + Result result = WindowsRootItem.Create(invalidPath, name); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -61,10 +61,10 @@ public class WindowsRootItemTests FileSystemItemStatus customStatus = FileSystemItemStatus.Accessible; // Act - ErrorOr result = WindowsRootItem.Create(path, name, customStatus); + Result result = WindowsRootItem.Create(path, name, customStatus); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(name, result.Value.Name); Assert.Equal(path, result.Value.Id.Path); @@ -76,16 +76,16 @@ public class WindowsRootItemTests public void Create_WhenCalledWithFileSystemPathId_ShouldReturnSuccessfulResult() { // Arrange - ErrorOr pathIdResult = FileSystemPathId.Create("E:\\"); - Assert.False(pathIdResult.IsError); + Result pathIdResult = FileSystemPathId.Create("E:\\"); + Assert.False(pathIdResult.IsFailure); FileSystemPathId pathId = pathIdResult.Value; string name = "E:"; // Act - ErrorOr result = WindowsRootItem.Create(pathId, name); + Result result = WindowsRootItem.Create(pathId, name); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(pathId, result.Value.Id); Assert.Equal(name, result.Value.Name); @@ -97,8 +97,8 @@ public class WindowsRootItemTests public void Items_WhenAccessed_ShouldReturnEmptyReadOnlyCollection() { // Arrange - ErrorOr createResult = WindowsRootItem.Create("F:\\", "F:"); - Assert.False(createResult.IsError); + Result createResult = WindowsRootItem.Create("F:\\", "F:"); + Assert.False(createResult.IsFailure); WindowsRootItem windowsRootItem = createResult.Value; // Act @@ -113,16 +113,16 @@ public class WindowsRootItemTests public void SetStatus_WhenCalledWithNewStatus_ShouldUpdateStatus() { // Arrange - ErrorOr createResult = WindowsRootItem.Create("G:\\", "G:"); - Assert.False(createResult.IsError); + Result createResult = WindowsRootItem.Create("G:\\", "G:"); + Assert.False(createResult.IsFailure); WindowsRootItem windowsRootItem = createResult.Value; FileSystemItemStatus newStatus = FileSystemItemStatus.Accessible; // Act - ErrorOr result = windowsRootItem.SetStatus(newStatus); + Result result = windowsRootItem.SetStatus(newStatus); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(newStatus, windowsRootItem.Status); } @@ -130,15 +130,15 @@ public class WindowsRootItemTests public void SetParent_WhenCalledWithNullParent_ShouldReturnError() { // Arrange - ErrorOr createResult = WindowsRootItem.Create("H:\\", "H:"); - Assert.False(createResult.IsError); + Result createResult = WindowsRootItem.Create("H:\\", "H:"); + Assert.False(createResult.IsFailure); WindowsRootItem windowsRootItem = createResult.Value; // Act - ErrorOr result = windowsRootItem.SetParent(null!); + Result result = windowsRootItem.SetParent(null!); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.ParentNodeCannotBeNull, result.FirstError); Assert.False(windowsRootItem.Parent.HasValue); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/FileSystemItemTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/FileSystemItemTests.cs index 8aa8b4e4..e6b09937 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/FileSystemItemTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/FileSystemItemTests.cs @@ -1,12 +1,11 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Fixtures; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using System.Diagnostics.CodeAnalysis; @@ -59,10 +58,10 @@ public class FileSystemItemTests FileSystemItemStatus newStatus = FileSystemItemStatus.Inaccessible; // Act - ErrorOr result = item.SetStatus(newStatus); + Result result = item.SetStatus(newStatus); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Updated, result.Value); Assert.Equal(newStatus, item.Status); } @@ -75,10 +74,10 @@ public class FileSystemItemTests FileSystemItemFixture parent = CreateFileSystemItemFixture(); // Act - ErrorOr result = item.SetParent(parent); + Result result = item.SetParent(parent); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Updated, result.Value); Assert.Equal(Optional.Some(parent), item.Parent); } @@ -90,10 +89,10 @@ public class FileSystemItemTests FileSystemItemFixture item = CreateFileSystemItemFixture(); // Act - ErrorOr result = item.SetParent(null!); + Result result = item.SetParent(null!); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.ParentNodeCannotBeNull, result.FirstError); Assert.Equal(Optional.None(), item.Parent); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs index 75d868c7..62abd03f 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using NSubstitute.ExceptionExtensions; @@ -76,10 +76,10 @@ public class DirectoryProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(false); // Act - ErrorOr> result = _sut.GetSubdirectoryPaths(path, false); + Result> result = _sut.GetSubdirectoryPaths(path, false); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -88,16 +88,16 @@ public class DirectoryProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); - string[] subdirectories = _fixture.CreateMany(3).ToArray(); + string[] subdirectories = [.. _fixture.CreateMany(3)]; _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true); _mockFileSystem.Directory.GetDirectories(path.Path).Returns(subdirectories); _mockFileSystem.Path.DirectorySeparatorChar.Returns(_dirSeparator); // Act - ErrorOr> result = _sut.GetSubdirectoryPaths(path, false); + Result> result = _sut.GetSubdirectoryPaths(path, false); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(3, result.Value.Count()); Assert.Equal( subdirectories.Select(x => x + _dirSeparator).OrderBy(x => x), @@ -118,10 +118,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.File.GetAttributes(_pathHidden1).Returns(FileAttributes.Directory | FileAttributes.Hidden); // Act - ErrorOr> result = _sut.GetSubdirectoryPaths(path, false); + Result> result = _sut.GetSubdirectoryPaths(path, false); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(result.Value); Assert.Equal(_pathVisible2, result.Value.First().Path); } @@ -139,10 +139,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.File.GetAttributes(_pathHidden1).Returns(FileAttributes.Directory | FileAttributes.Hidden); // Act - ErrorOr> result = _sut.GetSubdirectoryPaths(path, true); + Result> result = _sut.GetSubdirectoryPaths(path, true); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); Assert.Equal( new[] { _pathVisible2, _pathHidden2 }.OrderBy(p => p), @@ -163,10 +163,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.File.GetAttributes(_pathInvalid1).Throws(new Exception("Access denied")); // Act - ErrorOr> result = _sut.GetSubdirectoryPaths(path, false); + Result> result = _sut.GetSubdirectoryPaths(path, false); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); Assert.Equal(_pathInvalid2, result.Value.First().Path); Assert.Equal(_pathValid2, result.Value.Last().Path); @@ -189,10 +189,10 @@ public class DirectoryProviderServiceTests : [@"C:\A\", @"C:\B\", @"C:\C\"]; // Act - ErrorOr> result = _sut.GetSubdirectoryPaths(path, false); + Result> result = _sut.GetSubdirectoryPaths(path, false); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(expectedPaths, result.Value.Select(x => x.Path)); } @@ -205,10 +205,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.GetDirectories(path.Path).Returns([]); // Act - ErrorOr> result = _sut.GetSubdirectoryPaths(path, false); + Result> result = _sut.GetSubdirectoryPaths(path, false); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Empty(result.Value); } @@ -220,10 +220,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.Exists(path.Path).Returns(true); // Act - ErrorOr result = _sut.DirectoryExists(path); + Result result = _sut.DirectoryExists(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.True(result.Value); } @@ -235,10 +235,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.Exists(path.Path).Returns(false); // Act - ErrorOr result = _sut.DirectoryExists(path); + Result result = _sut.DirectoryExists(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.False(result.Value); } @@ -253,10 +253,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Path.GetFileName(fullPath).Returns("file.txt"); // Act - ErrorOr result = _sut.GetFileName(path); + Result result = _sut.GetFileName(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal("file.txt", result.Value); } @@ -272,10 +272,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Path.DirectorySeparatorChar.Returns(_dirSeparator); // Act - ErrorOr result = _sut.GetFileName(path); + Result result = _sut.GetFileName(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal("subfolder", result.Value); } @@ -291,10 +291,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Path.DirectorySeparatorChar.Returns(_dirSeparator); // Act - ErrorOr result = _sut.GetFileName(path); + Result result = _sut.GetFileName(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Empty(result.Value); } @@ -308,10 +308,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.GetLastWriteTime(path.Path).Returns(expectedDateTime); // Act - ErrorOr> result = _sut.GetLastWriteTime(path); + Result> result = _sut.GetLastWriteTime(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.True(result.Value.HasValue); Assert.Equal(expectedDateTime, result.Value.Value); } @@ -324,10 +324,10 @@ public class DirectoryProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false).Returns(false); // Act - ErrorOr> result = _sut.GetLastWriteTime(path); + Result> result = _sut.GetLastWriteTime(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -341,10 +341,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.GetCreationTime(path.Path).Returns(expectedDateTime); // Act - ErrorOr> result = _sut.GetCreationTime(path); + Result> result = _sut.GetCreationTime(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.True(result.Value.HasValue); Assert.Equal(expectedDateTime, result.Value.Value); } @@ -357,10 +357,10 @@ public class DirectoryProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false).Returns(false); // Act - ErrorOr> result = _sut.GetCreationTime(path); + Result> result = _sut.GetCreationTime(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -382,10 +382,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.CreateDirectory(fullPath).Returns(mockDirectoryInfo); // Act - ErrorOr result = _sut.CreateDirectory(parentPath, directoryName); + Result result = _sut.CreateDirectory(parentPath, directoryName); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(fullPath, result.Value.Path); _mockFileSystem.Directory.Received(1).CreateDirectory(fullPath); } @@ -400,10 +400,10 @@ public class DirectoryProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(parentPath, FileAccessMode.Write, false).Returns(false); // Act - ErrorOr result = _sut.CreateDirectory(parentPath, directoryName); + Result result = _sut.CreateDirectory(parentPath, directoryName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); _mockFileSystem.Directory.DidNotReceive().CreateDirectory(Arg.Any()); } @@ -416,10 +416,10 @@ public class DirectoryProviderServiceTests string directoryName = "NewDirectory"; // Act - ErrorOr result = _sut.CreateDirectory(parentPath, directoryName); + Result result = _sut.CreateDirectory(parentPath, directoryName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(ErrorType.Failure, result.FirstError.Type); } @@ -436,10 +436,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.CreateDirectory(invalidPath).Returns(Substitute.For()); // Act - ErrorOr result = _sut.CreateDirectory(parentPath, directoryName); + Result result = _sut.CreateDirectory(parentPath, directoryName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(ErrorType.Validation, result.FirstError.Type); } @@ -464,10 +464,10 @@ public class DirectoryProviderServiceTests .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); // Act - ErrorOr result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(destinationPath.Path, result.Value.Path); _mockFileSystem.Directory.Received(1).CreateDirectory(destinationPath.Path); } @@ -483,10 +483,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(false); // Act - ErrorOr result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError); } @@ -516,10 +516,10 @@ public class DirectoryProviderServiceTests .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); // Act - ErrorOr result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(expectedNewDirectoryPath, result.Value.Path); _mockFileSystem.Directory.Received(1).CreateDirectory(expectedNewDirectoryPath); } @@ -568,10 +568,10 @@ public class DirectoryProviderServiceTests .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); // Act - ErrorOr result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(_pathDestination, result.Value.Path); _mockFileSystem.Directory.Received(1).CreateDirectory(_pathDestination); _mockFileSystem.Directory.Received(1).CreateDirectory(_pathDestinationSubDir); @@ -591,10 +591,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.CreateDirectory(Arg.Any()).Throws(new Exception("Simulated error")); // Act - ErrorOr result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.DirectoryCopyError, result.FirstError); } @@ -611,10 +611,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(false); // Act - ErrorOr result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); + Result result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError); } @@ -630,10 +630,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.Exists(destinationPath.Path).Returns(false); // Act - ErrorOr result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); + Result result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(destinationPath.Path, result.Value.Path); _mockFileSystem.Directory.Received(1).Move(sourcePath.Path, destinationPath.Path); } @@ -664,10 +664,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.EnumerateFileSystemEntries(sourcePath.Path).Returns([]); // Act - ErrorOr result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); + Result result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(destinationPath.Path, result.Value.Path); _mockFileSystem.File.Received(1).Move(_pathSourceFile1, _pathDestinationFile1); _mockFileSystem.Directory.Received(1).Move( @@ -691,10 +691,10 @@ public class DirectoryProviderServiceTests .Do(x => throw new IOException("Simulated IO error")); // Act - ErrorOr result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); + Result result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.DirectoryMoveError, result.FirstError); } @@ -729,10 +729,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.EnumerateFileSystemEntries(sourcePath.Path).Returns([]); // Act - ErrorOr result = _sut.MoveDirectory(sourcePath, destPath, overwrite); + Result result = _sut.MoveDirectory(sourcePath, destPath, overwrite); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(destPath, result.Value); _mockFileSystem.File.Received(1).Delete(_pathDestinationFile1); _mockFileSystem.File.Received(1).Move(_pathSourceFile1, _pathDestinationFile1); @@ -767,10 +767,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.EnumerateFileSystemEntries(sourcePath.Path).Returns([_pathSourceFile2]); // Act - ErrorOr result = _sut.MoveDirectory(sourcePath, destPath, overwrite); + Result result = _sut.MoveDirectory(sourcePath, destPath, overwrite); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(destPath, result.Value); _mockFileSystem.File.DidNotReceive().Delete(Arg.Any()); _mockFileSystem.File.DidNotReceive().Move(_pathSourceFile1, _pathDestinationFile1); @@ -833,10 +833,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.EnumerateFileSystemEntries(_pathSourceSubDir).Returns([]); // Act - ErrorOr result = _sut.MoveDirectory(sourcePath, destPath, overwrite); + Result result = _sut.MoveDirectory(sourcePath, destPath, overwrite); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(destPath, result.Value); _mockFileSystem.File.Received(1).Move( s_isUnix ? "/Source/SubDir/file.txt" : @"C:\Source\SubDir\file.txt", @@ -865,10 +865,10 @@ public class DirectoryProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute, false).Returns(true); // Act - ErrorOr result = _sut.RenameDirectory(path, newName); + Result result = _sut.RenameDirectory(path, newName); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(newPath, result.Value.Path); _mockFileSystem.Directory.Received(1).Move(path.Path, newPath); } @@ -891,10 +891,10 @@ public class DirectoryProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(Arg.Any(), FileAccessMode.Write, false).Returns(false); // Act - ErrorOr result = _sut.RenameDirectory(path, newName); + Result result = _sut.RenameDirectory(path, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); } @@ -918,10 +918,10 @@ public class DirectoryProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute, false).Returns(false); // Act - ErrorOr result = _sut.RenameDirectory(path, newName); + Result result = _sut.RenameDirectory(path, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); } @@ -938,10 +938,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.GetParent(path.Path).Returns((IDirectoryInfo)null!); // Act - ErrorOr result = _sut.RenameDirectory(path, newName); + Result result = _sut.RenameDirectory(path, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); } @@ -962,10 +962,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.Path.Combine(parentPath, newName).Returns((string)null!); // Act - ErrorOr result = _sut.RenameDirectory(path, newName); + Result result = _sut.RenameDirectory(path, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); } @@ -982,10 +982,10 @@ public class DirectoryProviderServiceTests _mockFileSystem.DirectoryInfo.New(path.Path).Returns(mockDirectoryInfo); // Act - ErrorOr result = _sut.DeleteDirectory(path); + Result result = _sut.DeleteDirectory(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); mockDirectoryInfo.Received(1).Delete(true); } @@ -1000,10 +1000,10 @@ public class DirectoryProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete, false).Returns(false); // Act - ErrorOr result = _sut.DeleteDirectory(path); + Result result = _sut.DeleteDirectory(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); _mockFileSystem.DirectoryInfo.DidNotReceive().New(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs index c4372721..9488f961 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities.Fixtures; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; @@ -66,23 +65,23 @@ public class DirectoryServiceTests ]; _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) - .Returns(ErrorOrFactory.From(subPaths.AsEnumerable())); + .Returns(Result.From(subPaths.AsEnumerable())); foreach (FileSystemPathId subPath in subPaths) { _mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath) - .Returns(ErrorOrFactory.From(System.IO.Path.GetFileName(subPath.Path))); + .Returns(Result.From(System.IO.Path.GetFileName(subPath.Path))); _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); } // Act - ErrorOr> result = _sut.GetSubdirectories(path, includeHiddenElements); + Result> result = _sut.GetSubdirectories(path, includeHiddenElements); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); Assert.Equal(["Sub1", "Sub2"], result.Value.Select(d => d.Name)); } @@ -95,10 +94,10 @@ public class DirectoryServiceTests bool includeHiddenElements = false; // Act - ErrorOr> result = _sut.GetSubdirectories(invalidPath, includeHiddenElements); + Result> result = _sut.GetSubdirectories(invalidPath, includeHiddenElements); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -114,10 +113,10 @@ public class DirectoryServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr> result = _sut.GetSubdirectories(path, includeHiddenElements); + Result> result = _sut.GetSubdirectories(path, includeHiddenElements); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -133,7 +132,7 @@ public class DirectoryServiceTests ); _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) - .Returns(ErrorOrFactory.From(new[] { subPath }.AsEnumerable())); + .Returns(Result.From(new[] { subPath }.AsEnumerable())); _mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath) .Returns(Errors.Permission.UnauthorizedAccess); @@ -143,10 +142,10 @@ public class DirectoryServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr> result = _sut.GetSubdirectories(path, includeHiddenElements); + Result> result = _sut.GetSubdirectories(path, includeHiddenElements); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(result.Value); Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.First().Status); } @@ -164,23 +163,23 @@ public class DirectoryServiceTests ]; _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, includeHiddenElements) - .Returns(ErrorOrFactory.From(subPaths.AsEnumerable())); + .Returns(Result.From(subPaths.AsEnumerable())); foreach (FileSystemPathId subPath in subPaths) { _mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath) - .Returns(ErrorOrFactory.From(System.IO.Path.GetFileName(subPath.Path))); + .Returns(Result.From(System.IO.Path.GetFileName(subPath.Path))); _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); } // Act - ErrorOr> result = _sut.GetSubdirectories(parentDirectory, includeHiddenElements); + Result> result = _sut.GetSubdirectories(parentDirectory, includeHiddenElements); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); Assert.Equal(["Sub1", "Sub2"], result.Value.Select(d => d.Name)); } @@ -196,10 +195,10 @@ public class DirectoryServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr> result = _sut.GetSubdirectories(parentDirectory, includeHiddenElements); + Result> result = _sut.GetSubdirectories(parentDirectory, includeHiddenElements); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -214,7 +213,7 @@ public class DirectoryServiceTests ); _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, includeHiddenElements) - .Returns(ErrorOrFactory.From(new[] { subPath }.AsEnumerable())); + .Returns(Result.From(new[] { subPath }.AsEnumerable())); _mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath) .Returns(Errors.Permission.UnauthorizedAccess); @@ -224,10 +223,10 @@ public class DirectoryServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr> result = _sut.GetSubdirectories(parentDirectory, includeHiddenElements); + Result> result = _sut.GetSubdirectories(parentDirectory, includeHiddenElements); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(result.Value); Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.First().Status); } @@ -245,23 +244,23 @@ public class DirectoryServiceTests ]; _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) - .Returns(ErrorOrFactory.From(subPaths.AsEnumerable())); + .Returns(Result.From(subPaths.AsEnumerable())); foreach (FileSystemPathId subPath in subPaths) { _mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath) - .Returns(ErrorOrFactory.From(System.IO.Path.GetFileName(subPath.Path))); + .Returns(Result.From(System.IO.Path.GetFileName(subPath.Path))); _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); } // Act - ErrorOr> result = _sut.GetSubdirectories(pathId, includeHiddenElements); + Result> result = _sut.GetSubdirectories(pathId, includeHiddenElements); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); Assert.Equal(["Sub1", "Sub2"], result.Value.Select(d => d.Name)); } @@ -277,10 +276,10 @@ public class DirectoryServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr> result = _sut.GetSubdirectories(pathId, includeHiddenElements); + Result> result = _sut.GetSubdirectories(pathId, includeHiddenElements); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -295,7 +294,7 @@ public class DirectoryServiceTests ); _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) - .Returns(ErrorOrFactory.From(new[] { subPath }.AsEnumerable())); + .Returns(Result.From(new[] { subPath }.AsEnumerable())); _mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath) .Returns(Errors.Permission.UnauthorizedAccess); @@ -305,10 +304,10 @@ public class DirectoryServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr> result = _sut.GetSubdirectories(pathId, includeHiddenElements); + Result> result = _sut.GetSubdirectories(pathId, includeHiddenElements); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(result.Value); Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.First().Status); } @@ -322,20 +321,23 @@ public class DirectoryServiceTests FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(parentPath); FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPath, newDirName)); + _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId)); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(Result.From(false)); + _mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName) - .Returns(ErrorOrFactory.From(newDirPathId)); + .Returns(Result.From(newDirPathId)); _mockEnvironmentContext.DirectoryProviderService.GetFileName(newDirPathId) - .Returns(ErrorOrFactory.From(newDirName)); + .Returns(Result.From(newDirName)); _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newDirPathId) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newDirPathId) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); // Act - ErrorOr result = _sut.CreateDirectory(parentPath, newDirName); + Result result = _sut.CreateDirectory(parentPath, newDirName); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(newDirPathId, result.Value.Id); } @@ -347,10 +349,10 @@ public class DirectoryServiceTests string newDirName = "NewDirectory"; // Act - ErrorOr result = _sut.CreateDirectory(invalidPath, newDirName); + Result result = _sut.CreateDirectory(invalidPath, newDirName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -362,20 +364,23 @@ public class DirectoryServiceTests string newDirName = "NewDirectory"; FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName)); + _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId)); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(Result.From(false)); + _mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName) - .Returns(ErrorOrFactory.From(newDirPathId)); + .Returns(Result.From(newDirPathId)); _mockEnvironmentContext.DirectoryProviderService.GetFileName(newDirPathId) - .Returns(ErrorOrFactory.From(newDirName)); + .Returns(Result.From(newDirName)); _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newDirPathId) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newDirPathId) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); // Act - ErrorOr result = _sut.CreateDirectory(parentPathId, newDirName); + Result result = _sut.CreateDirectory(parentPathId, newDirName); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(newDirPathId, result.Value.Id); } @@ -385,15 +390,19 @@ public class DirectoryServiceTests // Arrange FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest); string newDirName = "NewDirectory"; + FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName)); + + _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId)); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(Result.From(false)); _mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName) .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.CreateDirectory(parentPathId, newDirName); + Result result = _sut.CreateDirectory(parentPathId, newDirName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -405,8 +414,11 @@ public class DirectoryServiceTests string newDirName = "NewDirectory"; FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName)); + _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId)); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(Result.From(false)); + _mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName) - .Returns(ErrorOrFactory.From(newDirPathId)); + .Returns(Result.From(newDirPathId)); _mockEnvironmentContext.DirectoryProviderService.GetFileName(newDirPathId) .Returns(Errors.Permission.UnauthorizedAccess); @@ -416,10 +428,10 @@ public class DirectoryServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.CreateDirectory(parentPathId, newDirName); + Result result = _sut.CreateDirectory(parentPathId, newDirName); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); Assert.Equal(newDirPathId, result.Value.Id); Assert.False(result.Value.DateCreated.HasValue); @@ -434,15 +446,15 @@ public class DirectoryServiceTests string newDirName = "NewDirectory"; FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName)); - _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(ErrorOrFactory.From(newDirPathId)); + _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId)); _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId) .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.CreateDirectory(parentPathId, newDirName); + Result result = _sut.CreateDirectory(parentPathId, newDirName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -453,15 +465,15 @@ public class DirectoryServiceTests FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest); string newDirName = "ExistingDirectory"; FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName)); - _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(ErrorOrFactory.From(newDirPathId)); + _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId)); _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(true); // Act - ErrorOr result = _sut.CreateDirectory(parentPathId, newDirName); + Result result = _sut.CreateDirectory(parentPathId, newDirName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.DirectoryAlreadyExists, result.FirstError); } @@ -476,10 +488,10 @@ public class DirectoryServiceTests .Returns(Errors.FileSystemManagement.InvalidPath); // Act - ErrorOr result = _sut.CreateDirectory(parentPathId, newDirName); + Result result = _sut.CreateDirectory(parentPathId, newDirName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); // Verify that DirectoryExists was not called @@ -498,20 +510,23 @@ public class DirectoryServiceTests s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName" ); + _mockPlatformContext.PathStrategy.CombinePath(oldPathId, newName).Returns(Result.From(newPathId)); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId).Returns(Result.From(false)); + _mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.DirectoryProviderService.GetFileName(newPathId) - .Returns(ErrorOrFactory.From(newName)); + .Returns(Result.From(newName)); _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newPathId) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newPathId) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); // Act - ErrorOr result = _sut.RenameDirectory(oldPath, newName); + Result result = _sut.RenameDirectory(oldPath, newName); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(newPathId, result.Value.Id); Assert.Equal(newName, result.Value.Name); } @@ -524,10 +539,10 @@ public class DirectoryServiceTests string newName = "NewName"; // Act - ErrorOr result = _sut.RenameDirectory(invalidPath, newName); + Result result = _sut.RenameDirectory(invalidPath, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -543,20 +558,23 @@ public class DirectoryServiceTests s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName" ); + _mockPlatformContext.PathStrategy.CombinePath(oldPathId, newName).Returns(Result.From(newPathId)); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId).Returns(Result.From(false)); + _mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.DirectoryProviderService.GetFileName(newPathId) - .Returns(ErrorOrFactory.From(newName)); + .Returns(Result.From(newName)); _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newPathId) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newPathId) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); // Act - ErrorOr result = _sut.RenameDirectory(oldPathId, newName); + Result result = _sut.RenameDirectory(oldPathId, newName); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(newPathId, result.Value.Id); Assert.Equal(newName, result.Value.Name); } @@ -569,15 +587,21 @@ public class DirectoryServiceTests s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName" ); string newName = "NewName"; + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName" + ); + + _mockPlatformContext.PathStrategy.CombinePath(oldPathId, newName).Returns(Result.From(newPathId)); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId).Returns(Result.From(false)); _mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName) .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.RenameDirectory(oldPathId, newName); + Result result = _sut.RenameDirectory(oldPathId, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -593,8 +617,11 @@ public class DirectoryServiceTests s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName" ); + _mockPlatformContext.PathStrategy.CombinePath(oldPathId, newName).Returns(Result.From(newPathId)); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId).Returns(Result.From(false)); + _mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.DirectoryProviderService.GetFileName(newPathId) .Returns(Errors.Permission.UnauthorizedAccess); @@ -604,10 +631,10 @@ public class DirectoryServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.RenameDirectory(oldPathId, newName); + Result result = _sut.RenameDirectory(oldPathId, newName); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); Assert.Equal(newPathId, result.Value.Id); Assert.False(result.Value.DateCreated.HasValue); @@ -627,15 +654,15 @@ public class DirectoryServiceTests ); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId) - .Returns(ErrorOrFactory.From(true)); + .Returns(Result.From(true)); // Act - ErrorOr result = _sut.RenameDirectory(oldPathId, newName); + Result result = _sut.RenameDirectory(oldPathId, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.DirectoryAlreadyExists, result.FirstError); } @@ -652,10 +679,10 @@ public class DirectoryServiceTests .Returns(Errors.FileSystemManagement.InvalidPath); // Act - ErrorOr result = _sut.RenameDirectory(oldPathId, newName); + Result result = _sut.RenameDirectory(oldPathId, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); // Verify that DirectoryExists and RenameDirectory were not called @@ -675,16 +702,16 @@ public class DirectoryServiceTests s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName" ); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId) .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.RenameDirectory(oldPathId, newName); + Result result = _sut.RenameDirectory(oldPathId, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); // Verify that RenameDirectory was not called @@ -702,10 +729,10 @@ public class DirectoryServiceTests .Returns(Result.Deleted); // Act - ErrorOr result = _sut.DeleteDirectory(path); + Result result = _sut.DeleteDirectory(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); } @@ -716,10 +743,10 @@ public class DirectoryServiceTests string invalidPath = string.Empty; // Act - ErrorOr result = _sut.DeleteDirectory(invalidPath); + Result result = _sut.DeleteDirectory(invalidPath); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -735,10 +762,10 @@ public class DirectoryServiceTests .Returns(Result.Deleted); // Act - ErrorOr result = _sut.DeleteDirectory(pathId); + Result result = _sut.DeleteDirectory(pathId); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); } @@ -754,10 +781,10 @@ public class DirectoryServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.DeleteDirectory(pathId); + Result result = _sut.DeleteDirectory(pathId); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -773,10 +800,10 @@ public class DirectoryServiceTests .Returns(Errors.FileSystemManagement.DirectoryNotFound); // Act - ErrorOr result = _sut.DeleteDirectory(pathId); + Result result = _sut.DeleteDirectory(pathId); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DriveServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DriveServiceTests.cs index dd00ea9b..b7b8ad35 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DriveServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DriveServiceTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -44,10 +44,10 @@ public class DriveServiceTests _mockPlatformContext.Platform.Returns(PlatformType.Unix); // Act - ErrorOr> result = _sut.GetDrives(); + Result> result = _sut.GetDrives(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(result.Value); Assert.IsType(result.Value.First()); Assert.Equal(FileSystemItemStatus.Accessible, result.Value.First().Status); @@ -67,10 +67,10 @@ public class DriveServiceTests _mockFileSystem.DriveInfo.GetDrives().Returns(mockDrives); // Act - ErrorOr> result = _sut.GetDrives(); + Result> result = _sut.GetDrives(); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); // Only ready drives Assert.All(result.Value, item => Assert.IsType(item)); Assert.Equal(["C:\\", "D:\\"], result.Value.Select(d => d.Name)); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs index e0c6b0c6..6ad13a46 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs @@ -1,12 +1,11 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using NSubstitute.ExceptionExtensions; @@ -62,10 +61,10 @@ public class FileProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(false); // Act - ErrorOr> result = _sut.GetFilePaths(path, false); + Result> result = _sut.GetFilePaths(path, false); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -79,10 +78,10 @@ public class FileProviderServiceTests _mockFileSystem.Directory.GetFiles(path.Path).Returns(files); // Act - ErrorOr> result = _sut.GetFilePaths(path, false); + Result> result = _sut.GetFilePaths(path, false); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(3, result.Value.Count()); Assert.Equal( files.OrderBy(f => f), @@ -102,10 +101,10 @@ public class FileProviderServiceTests _mockFileSystem.File.GetAttributes(_pathHidden1).Returns(FileAttributes.Hidden); // Act - ErrorOr> result = _sut.GetFilePaths(path, false); + Result> result = _sut.GetFilePaths(path, false); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(result.Value); Assert.Equal(_pathVisible1, result.Value.First().Path); } @@ -122,10 +121,10 @@ public class FileProviderServiceTests _mockFileSystem.File.GetAttributes(_pathHidden1).Returns(FileAttributes.Hidden); // Act - ErrorOr> result = _sut.GetFilePaths(path, true); + Result> result = _sut.GetFilePaths(path, true); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); Assert.Equal( new[] { _pathVisible1, _pathHidden1 }.OrderBy(p => p), @@ -145,10 +144,10 @@ public class FileProviderServiceTests _mockFileSystem.File.GetAttributes(_pathInvalid1).Throws(new Exception("Access denied")); // Act - ErrorOr> result = _sut.GetFilePaths(path, false); + Result> result = _sut.GetFilePaths(path, false); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); Assert.Equal([_pathInvalid1, _pathValid1], result.Value.Select(x => x.Path)); } @@ -169,10 +168,10 @@ public class FileProviderServiceTests _mockFileSystem.File.GetAttributes(Arg.Any()).Returns(FileAttributes.Normal); // Act - ErrorOr> result = _sut.GetFilePaths(path, false); + Result> result = _sut.GetFilePaths(path, false); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(expectedFiles, result.Value.Select(x => x.Path)); } @@ -185,10 +184,10 @@ public class FileProviderServiceTests _mockFileSystem.Directory.GetFiles(path.Path).Returns([]); // Act - ErrorOr> result = _sut.GetFilePaths(path, false); + Result> result = _sut.GetFilePaths(path, false); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Empty(result.Value); } @@ -200,10 +199,10 @@ public class FileProviderServiceTests _mockFileSystem.File.Exists(path.Path).Returns(true); // Act - ErrorOr result = _sut.FileExists(path); + Result result = _sut.FileExists(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.True(result.Value); } @@ -215,10 +214,10 @@ public class FileProviderServiceTests _mockFileSystem.File.Exists(path.Path).Returns(false); // Act - ErrorOr result = _sut.FileExists(path); + Result result = _sut.FileExists(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.False(result.Value); } @@ -231,10 +230,10 @@ public class FileProviderServiceTests _mockFileSystem.Path.GetFileName(path.Path).Returns(expectedFileName); // Act - ErrorOr result = _sut.GetFileName(path); + Result result = _sut.GetFileName(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(expectedFileName, result.Value); } @@ -246,10 +245,10 @@ public class FileProviderServiceTests _mockFileSystem.Path.GetFileName(path.Path).Returns(string.Empty); // Act - ErrorOr result = _sut.GetFileName(path); + Result result = _sut.GetFileName(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Empty(result.Value); } @@ -270,10 +269,10 @@ public class FileProviderServiceTests _mockFileSystem.File.ReadAllBytes(tempFilePath).Returns(x => File.ReadAllBytes(x.Arg())); // Act - ErrorOr result = _sut.GetFileAsync(path); + Result result = _sut.GetFileAsync(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(expectedContents, result.Value); } finally @@ -291,10 +290,10 @@ public class FileProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(false); // Act - ErrorOr result = _sut.GetFileAsync(path); + Result result = _sut.GetFileAsync(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -309,10 +308,10 @@ public class FileProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true); // Act - ErrorOr result = _sut.GetFileAsync(path); + Result result = _sut.GetFileAsync(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Empty(result.Value); } finally @@ -337,10 +336,10 @@ public class FileProviderServiceTests _mockFileSystem.File.GetLastWriteTime(path.Path).Returns(expectedDateTime); // Act - ErrorOr> result = _sut.GetLastWriteTime(path); + Result> result = _sut.GetLastWriteTime(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.True(result.Value.HasValue); Assert.Equal(expectedDateTime, result.Value.Value, TimeSpan.FromSeconds(1)); } @@ -358,10 +357,10 @@ public class FileProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false); // Act - ErrorOr> result = _sut.GetLastWriteTime(path); + Result> result = _sut.GetLastWriteTime(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -380,10 +379,10 @@ public class FileProviderServiceTests _mockFileSystem.File.GetCreationTime(path.Path).Returns(expectedDateTime); // Act - ErrorOr> result = _sut.GetCreationTime(path); + Result> result = _sut.GetCreationTime(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.True(result.Value.HasValue); Assert.Equal(expectedDateTime, result.Value.Value, TimeSpan.FromSeconds(1)); } @@ -401,10 +400,10 @@ public class FileProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false); // Act - ErrorOr> result = _sut.GetCreationTime(path); + Result> result = _sut.GetCreationTime(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -424,10 +423,10 @@ public class FileProviderServiceTests _mockFileSystem.FileInfo.New(path.Path).Returns(new FileInfoWrapper(_mockFileSystem, new FileInfo(tempFilePath))); // Act - ErrorOr result = _sut.GetSize(path); + Result result = _sut.GetSize(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(expectedSize, result.Value); } @@ -445,10 +444,10 @@ public class FileProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false); // Act - ErrorOr result = _sut.GetSize(path); + Result result = _sut.GetSize(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -463,10 +462,10 @@ public class FileProviderServiceTests _mockFileSystem.FileInfo.New(path.Path).Returns((IFileInfo)null!); // Act - ErrorOr result = _sut.GetSize(path); + Result result = _sut.GetSize(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(0, result.Value); } @@ -485,10 +484,10 @@ public class FileProviderServiceTests _mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(_pathDestinationFile); // Act - ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(_pathDestinationFile, result.Value.Path); _mockFileSystem.File.Received(1).Copy(sourcePath.Path, _pathDestinationFile, overrideExisting); } @@ -504,10 +503,10 @@ public class FileProviderServiceTests _mockFileSystem.File.Exists(sourcePath.Path).Returns(false); // Act - ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); } @@ -530,10 +529,10 @@ public class FileProviderServiceTests .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); // Act - ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.FileAlreadyExists, result.FirstError); _mockFileSystem.File.DidNotReceive().Copy(Arg.Any(), Arg.Any(), Arg.Any()); } @@ -553,10 +552,10 @@ public class FileProviderServiceTests _mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(_pathDestinationFile); // Act - ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(_pathDestinationFile, result.Value.Path); _mockFileSystem.File.Received(1).Copy(sourcePath.Path, _pathDestinationFile, overrideExisting); } @@ -574,10 +573,10 @@ public class FileProviderServiceTests .Do(x => { throw new Exception("Simulated error"); }); // Act - ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.FileCopyError, result.FirstError); } @@ -616,10 +615,10 @@ public class FileProviderServiceTests }); // Act - ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(expectedNewFilePath, result.Value.Path); _mockFileSystem.File.Received(1).Copy(sourcePath.Path, expectedNewFilePath, overrideExisting); } @@ -637,10 +636,10 @@ public class FileProviderServiceTests _mockFileSystem.File.Exists(sourcePath.Path).Returns(false); // Act - ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); } @@ -659,10 +658,10 @@ public class FileProviderServiceTests _mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(destinationFilePath); // Act - ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(destinationFilePath, result.Value.Path); _mockFileSystem.File.Received(1).Move(sourcePath.Path, destinationFilePath); } @@ -682,10 +681,10 @@ public class FileProviderServiceTests _mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(destinationFilePath); // Act - ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(destinationFilePath, result.Value.Path); _mockFileSystem.File.Received(1).Move(sourcePath.Path, destinationFilePath, overrideExisting); } @@ -705,10 +704,10 @@ public class FileProviderServiceTests _mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(destinationFilePath); // Act - ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.FileAlreadyExists, result.FirstError); } @@ -729,10 +728,10 @@ public class FileProviderServiceTests .Do(x => throw new IOException("Simulated IO error")); // Act - ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.FileMoveError, result.FirstError); } @@ -755,10 +754,10 @@ public class FileProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute).Returns(true); // Act - ErrorOr result = _sut.RenameFile(path, newName); + Result result = _sut.RenameFile(path, newName); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(newPath, result.Value.Path); _mockFileSystem.File.Received(1).Move(path.Path, newPath); } @@ -781,10 +780,10 @@ public class FileProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(Arg.Any(), FileAccessMode.Write).Returns(false); // Act - ErrorOr result = _sut.RenameFile(path, newName); + Result result = _sut.RenameFile(path, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); } @@ -808,10 +807,10 @@ public class FileProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute).Returns(false); // Act - ErrorOr result = _sut.RenameFile(path, newName); + Result result = _sut.RenameFile(path, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); } @@ -828,10 +827,10 @@ public class FileProviderServiceTests _mockFileSystem.FileInfo.New(path.Path).Returns((IFileInfo)null!); // Act - ErrorOr result = _sut.RenameFile(path, newName); + Result result = _sut.RenameFile(path, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.CannotNavigateUp, result.FirstError); _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); } @@ -852,10 +851,10 @@ public class FileProviderServiceTests _mockFileSystem.Path.Combine(parentPath, newName).Returns((string)null!); // Act - ErrorOr result = _sut.RenameFile(path, newName); + Result result = _sut.RenameFile(path, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); } @@ -877,7 +876,7 @@ public class FileProviderServiceTests _mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath); // Mock successful creation of parent directory FileSystemPathId - ErrorOr parentDirectoryPathId = FileSystemPathId.Create(parentPath); + Result parentDirectoryPathId = FileSystemPathId.Create(parentPath); _mockFileSystem.Path.GetDirectoryName(path.Path).Returns(parentPath); // Mock permissions: executable for the file, but not writable for the parent directory @@ -885,10 +884,10 @@ public class FileProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(Arg.Is(x => x.Path == parentPath), FileAccessMode.Write).Returns(false); // Act - ErrorOr result = _sut.RenameFile(path, newName); + Result result = _sut.RenameFile(path, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); } @@ -904,10 +903,10 @@ public class FileProviderServiceTests _mockFileSystem.File.Exists(path.Path).Returns(true); // Act - ErrorOr result = _sut.DeleteFile(path); + Result result = _sut.DeleteFile(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); _mockFileSystem.File.Received(1).Delete(path.Path); } @@ -922,10 +921,10 @@ public class FileProviderServiceTests _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(false); // Act - ErrorOr result = _sut.DeleteFile(path); + Result result = _sut.DeleteFile(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); _mockFileSystem.File.DidNotReceive().Delete(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileServiceTests.cs index 3d97baf6..4cf46087 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileServiceTests.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities.Fixtures; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; @@ -76,25 +75,25 @@ public class FileServiceTests ]; _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) - .Returns(ErrorOrFactory.From(filePaths.AsEnumerable())); + .Returns(Result.From(filePaths.AsEnumerable())); foreach (FileSystemPathId filePath in filePaths) { _mockEnvironmentContext.FileProviderService.GetFileName(filePath) - .Returns(ErrorOrFactory.From(System.IO.Path.GetFileName(filePath.Path))); + .Returns(Result.From(System.IO.Path.GetFileName(filePath.Path))); _mockEnvironmentContext.FileProviderService.GetLastWriteTime(filePath) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); _mockEnvironmentContext.FileProviderService.GetCreationTime(filePath) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); _mockEnvironmentContext.FileProviderService.GetSize(filePath) - .Returns(ErrorOrFactory.From((long?)1024)); + .Returns(Result.From((long?)1024)); } // Act - ErrorOr> result = _sut.GetFiles(path, includeHiddenElements); + Result> result = _sut.GetFiles(path, includeHiddenElements); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); Assert.Equal(["File1.txt", "File2.txt"], result.Value.Select(f => f.Name)); } @@ -107,10 +106,10 @@ public class FileServiceTests bool includeHiddenElements = false; // Act - ErrorOr> result = _sut.GetFiles(invalidPath, includeHiddenElements); + Result> result = _sut.GetFiles(invalidPath, includeHiddenElements); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -126,10 +125,10 @@ public class FileServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr> result = _sut.GetFiles(path, includeHiddenElements); + Result> result = _sut.GetFiles(path, includeHiddenElements); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -143,7 +142,7 @@ public class FileServiceTests FileSystemPathId filePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathTestDirInaccessible); _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) - .Returns(ErrorOrFactory.From(new[] { filePath }.AsEnumerable())); + .Returns(Result.From(new[] { filePath }.AsEnumerable())); _mockEnvironmentContext.FileProviderService.GetFileName(filePath) .Returns(Errors.Permission.UnauthorizedAccess); @@ -152,13 +151,13 @@ public class FileServiceTests _mockEnvironmentContext.FileProviderService.GetCreationTime(filePath) .Returns(Errors.Permission.UnauthorizedAccess); _mockEnvironmentContext.FileProviderService.GetSize(filePath) - .Returns(ErrorOrFactory.From((long?)null)); + .Returns(Result.From((long?)null)); // Act - ErrorOr> result = _sut.GetFiles(path, includeHiddenElements); + Result> result = _sut.GetFiles(path, includeHiddenElements); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(result.Value); Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.First().Status); } @@ -176,25 +175,25 @@ public class FileServiceTests ]; _mockEnvironmentContext.FileProviderService.GetFilePaths(parentFile.Id, includeHiddenElements) - .Returns(ErrorOrFactory.From(filePaths.AsEnumerable())); + .Returns(Result.From(filePaths.AsEnumerable())); foreach (FileSystemPathId filePath in filePaths) { _mockEnvironmentContext.FileProviderService.GetFileName(filePath) - .Returns(ErrorOrFactory.From(System.IO.Path.GetFileName(filePath.Path))); + .Returns(Result.From(System.IO.Path.GetFileName(filePath.Path))); _mockEnvironmentContext.FileProviderService.GetLastWriteTime(filePath) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); _mockEnvironmentContext.FileProviderService.GetCreationTime(filePath) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); _mockEnvironmentContext.FileProviderService.GetSize(filePath) - .Returns(ErrorOrFactory.From((long?)1024)); + .Returns(Result.From((long?)1024)); } // Act - ErrorOr> result = _sut.GetFiles(parentFile, includeHiddenElements); + Result> result = _sut.GetFiles(parentFile, includeHiddenElements); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); Assert.Equal(["File1.txt", "File2.txt"], result.Value.Select(f => f.Name)); } @@ -210,10 +209,10 @@ public class FileServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr> result = _sut.GetFiles(parentFile, includeHiddenElements); + Result> result = _sut.GetFiles(parentFile, includeHiddenElements); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -226,7 +225,7 @@ public class FileServiceTests FileSystemPathId filePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathTestDirInaccessible); _mockEnvironmentContext.FileProviderService.GetFilePaths(parentFile.Id, includeHiddenElements) - .Returns(ErrorOrFactory.From(new[] { filePath }.AsEnumerable())); + .Returns(Result.From(new[] { filePath }.AsEnumerable())); _mockEnvironmentContext.FileProviderService.GetFileName(filePath) .Returns(Errors.Permission.UnauthorizedAccess); @@ -235,13 +234,13 @@ public class FileServiceTests _mockEnvironmentContext.FileProviderService.GetCreationTime(filePath) .Returns(Errors.Permission.UnauthorizedAccess); _mockEnvironmentContext.FileProviderService.GetSize(filePath) - .Returns(ErrorOrFactory.From((long?)null)); + .Returns(Result.From((long?)null)); // Act - ErrorOr> result = _sut.GetFiles(parentFile, includeHiddenElements); + Result> result = _sut.GetFiles(parentFile, includeHiddenElements); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(result.Value); Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.First().Status); } @@ -259,25 +258,25 @@ public class FileServiceTests ]; _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) - .Returns(ErrorOrFactory.From(filePaths.AsEnumerable())); + .Returns(Result.From(filePaths.AsEnumerable())); foreach (FileSystemPathId filePath in filePaths) { _mockEnvironmentContext.FileProviderService.GetFileName(filePath) - .Returns(ErrorOrFactory.From(System.IO.Path.GetFileName(filePath.Path))); + .Returns(Result.From(System.IO.Path.GetFileName(filePath.Path))); _mockEnvironmentContext.FileProviderService.GetLastWriteTime(filePath) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); _mockEnvironmentContext.FileProviderService.GetCreationTime(filePath) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); _mockEnvironmentContext.FileProviderService.GetSize(filePath) - .Returns(ErrorOrFactory.From((long?)1024)); + .Returns(Result.From((long?)1024)); } // Act - ErrorOr> result = _sut.GetFiles(pathId, includeHiddenElements); + Result> result = _sut.GetFiles(pathId, includeHiddenElements); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); Assert.Equal(["File1.txt", "File2.txt"], result.Value.Select(f => f.Name)); } @@ -293,10 +292,10 @@ public class FileServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr> result = _sut.GetFiles(pathId, includeHiddenElements); + Result> result = _sut.GetFiles(pathId, includeHiddenElements); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -309,7 +308,7 @@ public class FileServiceTests FileSystemPathId filePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathTestDirInaccessible); _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) - .Returns(ErrorOrFactory.From(new[] { filePath }.AsEnumerable())); + .Returns(Result.From(new[] { filePath }.AsEnumerable())); _mockEnvironmentContext.FileProviderService.GetFileName(filePath) .Returns(Errors.Permission.UnauthorizedAccess); @@ -318,13 +317,13 @@ public class FileServiceTests _mockEnvironmentContext.FileProviderService.GetCreationTime(filePath) .Returns(Errors.Permission.UnauthorizedAccess); _mockEnvironmentContext.FileProviderService.GetSize(filePath) - .Returns(ErrorOrFactory.From((long?)null)); + .Returns(Result.From((long?)null)); // Act - ErrorOr> result = _sut.GetFiles(pathId, includeHiddenElements); + Result> result = _sut.GetFiles(pathId, includeHiddenElements); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(result.Value); Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.First().Status); } @@ -354,10 +353,10 @@ public class FileServiceTests _mockEnvironmentContext.FileProviderService.GetSize(copiedFilePathId).Returns((long?)1024); // Act - ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal("file.txt", result.Value.Name); Assert.Equal(FileSystemItemStatus.Accessible, result.Value.Status); @@ -372,13 +371,13 @@ public class FileServiceTests bool overrideExisting = true; FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); - _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(ErrorOrFactory.From(false)); + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(Result.From(false)); // Act - ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); } @@ -393,15 +392,15 @@ public class FileServiceTests FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(destinationPath); _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); - _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(ErrorOrFactory.From(true)); + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(Result.From(true)); _mockEnvironmentContext.FileProviderService.CopyFile(sourcePathId, destinationPathId, overrideExisting) .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -417,20 +416,20 @@ public class FileServiceTests FileSystemPathId copiedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestinationFile); _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); - _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(ErrorOrFactory.From(true)); + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(Result.From(true)); _mockEnvironmentContext.FileProviderService.CopyFile(sourcePathId, destinationPathId, overrideExisting) - .Returns(ErrorOrFactory.From(copiedFilePathId)); + .Returns(Result.From(copiedFilePathId)); _mockEnvironmentContext.FileProviderService.GetFileName(copiedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); _mockEnvironmentContext.FileProviderService.GetLastWriteTime(copiedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); _mockEnvironmentContext.FileProviderService.GetCreationTime(copiedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); - _mockEnvironmentContext.FileProviderService.GetSize(copiedFilePathId).Returns(ErrorOrFactory.From((long?)null)); + _mockEnvironmentContext.FileProviderService.GetSize(copiedFilePathId).Returns(Result.From((long?)null)); // Act - ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); } @@ -444,10 +443,10 @@ public class FileServiceTests bool overrideExisting = true; // Act - ErrorOr result = _sut.CopyFile(invalidSourcePath, destinationPath, overrideExisting); + Result result = _sut.CopyFile(invalidSourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -461,10 +460,10 @@ public class FileServiceTests _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); // Act - ErrorOr result = _sut.CopyFile(sourcePath, invalidDestinationPath, overrideExisting); + Result result = _sut.CopyFile(sourcePath, invalidDestinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -488,10 +487,10 @@ public class FileServiceTests _mockEnvironmentContext.FileProviderService.GetSize(copiedFilePathId).Returns((long?)1024); // Act - ErrorOr result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); + Result result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal("file.txt", result.Value.Name); Assert.Equal(FileSystemItemStatus.Accessible, result.Value.Status); @@ -508,10 +507,10 @@ public class FileServiceTests _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(false); // Act - ErrorOr result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); + Result result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); } @@ -528,10 +527,10 @@ public class FileServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); + Result result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -551,13 +550,13 @@ public class FileServiceTests _mockEnvironmentContext.FileProviderService.GetFileName(copiedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); _mockEnvironmentContext.FileProviderService.GetLastWriteTime(copiedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); _mockEnvironmentContext.FileProviderService.GetCreationTime(copiedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); - _mockEnvironmentContext.FileProviderService.GetSize(copiedFilePathId).Returns(ErrorOrFactory.From((long?)null)); + _mockEnvironmentContext.FileProviderService.GetSize(copiedFilePathId).Returns(Result.From((long?)null)); // Act - ErrorOr result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); + Result result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); } @@ -587,10 +586,10 @@ public class FileServiceTests _mockEnvironmentContext.FileProviderService.GetSize(movedFilePathId).Returns((long?)1024); // Act - ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal("file.txt", result.Value.Name); Assert.Equal(FileSystemItemStatus.Accessible, result.Value.Status); @@ -609,10 +608,10 @@ public class FileServiceTests _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(false); // Act - ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); } @@ -632,10 +631,10 @@ public class FileServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -660,13 +659,13 @@ public class FileServiceTests _mockEnvironmentContext.FileProviderService.GetFileName(movedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); _mockEnvironmentContext.FileProviderService.GetLastWriteTime(movedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); _mockEnvironmentContext.FileProviderService.GetCreationTime(movedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); - _mockEnvironmentContext.FileProviderService.GetSize(movedFilePathId).Returns(ErrorOrFactory.From((long?)null)); + _mockEnvironmentContext.FileProviderService.GetSize(movedFilePathId).Returns(Result.From((long?)null)); // Act - ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); } @@ -682,10 +681,10 @@ public class FileServiceTests _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); // Act - ErrorOr result = _sut.MoveFile(invalidSourcePath, destinationPath, overrideExisting); + Result result = _sut.MoveFile(invalidSourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -700,10 +699,10 @@ public class FileServiceTests _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); // Act - ErrorOr result = _sut.MoveFile(sourcePath, invalidDestinationPath, overrideExisting); + Result result = _sut.MoveFile(sourcePath, invalidDestinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -727,10 +726,10 @@ public class FileServiceTests _mockEnvironmentContext.FileProviderService.GetSize(movedFilePathId).Returns((long?)1024); // Act - ErrorOr result = _sut.MoveFile(sourcePathId, destinationPathId, overrideExisting); + Result result = _sut.MoveFile(sourcePathId, destinationPathId, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal("file.txt", result.Value.Name); Assert.Equal(FileSystemItemStatus.Accessible, result.Value.Status); @@ -749,10 +748,10 @@ public class FileServiceTests _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(false); // Act - ErrorOr result = _sut.MoveFile(sourcePathId, destinationPathId, overrideExisting); + Result result = _sut.MoveFile(sourcePathId, destinationPathId, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); } @@ -769,10 +768,10 @@ public class FileServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.MoveFile(sourcePathId, destinationPathId, overrideExisting); + Result result = _sut.MoveFile(sourcePathId, destinationPathId, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -792,13 +791,13 @@ public class FileServiceTests _mockEnvironmentContext.FileProviderService.GetFileName(movedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); _mockEnvironmentContext.FileProviderService.GetLastWriteTime(movedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); _mockEnvironmentContext.FileProviderService.GetCreationTime(movedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); - _mockEnvironmentContext.FileProviderService.GetSize(movedFilePathId).Returns(ErrorOrFactory.From((long?)null)); + _mockEnvironmentContext.FileProviderService.GetSize(movedFilePathId).Returns(Result.From((long?)null)); // Act - ErrorOr result = _sut.MoveFile(sourcePathId, destinationPathId, overrideExisting); + Result result = _sut.MoveFile(sourcePathId, destinationPathId, overrideExisting); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); } @@ -817,10 +816,10 @@ public class FileServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + Result result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -835,22 +834,22 @@ public class FileServiceTests _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(false); _mockEnvironmentContext.FileProviderService.RenameFile(pathId, newName) - .Returns(ErrorOrFactory.From(newPathId)); - _mockEnvironmentContext.FileProviderService.GetFileName(newPathId).Returns(ErrorOrFactory.From(newName)); + .Returns(Result.From(newPathId)); + _mockEnvironmentContext.FileProviderService.GetFileName(newPathId).Returns(Result.From(newName)); _mockEnvironmentContext.FileProviderService.GetLastWriteTime(newPathId) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); _mockEnvironmentContext.FileProviderService.GetCreationTime(newPathId) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); - _mockEnvironmentContext.FileProviderService.GetSize(newPathId).Returns(ErrorOrFactory.From((long?)1024)); + .Returns(Result.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + _mockEnvironmentContext.FileProviderService.GetSize(newPathId).Returns(Result.From((long?)1024)); // Act - ErrorOr result = _sut.RenameFile(path, newName); + Result result = _sut.RenameFile(path, newName); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(newName, result.Value.Name); Assert.Equal(FileSystemItemStatus.Accessible, result.Value.Status); @@ -866,14 +865,14 @@ public class FileServiceTests _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(true); // Act - ErrorOr result = _sut.RenameFile(path, newName); + Result result = _sut.RenameFile(path, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.FileAlreadyExists, result.FirstError); } @@ -888,16 +887,16 @@ public class FileServiceTests _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(false); _mockEnvironmentContext.FileProviderService.RenameFile(pathId, newName) .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.RenameFile(path, newName); + Result result = _sut.RenameFile(path, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -912,21 +911,21 @@ public class FileServiceTests _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(false); _mockEnvironmentContext.FileProviderService.RenameFile(pathId, newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.FileProviderService.GetFileName(newPathId).Returns(Errors.Permission.UnauthorizedAccess); _mockEnvironmentContext.FileProviderService.GetLastWriteTime(newPathId).Returns(Errors.Permission.UnauthorizedAccess); _mockEnvironmentContext.FileProviderService.GetCreationTime(newPathId).Returns(Errors.Permission.UnauthorizedAccess); - _mockEnvironmentContext.FileProviderService.GetSize(newPathId).Returns(ErrorOrFactory.From((long?)null)); + _mockEnvironmentContext.FileProviderService.GetSize(newPathId).Returns(Result.From((long?)null)); // Act - ErrorOr result = _sut.RenameFile(path, newName); + Result result = _sut.RenameFile(path, newName); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); } @@ -941,10 +940,10 @@ public class FileServiceTests _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); // Act - ErrorOr result = _sut.RenameFile(invalidPath, newName); + Result result = _sut.RenameFile(invalidPath, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -957,22 +956,22 @@ public class FileServiceTests FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceNewFile); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(false); _mockEnvironmentContext.FileProviderService.RenameFile(pathId, newName) - .Returns(ErrorOrFactory.From(newPathId)); - _mockEnvironmentContext.FileProviderService.GetFileName(newPathId).Returns(ErrorOrFactory.From(newName)); + .Returns(Result.From(newPathId)); + _mockEnvironmentContext.FileProviderService.GetFileName(newPathId).Returns(Result.From(newName)); _mockEnvironmentContext.FileProviderService.GetLastWriteTime(newPathId) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); _mockEnvironmentContext.FileProviderService.GetCreationTime(newPathId) - .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); - _mockEnvironmentContext.FileProviderService.GetSize(newPathId).Returns(ErrorOrFactory.From((long?)1024)); + .Returns(Result.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + _mockEnvironmentContext.FileProviderService.GetSize(newPathId).Returns(Result.From((long?)1024)); // Act - ErrorOr result = _sut.RenameFile(pathId, newName); + Result result = _sut.RenameFile(pathId, newName); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(newName, result.Value.Name); Assert.Equal(FileSystemItemStatus.Accessible, result.Value.Status); @@ -987,14 +986,14 @@ public class FileServiceTests FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceExistingFile); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(true); // Act - ErrorOr result = _sut.RenameFile(pathId, newName); + Result result = _sut.RenameFile(pathId, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.FileAlreadyExists, result.FirstError); } @@ -1007,16 +1006,16 @@ public class FileServiceTests FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceNewFile); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(false); _mockEnvironmentContext.FileProviderService.RenameFile(pathId, newName) .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.RenameFile(pathId, newName); + Result result = _sut.RenameFile(pathId, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -1029,21 +1028,21 @@ public class FileServiceTests FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceNewFile); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(false); _mockEnvironmentContext.FileProviderService.RenameFile(pathId, newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.FileProviderService.GetFileName(newPathId).Returns(Errors.Permission.UnauthorizedAccess); _mockEnvironmentContext.FileProviderService.GetLastWriteTime(newPathId).Returns(Errors.Permission.UnauthorizedAccess); _mockEnvironmentContext.FileProviderService.GetCreationTime(newPathId).Returns(Errors.Permission.UnauthorizedAccess); - _mockEnvironmentContext.FileProviderService.GetSize(newPathId).Returns(ErrorOrFactory.From((long?)null)); + _mockEnvironmentContext.FileProviderService.GetSize(newPathId).Returns(Result.From((long?)null)); // Act - ErrorOr result = _sut.RenameFile(pathId, newName); + Result result = _sut.RenameFile(pathId, newName); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.NotNull(result.Value); Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); } @@ -1060,10 +1059,10 @@ public class FileServiceTests .Returns(Errors.FileSystemManagement.InvalidPath); // Act - ErrorOr result = _sut.RenameFile(path, newName); + Result result = _sut.RenameFile(path, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -1077,15 +1076,15 @@ public class FileServiceTests _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.FileProviderService.FileExists(newPathId) .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.RenameFile(path, newName); + Result result = _sut.RenameFile(path, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -1100,10 +1099,10 @@ public class FileServiceTests .Returns(Errors.FileSystemManagement.InvalidPath); // Act - ErrorOr result = _sut.RenameFile(pathId, newName); + Result result = _sut.RenameFile(pathId, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -1116,15 +1115,15 @@ public class FileServiceTests FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceNewFile); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) - .Returns(ErrorOrFactory.From(newPathId)); + .Returns(Result.From(newPathId)); _mockEnvironmentContext.FileProviderService.FileExists(newPathId) .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.RenameFile(pathId, newName); + Result result = _sut.RenameFile(pathId, newName); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -1139,10 +1138,10 @@ public class FileServiceTests .Returns(Result.Deleted); // Act - ErrorOr result = _sut.DeleteFile(path); + Result result = _sut.DeleteFile(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); } @@ -1153,10 +1152,10 @@ public class FileServiceTests string invalidPath = string.Empty; // Act - ErrorOr result = _sut.DeleteFile(invalidPath); + Result result = _sut.DeleteFile(invalidPath); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -1171,10 +1170,10 @@ public class FileServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.DeleteFile(path); + Result result = _sut.DeleteFile(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -1188,10 +1187,10 @@ public class FileServiceTests .Returns(Result.Deleted); // Act - ErrorOr result = _sut.DeleteFile(pathId); + Result result = _sut.DeleteFile(pathId); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); } @@ -1205,10 +1204,10 @@ public class FileServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = _sut.DeleteFile(pathId); + Result result = _sut.DeleteFile(pathId); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileTypeServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileTypeServiceTests.cs index 62c82bea..13382bc4 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileTypeServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileTypeServiceTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities.Fixtures; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; @@ -55,10 +55,10 @@ public class FileTypeServiceTests _mockFileSystemPermissionsService.CanAccessPath(file.Id, FileAccessMode.ReadContents).Returns(true); // Act - ErrorOr result = await sut.GetImageTypeAsync(file, CancellationToken.None); + Result result = await sut.GetImageTypeAsync(file, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(ImageType.PNG, result.Value); } @@ -74,10 +74,10 @@ public class FileTypeServiceTests _mockFileSystemPermissionsService.CanAccessPath(file.Id, FileAccessMode.ReadContents).Returns(false); // Act - ErrorOr result = await sut.GetImageTypeAsync(file, CancellationToken.None); + Result result = await sut.GetImageTypeAsync(file, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -93,10 +93,10 @@ public class FileTypeServiceTests _mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true); // Act - ErrorOr result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); + Result result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(ImageType.None, result.Value); } @@ -113,10 +113,10 @@ public class FileTypeServiceTests _mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true); // Act - ErrorOr result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); + Result result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(ImageType.SVG, result.Value); } @@ -135,10 +135,10 @@ public class FileTypeServiceTests _mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true); // Act - ErrorOr result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); + Result result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(ImageType.TGA, result.Value); } @@ -154,10 +154,10 @@ public class FileTypeServiceTests _mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true); // Act - ErrorOr result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); + Result result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(ImageType.None, result.Value); } @@ -185,10 +185,10 @@ public class FileTypeServiceTests _mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true); // Act - ErrorOr result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); + Result result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(ImageType.SVG, result.Value); } @@ -221,10 +221,10 @@ public class FileTypeServiceTests _mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true); // Act - ErrorOr result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); + Result result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(expectedType, result.Value); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/PathServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/PathServiceTests.cs index b2be92d7..24978918 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/PathServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/PathServiceTests.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; @@ -202,13 +202,13 @@ public class PathServiceTests string name = "SubDir"; FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); FileSystemPathId combinedPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\BaseDir\SubDir"); - _mockPathStrategy.CombinePath(pathId, name).Returns(ErrorOrFactory.From(combinedPathId)); + _mockPathStrategy.CombinePath(pathId, name).Returns(Result.From(combinedPathId)); // Act - ErrorOr result = _sut.CombinePath(path, name); + Result result = _sut.CombinePath(path, name); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(@"C:\BaseDir\SubDir", result.Value); _mockPathStrategy.Received(1).CombinePath(Arg.Is(id => id.Path == path), name); } @@ -221,10 +221,10 @@ public class PathServiceTests string name = "SubDir"; // Act - ErrorOr result = _sut.CombinePath(invalidPath, name); + Result result = _sut.CombinePath(invalidPath, name); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockPathStrategy.DidNotReceive().CombinePath(Arg.Any(), Arg.Any()); } @@ -239,10 +239,10 @@ public class PathServiceTests _mockPathStrategy.CombinePath(pathId, name).Returns(Errors.FileSystemManagement.InvalidPath); // Act - ErrorOr result = _sut.CombinePath(path, name); + Result result = _sut.CombinePath(path, name); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockPathStrategy.Received(1).CombinePath(Arg.Is(id => id.Path == path), name); } @@ -255,10 +255,10 @@ public class PathServiceTests string? name = null; // Act - ErrorOr result = _sut.CombinePath(path, name!); + Result result = _sut.CombinePath(path, name!); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockPathStrategy.DidNotReceive().CombinePath(Arg.Any(), Arg.Any()); } @@ -270,13 +270,13 @@ public class PathServiceTests string validPath = @"C:\ValidPath\SubDir"; FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(validPath); List expectedSegments = _pathSegmentFixture.CreateMany(); - _mockPathStrategy.ParsePath(pathId).Returns(ErrorOrFactory.From(expectedSegments.AsEnumerable())); + _mockPathStrategy.ParsePath(pathId).Returns(Result.From(expectedSegments.AsEnumerable())); // Act - ErrorOr> result = _sut.ParsePath(validPath); + Result> result = _sut.ParsePath(validPath); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(expectedSegments, result.Value); _mockPathStrategy.Received(1).ParsePath(Arg.Is(id => id.Path == validPath)); } @@ -288,10 +288,10 @@ public class PathServiceTests string invalidPath = string.Empty; // Act - ErrorOr> result = _sut.ParsePath(invalidPath); + Result> result = _sut.ParsePath(invalidPath); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockPathStrategy.DidNotReceive().ParsePath(Arg.Any()); } @@ -305,10 +305,10 @@ public class PathServiceTests _mockPathStrategy.ParsePath(pathId).Returns(Errors.FileSystemManagement.InvalidPath); // Act - ErrorOr> result = _sut.ParsePath(path); + Result> result = _sut.ParsePath(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockPathStrategy.Received(1).ParsePath(Arg.Is(id => id.Path == path)); } @@ -320,10 +320,10 @@ public class PathServiceTests string? nullPath = null; // Act - ErrorOr> result = _sut.ParsePath(nullPath!); + Result> result = _sut.ParsePath(nullPath!); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockPathStrategy.DidNotReceive().ParsePath(Arg.Any()); } @@ -335,13 +335,13 @@ public class PathServiceTests string validPath = @"C:\ValidPath\SubDir"; FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(validPath); List expectedSegments = _pathSegmentFixture.CreateMany(2); // Assuming parent path has 2 segments - _mockPathStrategy.GoUpOneLevel(pathId).Returns(ErrorOrFactory.From(expectedSegments.AsEnumerable())); + _mockPathStrategy.GoUpOneLevel(pathId).Returns(Result.From(expectedSegments.AsEnumerable())); // Act - ErrorOr> result = _sut.GoUpOneLevel(validPath); + Result> result = _sut.GoUpOneLevel(validPath); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(expectedSegments, result.Value); _mockPathStrategy.Received(1).GoUpOneLevel(Arg.Is(id => id.Path == validPath)); } @@ -353,13 +353,13 @@ public class PathServiceTests string rootPath = @"C:\"; FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(rootPath); List emptySegmentList = []; - _mockPathStrategy.GoUpOneLevel(pathId).Returns(ErrorOrFactory.From(emptySegmentList.AsEnumerable())); + _mockPathStrategy.GoUpOneLevel(pathId).Returns(Result.From(emptySegmentList.AsEnumerable())); // Act - ErrorOr> result = _sut.GoUpOneLevel(rootPath); + Result> result = _sut.GoUpOneLevel(rootPath); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Empty(result.Value); _mockPathStrategy.Received(1).GoUpOneLevel(Arg.Is(id => id.Path == rootPath)); } @@ -371,10 +371,10 @@ public class PathServiceTests string invalidPath = string.Empty; // Act - ErrorOr> result = _sut.GoUpOneLevel(invalidPath); + Result> result = _sut.GoUpOneLevel(invalidPath); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockPathStrategy.DidNotReceive().GoUpOneLevel(Arg.Any()); } @@ -388,10 +388,10 @@ public class PathServiceTests _mockPathStrategy.GoUpOneLevel(pathId).Returns(Errors.FileSystemManagement.InvalidPath); // Act - ErrorOr> result = _sut.GoUpOneLevel(path); + Result> result = _sut.GoUpOneLevel(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockPathStrategy.Received(1).GoUpOneLevel(Arg.Is(id => id.Path == path)); } @@ -403,10 +403,10 @@ public class PathServiceTests string? nullPath = null; // Act - ErrorOr> result = _sut.GoUpOneLevel(nullPath!); + Result> result = _sut.GoUpOneLevel(nullPath!); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockPathStrategy.DidNotReceive().GoUpOneLevel(Arg.Any()); } @@ -465,13 +465,13 @@ public class PathServiceTests string validPath = @"C:\ValidPath\SubDir"; FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(validPath); PathSegment expectedRootSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDirectory: false, isDrive: true); - _mockPathStrategy.GetPathRoot(pathId).Returns(ErrorOrFactory.From(expectedRootSegment)); + _mockPathStrategy.GetPathRoot(pathId).Returns(Result.From(expectedRootSegment)); // Act - ErrorOr result = _sut.GetPathRoot(validPath); + Result result = _sut.GetPathRoot(validPath); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(expectedRootSegment, result.Value); _mockPathStrategy.Received(1).GetPathRoot(Arg.Is(id => id.Path == validPath)); } @@ -483,10 +483,10 @@ public class PathServiceTests string invalidPath = string.Empty; // Act - ErrorOr result = _sut.GetPathRoot(invalidPath); + Result result = _sut.GetPathRoot(invalidPath); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockPathStrategy.DidNotReceive().GetPathRoot(Arg.Any()); } @@ -500,10 +500,10 @@ public class PathServiceTests _mockPathStrategy.GetPathRoot(pathId).Returns(Errors.FileSystemManagement.InvalidPath); // Act - ErrorOr result = _sut.GetPathRoot(path); + Result result = _sut.GetPathRoot(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockPathStrategy.Received(1).GetPathRoot(Arg.Is(id => id.Path == path)); } @@ -515,10 +515,10 @@ public class PathServiceTests string? nullPath = null; // Act - ErrorOr result = _sut.GetPathRoot(nullPath!); + Result result = _sut.GetPathRoot(nullPath!); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockPathStrategy.DidNotReceive().GetPathRoot(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs index 9612c280..46eb0c0b 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; 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.SharedKernel.Common.Enums.PhotoLibrary; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services.Fixtures; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; @@ -57,15 +57,15 @@ public class ThumbnailServiceTests } _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) - .Returns(ErrorOrFactory.From(ImageType.JPEG)); + .Returns(Result.From(ImageType.JPEG)); _mockEnvironmentContext.FileProviderService.GetFileAsync(pathId) - .Returns(ErrorOrFactory.From(imageBytes)); + .Returns(Result.From(imageBytes)); // Act - ErrorOr result = await _sut.GetThumbnailAsync(path, quality, CancellationToken.None); + Result result = await _sut.GetThumbnailAsync(path, quality, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(ImageType.JPEG, result.Value.Type); Assert.NotEmpty(result.Value.Bytes); } @@ -78,10 +78,10 @@ public class ThumbnailServiceTests int quality = 80; // Act - ErrorOr result = await _sut.GetThumbnailAsync(invalidPath, quality, CancellationToken.None); + Result result = await _sut.GetThumbnailAsync(invalidPath, quality, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -96,10 +96,10 @@ public class ThumbnailServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); + Result result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -111,13 +111,13 @@ public class ThumbnailServiceTests int quality = 80; _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) - .Returns(ErrorOrFactory.From(ImageType.None)); + .Returns(Result.From(ImageType.None)); // Act - ErrorOr result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); + Result result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Thumbnails.NoThumbnail, result.FirstError); } @@ -129,15 +129,15 @@ public class ThumbnailServiceTests int quality = 80; _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) - .Returns(ErrorOrFactory.From(ImageType.JPEG)); + .Returns(Result.From(ImageType.JPEG)); _mockEnvironmentContext.FileProviderService.GetFileAsync(pathId) .Returns(Errors.Permission.UnauthorizedAccess); // Act - ErrorOr result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); + Result result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } @@ -150,15 +150,15 @@ public class ThumbnailServiceTests int quality = 80; _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) - .Returns(ErrorOrFactory.From(imageType)); + .Returns(Result.From(imageType)); _mockEnvironmentContext.FileProviderService.GetFileAsync(pathId) - .Returns(ErrorOrFactory.From(imageBytes)); + .Returns(Result.From(imageBytes)); // Act - ErrorOr result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); + Result result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(imageType, result.Value.Type); Assert.NotEmpty(result.Value.Bytes); @@ -179,7 +179,7 @@ public class ThumbnailServiceTests cts.Cancel(); _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, cts.Token) - .Returns(Task.FromCanceled>(cts.Token)); + .Returns(Task.FromCanceled>(cts.Token)); // Act & Assert await Assert.ThrowsAsync(() => diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs index b16f2aae..16070fb1 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; @@ -233,10 +233,10 @@ public class UnixPathStrategyTests string name = "documents"; // Act - ErrorOr result = _sut.CombinePath(path, name); + Result result = _sut.CombinePath(path, name); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal("/home/user/documents/", result.Value.Path); } @@ -248,10 +248,10 @@ public class UnixPathStrategyTests string name = "documents"; // Act - ErrorOr result = _sut.CombinePath(path, name); + Result result = _sut.CombinePath(path, name); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal("/home/user/documents/", result.Value.Path); } @@ -263,10 +263,10 @@ public class UnixPathStrategyTests string name = "/documents"; // Act - ErrorOr result = _sut.CombinePath(path, name); + Result result = _sut.CombinePath(path, name); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal("/home/user/documents/", result.Value.Path); } @@ -278,10 +278,10 @@ public class UnixPathStrategyTests string name = ""; // Act - ErrorOr result = _sut.CombinePath(path, name); + Result result = _sut.CombinePath(path, name); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError); } @@ -293,10 +293,10 @@ public class UnixPathStrategyTests string name = null!; // Act - ErrorOr result = _sut.CombinePath(path, name); + Result result = _sut.CombinePath(path, name); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError); } @@ -308,10 +308,10 @@ public class UnixPathStrategyTests string name = "home"; // Act - ErrorOr result = _sut.CombinePath(path, name); + Result result = _sut.CombinePath(path, name); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal("/home/", result.Value.Path); } @@ -322,10 +322,10 @@ public class UnixPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents/file.txt"); // Act - ErrorOr> result = _sut.ParsePath(path); + Result> result = _sut.ParsePath(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(5, result.Value.Count()); Assert.Equal(_pathSegmentFixture.CreatePathSegment("/", false, true), result.Value.ElementAt(0)); Assert.Equal(_pathSegmentFixture.CreatePathSegment("home", true, false), result.Value.ElementAt(1)); @@ -341,10 +341,10 @@ public class UnixPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/"); // Act - ErrorOr> result = _sut.ParsePath(path); + Result> result = _sut.ParsePath(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(result.Value); Assert.Equal(_pathSegmentFixture.CreatePathSegment("/", false, true), result.Value.Single()); } @@ -356,10 +356,10 @@ public class UnixPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents/"); // Act - ErrorOr> result = _sut.ParsePath(path); + Result> result = _sut.ParsePath(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(4, result.Value.Count()); Assert.Equal(_pathSegmentFixture.CreatePathSegment("documents", true, false), result.Value.Last()); } @@ -371,10 +371,10 @@ public class UnixPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("home/user"); // Act - ErrorOr> result = _sut.ParsePath(path); + Result> result = _sut.ParsePath(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -385,10 +385,10 @@ public class UnixPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/file.with.dots.txt"); // Act - ErrorOr> result = _sut.ParsePath(path); + Result> result = _sut.ParsePath(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(4, result.Value.Count()); Assert.Equal(_pathSegmentFixture.CreatePathSegment("file.with.dots.txt", false, false), result.Value.Last()); } @@ -400,10 +400,10 @@ public class UnixPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents"); // Act - ErrorOr> result = _sut.GoUpOneLevel(path); + Result> result = _sut.GoUpOneLevel(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(3, result.Value.Count()); Assert.Equal(_pathSegmentFixture.CreatePathSegment("/", false, true), result.Value.ElementAt(0)); Assert.Equal(_pathSegmentFixture.CreatePathSegment("home", true, false), result.Value.ElementAt(1)); @@ -417,10 +417,10 @@ public class UnixPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/"); // Act - ErrorOr> result = _sut.GoUpOneLevel(path); + Result> result = _sut.GoUpOneLevel(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.CannotNavigateUp, result.FirstError); } @@ -431,10 +431,10 @@ public class UnixPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/"); // Act - ErrorOr> result = _sut.GoUpOneLevel(path); + Result> result = _sut.GoUpOneLevel(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); Assert.Equal(_pathSegmentFixture.CreatePathSegment("/", false, true), result.Value.ElementAt(0)); Assert.Equal(_pathSegmentFixture.CreatePathSegment("home", true, false), result.Value.ElementAt(1)); @@ -447,10 +447,10 @@ public class UnixPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("invalid/path"); // Act - ErrorOr> result = _sut.GoUpOneLevel(path); + Result> result = _sut.GoUpOneLevel(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -461,10 +461,10 @@ public class UnixPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home"); // Act - ErrorOr> result = _sut.GoUpOneLevel(path); + Result> result = _sut.GoUpOneLevel(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(result.Value); Assert.Equal(_pathSegmentFixture.CreatePathSegment("/", false, true), result.Value.Single()); } @@ -516,10 +516,10 @@ public class UnixPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents"); // Act - ErrorOr result = _sut.GetPathRoot(path); + Result result = _sut.GetPathRoot(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(_pathSegmentFixture.CreatePathSegment("/", false, true), result.Value); } @@ -530,10 +530,10 @@ public class UnixPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/"); // Act - ErrorOr result = _sut.GetPathRoot(path); + Result result = _sut.GetPathRoot(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(_pathSegmentFixture.CreatePathSegment("/", false, true), result.Value); } @@ -544,10 +544,10 @@ public class UnixPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("home/user"); // Act - ErrorOr result = _sut.GetPathRoot(path); + Result result = _sut.GetPathRoot(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs index 79fb7737..4c163e71 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; @@ -276,10 +276,10 @@ public class WindowsPathStrategyTests string name = "Documents"; // Act - ErrorOr result = _sut.CombinePath(path, name); + Result result = _sut.CombinePath(path, name); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(@"C:\Users\User\Documents\", result.Value.Path); } @@ -291,10 +291,10 @@ public class WindowsPathStrategyTests string name = "Documents"; // Act - ErrorOr result = _sut.CombinePath(path, name); + Result result = _sut.CombinePath(path, name); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(@"C:\Users\User\Documents\", result.Value.Path); } @@ -306,10 +306,10 @@ public class WindowsPathStrategyTests string name = @"\Documents"; // Act - ErrorOr result = _sut.CombinePath(path, name); + Result result = _sut.CombinePath(path, name); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(@"C:\Users\User\Documents\", result.Value.Path); } @@ -321,10 +321,10 @@ public class WindowsPathStrategyTests string name = null!; // Act - ErrorOr result = _sut.CombinePath(path, name); + Result result = _sut.CombinePath(path, name); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError); } @@ -336,10 +336,10 @@ public class WindowsPathStrategyTests string name = "Users"; // Act - ErrorOr result = _sut.CombinePath(path, name); + Result result = _sut.CombinePath(path, name); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(@"C:\Users\", result.Value.Path); } @@ -351,10 +351,10 @@ public class WindowsPathStrategyTests string name = "folder"; // Act - ErrorOr result = _sut.CombinePath(path, name); + Result result = _sut.CombinePath(path, name); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(@"\\server\share\folder\", result.Value.Path); } @@ -365,10 +365,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents\file.txt"); // Act - ErrorOr> result = _sut.ParsePath(path); + Result> result = _sut.ParsePath(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(5, result.Value.Count()); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("C:", false, true), result.Value.ElementAt(0)); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("Users", true, false), result.Value.ElementAt(1)); @@ -384,10 +384,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\"); // Act - ErrorOr> result = _sut.ParsePath(path); + Result> result = _sut.ParsePath(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(result.Value); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("C:", false, true), result.Value.Single()); } @@ -399,10 +399,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents\"); // Act - ErrorOr> result = _sut.ParsePath(path); + Result> result = _sut.ParsePath(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(4, result.Value.Count()); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("Documents", true, false), result.Value.Last()); } @@ -414,10 +414,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"Users\User"); // Act - ErrorOr> result = _sut.ParsePath(path); + Result> result = _sut.ParsePath(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -428,10 +428,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\file.with.dots.txt"); // Act - ErrorOr> result = _sut.ParsePath(path); + Result> result = _sut.ParsePath(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(4, result.Value.Count()); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("file.with.dots.txt", false, false), result.Value.Last()); } @@ -443,10 +443,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder\file.txt"); // Act - ErrorOr> result = _sut.ParsePath(path); + Result> result = _sut.ParsePath(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(5, result.Value.Count()); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment(@"\\", false, true), result.Value.ElementAt(0)); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("server", true, false), result.Value.ElementAt(1)); @@ -462,10 +462,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents"); // Act - ErrorOr> result = _sut.GoUpOneLevel(path); + Result> result = _sut.GoUpOneLevel(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(3, result.Value.Count()); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("C:", false, true), result.Value.ElementAt(0)); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("Users", true, false), result.Value.ElementAt(1)); @@ -479,10 +479,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\"); // Act - ErrorOr> result = _sut.GoUpOneLevel(path); + Result> result = _sut.GoUpOneLevel(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.CannotNavigateUp, result.FirstError); } @@ -493,10 +493,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\"); // Act - ErrorOr> result = _sut.GoUpOneLevel(path); + Result> result = _sut.GoUpOneLevel(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("C:", false, true), result.Value.ElementAt(0)); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("Users", true, false), result.Value.ElementAt(1)); @@ -509,10 +509,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"invalid\path"); // Act - ErrorOr> result = _sut.GoUpOneLevel(path); + Result> result = _sut.GoUpOneLevel(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -523,10 +523,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users"); // Act - ErrorOr> result = _sut.GoUpOneLevel(path); + Result> result = _sut.GoUpOneLevel(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Single(result.Value); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("C:", false, true), result.Value.Single()); } @@ -538,10 +538,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder\subfolder"); // Act - ErrorOr> result = _sut.GoUpOneLevel(path); + Result> result = _sut.GoUpOneLevel(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(4, result.Value.Count()); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment(@"\\", false, true), result.Value.ElementAt(0)); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("server", true, false), result.Value.ElementAt(1)); @@ -556,10 +556,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share"); // Act - ErrorOr> result = _sut.GoUpOneLevel(path); + Result> result = _sut.GoUpOneLevel(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.CannotNavigateUp, result.FirstError); } @@ -570,10 +570,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder"); // Act - ErrorOr> result = _sut.GoUpOneLevel(path); + Result> result = _sut.GoUpOneLevel(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(3, result.Value.Count()); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment(@"\\", false, true), result.Value.ElementAt(0)); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("server", true, false), result.Value.ElementAt(1)); @@ -587,10 +587,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\"); // Act - ErrorOr> result = _sut.GoUpOneLevel(path); + Result> result = _sut.GoUpOneLevel(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.CannotNavigateUp, result.FirstError); } @@ -634,10 +634,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents"); // Act - ErrorOr result = _sut.GetPathRoot(path); + Result result = _sut.GetPathRoot(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("C:\\", true, true), result.Value); } @@ -648,10 +648,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\"); // Act - ErrorOr result = _sut.GetPathRoot(path); + Result result = _sut.GetPathRoot(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("C:\\", true, true), result.Value); } @@ -662,10 +662,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"InvalidFolder"); // Act - ErrorOr result = _sut.GetPathRoot(path); + Result result = _sut.GetPathRoot(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -676,10 +676,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder"); // Act - ErrorOr result = _sut.GetPathRoot(path); + Result result = _sut.GetPathRoot(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment(@"\\server\share\", true, false), result.Value); } @@ -690,10 +690,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\"); // Act - ErrorOr result = _sut.GetPathRoot(path); + Result result = _sut.GetPathRoot(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -704,10 +704,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server"); // Act - ErrorOr result = _sut.GetPathRoot(path); + Result result = _sut.GetPathRoot(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -718,10 +718,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"InvalidPath"); // Act - ErrorOr result = _sut.GetPathRoot(path); + Result result = _sut.GetPathRoot(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -732,10 +732,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\"); // Act - ErrorOr result = _sut.GetPathRoot(path); + Result result = _sut.GetPathRoot(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } @@ -746,10 +746,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share"); // Act - ErrorOr result = _sut.GetPathRoot(path); + Result result = _sut.GetPathRoot(path); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equivalent(_pathSegmentFixture.CreatePathSegment(@"\\server\share\", true, false), result.Value); } @@ -760,10 +760,10 @@ public class WindowsPathStrategyTests FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"invalid\path"); // Act - ErrorOr result = _sut.GetPathRoot(path); + Result result = _sut.GetPathRoot(path); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdTests.cs index afc31cf4..d3134664 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdTests.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using System.Diagnostics.CodeAnalysis; @@ -31,10 +31,10 @@ public class FileSystemPathIdTests string validPath = @"C:\TestDir\file.txt"; // Act - ErrorOr result = FileSystemPathId.Create(validPath); + Result result = FileSystemPathId.Create(validPath); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(validPath, result.Value.Path); } @@ -45,10 +45,10 @@ public class FileSystemPathIdTests public void Create_WithInvalidPath_ShouldReturnError(string? invalidPath) { // Act - ErrorOr result = FileSystemPathId.Create(invalidPath!); + Result result = FileSystemPathId.Create(invalidPath!); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs index 904ed1bc..54d2cc01 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; @@ -33,9 +33,9 @@ public class FileSystemPathIdFixture { path ??= _faker.System.FilePath(); - ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); + Result fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) + if (fileSystemPathIdResult.IsFailure) throw new InvalidOperationException("Failed to create FileSystemPathId: " + string.Join(", ", fileSystemPathIdResult.Errors)); return fileSystemPathIdResult.Value; } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs index 76b465c9..1d6fc891 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; @@ -39,9 +39,9 @@ public class PathSegmentFixture isDirectory ??= true; isDrive ??= false; - ErrorOr pathResult = PathSegment.Create(name, isDirectory.Value, isDrive.Value); + Result pathResult = PathSegment.Create(name, isDirectory.Value, isDrive.Value); - if (pathResult.IsError) + if (pathResult.IsFailure) throw new InvalidOperationException("Failed to create PathSegment: " + string.Join(", ", pathResult.Errors)); return pathResult.Value; } @@ -53,6 +53,6 @@ public class PathSegmentFixture /// The created list. public List CreateMany(int count = 3) { - return Enumerable.Range(0, count).Select(_ => CreatePathSegment()).ToList(); + return [.. Enumerable.Range(0, count).Select(_ => CreatePathSegment())]; } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs index 3ba05f6c..29f6d603 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using ErrorOr; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; @@ -58,10 +57,10 @@ public class StreamInfoFixture sampleRate ??= Optional.FromNullable(_faker.Random.Bool() ? (int?)_faker.Random.Number(8000, 192000) : null); channels ??= Optional.FromNullable(_faker.Random.Bool() ? (int?)_faker.Random.Number(1, 8) : null); - ErrorOr streamInfoResult = StreamInfo.Create( + Result streamInfoResult = StreamInfo.Create( streamId, mimeType, bitrate.Value, codec, resolution.Value, frameRate.Value, sampleRate.Value, channels.Value); - if (streamInfoResult.IsError) + if (streamInfoResult.IsFailure) throw new InvalidOperationException("Failed to create StreamInfo: " + string.Join(", ", streamInfoResult.Errors)); return streamInfoResult.Value; } @@ -73,6 +72,6 @@ public class StreamInfoFixture /// The created list. public List CreateMany(int count = 3) { - return Enumerable.Range(0, count).Select(_ => CreateStreamInfo()).ToList(); + return [.. Enumerable.Range(0, count).Select(_ => CreateStreamInfo())]; } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/PathSegmentTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/PathSegmentTests.cs index 8fa78ab6..e606e493 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/PathSegmentTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/PathSegmentTests.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using System.Diagnostics.CodeAnalysis; @@ -33,10 +33,10 @@ public class PathSegmentTests bool isDrive = false; // Act - ErrorOr result = PathSegment.Create(name, isDirectory, isDrive); + Result result = PathSegment.Create(name, isDirectory, isDrive); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(name, result.Value.Name); Assert.Equal(isDirectory, result.Value.IsDirectory); Assert.Equal(isDrive, result.Value.IsDrive); @@ -49,10 +49,10 @@ public class PathSegmentTests public void Create_WithInvalidName_ShouldReturnError(string? invalidName) { // Act - ErrorOr result = PathSegment.Create(invalidName!, true, false); + Result result = PathSegment.Create(invalidName!, true, false); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/StreamInfoTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/StreamInfoTests.cs index ae46f320..a2eba0e0 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/StreamInfoTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/StreamInfoTests.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; @@ -40,10 +39,10 @@ public class StreamInfoTests Optional channels = Optional.Some(2); // Act - ErrorOr result = StreamInfo.Create(streamId, mimeType, bitrate, codec, resolution, frameRate, sampleRate, channels); + Result result = StreamInfo.Create(streamId, mimeType, bitrate, codec, resolution, frameRate, sampleRate, channels); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(streamId, result.Value.StreamId); Assert.Equal(mimeType, result.Value.MimeType); Assert.Equal(bitrate, result.Value.Bitrate); @@ -64,10 +63,10 @@ public class StreamInfoTests string codec = "h264"; // Act - ErrorOr result = StreamInfo.Create(streamId!, mimeType, bitrate, codec, Optional.None(), Optional.None(), Optional.None(), Optional.None()); + Result result = StreamInfo.Create(streamId!, mimeType, bitrate, codec, Optional.None(), Optional.None(), Optional.None(), Optional.None()); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.StreamIdCannotBeEmpty, result.FirstError); } @@ -81,10 +80,10 @@ public class StreamInfoTests string? codec = null; // Act - ErrorOr result = StreamInfo.Create(streamId, mimeType, bitrate, codec!, Optional.None(), Optional.None(), Optional.None(), Optional.None()); + Result result = StreamInfo.Create(streamId, mimeType, bitrate, codec!, Optional.None(), Optional.None(), Optional.None(), Optional.None()); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.CodecCannotBeEmpty, result.FirstError); } @@ -98,10 +97,10 @@ public class StreamInfoTests string codec = "h264"; // Act - ErrorOr result = StreamInfo.Create(streamId, mimeType, bitrate, codec, Optional.None(), Optional.None(), Optional.None(), Optional.None()); + Result result = StreamInfo.Create(streamId, mimeType, bitrate, codec, Optional.None(), Optional.None(), Optional.None(), Optional.None()); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.BitrateMustBeAPositiveNumber, result.FirstError); } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/ValidationOptionsTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/ValidationOptionsTests.cs index b331532f..05a9f49b 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/ValidationOptionsTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/ValidationOptionsTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; using Lumina.Infrastructure.Common.Validation; using Lumina.Infrastructure.UnitTests.Common.Validation.Fixtures; using Microsoft.Extensions.Options; diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs index 42e906a3..d41b6411 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Infrastructure.Common.Errors; using Lumina.Infrastructure.Common.Models.DTO.Configuration; using Lumina.Infrastructure.Common.Validators; diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs index 13eca23c..cf80f2e2 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Infrastructure.Common.Errors; using Lumina.Infrastructure.Common.Models.DTO.Configuration; using Lumina.Infrastructure.Common.Validators; diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsDtoValidatorTests.cs index b9291c59..aae59a10 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsDtoValidatorTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Infrastructure.Common.Errors; using Lumina.Infrastructure.Common.Models.DTO.Configuration; using Lumina.Infrastructure.Common.Validators; diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsDtoValidatorTests.cs index 03af6439..01b14622 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsDtoValidatorTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Infrastructure.Common.Errors; using Lumina.Infrastructure.Common.Models.DTO.Configuration; using Lumina.Infrastructure.Common.Validators; diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsDtoValidatorTests.cs index 35d0108d..d7c19f9f 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsDtoValidatorTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Domain.Common.Primitives; using Lumina.Infrastructure.Common.Errors; using Lumina.Infrastructure.Common.Validators; using System.Collections.Generic; diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs index 4cbc3807..33278568 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; -using Lumina.Domain.SharedKernel.Common.Errors; using Lumina.Infrastructure.Core.Authorization; using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory; using Lumina.Infrastructure.UnitTests.Core.Authorization.Fixtures; @@ -52,7 +52,7 @@ public class AuthorizationServiceTests // Arrange Guid userId = Guid.NewGuid(); _mockUserRepository.GetByIdAsync(userId, Arg.Any()) - .Returns(ErrorOrFactory.From(null)); + .Returns(Result.From(null)); // Act bool result = await _sut.HasPermissionAsync(userId, AuthorizationPermission.CanViewUsers, CancellationToken.None); @@ -87,7 +87,7 @@ public class AuthorizationServiceTests directPermissions: [AuthorizationPermission.CanViewUsers]); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); // Act bool result = await _sut.HasPermissionAsync(user.Id, AuthorizationPermission.CanViewUsers, CancellationToken.None); @@ -110,7 +110,7 @@ public class AuthorizationServiceTests rolePermissions: rolePermissions); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); // Act bool result = await _sut.HasPermissionAsync(user.Id, AuthorizationPermission.CanViewUsers, CancellationToken.None); @@ -127,7 +127,7 @@ public class AuthorizationServiceTests UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); // Act bool result = await _sut.HasPermissionAsync(user.Id, AuthorizationPermission.CanViewUsers, CancellationToken.None); @@ -145,7 +145,7 @@ public class AuthorizationServiceTests directPermissions: [AuthorizationPermission.CanDeleteUsers]); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); // Act bool result = await _sut.HasPermissionAsync(user.Id, AuthorizationPermission.CanViewUsers, CancellationToken.None); @@ -169,7 +169,7 @@ public class AuthorizationServiceTests rolePermissions: rolePermissions); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); // Act bool result = await _sut.HasPermissionAsync(user.Id, AuthorizationPermission.CanViewUsers, CancellationToken.None); @@ -185,7 +185,7 @@ public class AuthorizationServiceTests // Arrange Guid userId = Guid.NewGuid(); _mockUserRepository.GetByIdAsync(userId, Arg.Any()) - .Returns(ErrorOrFactory.From(null)); + .Returns(Result.From(null)); // Act bool result = await _sut.IsInRoleAsync(userId, "Admin", CancellationToken.None); @@ -225,7 +225,7 @@ public class AuthorizationServiceTests rolePermissions: rolePermissions); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); // Act bool result = await _sut.IsInRoleAsync(user.Id, "Admin", CancellationToken.None); @@ -248,7 +248,7 @@ public class AuthorizationServiceTests rolePermissions: rolePermissions); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); // Act bool result = await _sut.IsInRoleAsync(user.Id, "Admin", CancellationToken.None); @@ -265,7 +265,7 @@ public class AuthorizationServiceTests UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); // Act bool result = await _sut.IsInRoleAsync(user.Id, "Admin", CancellationToken.None); @@ -402,13 +402,13 @@ public class AuthorizationServiceTests // Arrange Guid userId = Guid.NewGuid(); _mockUserRepository.GetByIdAsync(userId, Arg.Any()) - .Returns(ErrorOrFactory.From(null)); + .Returns(Result.From(null)); // Act - ErrorOr result = await _sut.GetUserAuthorizationAsync(userId, CancellationToken.None); + Result result = await _sut.GetUserAuthorizationAsync(userId, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(Errors.Users.UserDoesNotExist, result.FirstError); await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any()); } @@ -423,10 +423,10 @@ public class AuthorizationServiceTests .Returns(error); // Act - ErrorOr result = await _sut.GetUserAuthorizationAsync(userId, CancellationToken.None); + Result result = await _sut.GetUserAuthorizationAsync(userId, CancellationToken.None); // Assert - Assert.True(result.IsError); + Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any()); } @@ -437,13 +437,13 @@ public class AuthorizationServiceTests // Arrange UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); // Act - ErrorOr result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None); + Result result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(user.Id, result.Value.UserId); Assert.Null(result.Value.Role); Assert.Empty(result.Value.Permissions); @@ -462,13 +462,13 @@ public class AuthorizationServiceTests ]); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); // Act - ErrorOr result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None); + Result result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(user.Id, result.Value.UserId); Assert.Null(result.Value.Role); Assert.Equal([AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanDeleteUsers], @@ -492,13 +492,13 @@ public class AuthorizationServiceTests rolePermissions: rolePermissions); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); // Act - ErrorOr result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None); + Result result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(user.Id, result.Value.UserId); Assert.Equal("Admin", result.Value.Role); Assert.Equal([AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanDeleteUsers], @@ -523,13 +523,13 @@ public class AuthorizationServiceTests rolePermissions: rolePermissions); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); + .Returns(Result.From(user)); // Act - ErrorOr result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None); + Result result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None); // Assert - Assert.False(result.IsError); + Assert.False(result.IsFailure); Assert.Equal(user.Id, result.Value.UserId); Assert.Equal("Admin", result.Value.Role); Assert.Equivalent( diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointTests.cs index fec666db..e9a68cbe 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Permissions.GetPermissions; using Microsoft.AspNetCore.Http; @@ -25,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Admin.Authorization.P [ExcludeFromCodeCoverage] public class GetPermissionsEndpointTests { - private readonly IQueryHandler>> _mockHandler; + private readonly IQueryHandler>> _mockHandler; private readonly GetPermissionsEndpoint _sut; /// @@ -33,7 +33,7 @@ public class GetPermissionsEndpointTests /// public GetPermissionsEndpointTests() { - _mockHandler = Substitute.For>>>(); + _mockHandler = Substitute.For>>>(); _sut = Factory.Create(_mockHandler); } @@ -49,7 +49,7 @@ public class GetPermissionsEndpointTests new(Guid.NewGuid(), AuthorizationPermission.CanRegisterUsers) ]; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); @@ -91,7 +91,7 @@ public class GetPermissionsEndpointTests CancellationToken cancellationToken = CancellationToken.None; IEnumerable response = []; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(response)); + .Returns(Result.From(response)); // Act await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); @@ -116,7 +116,7 @@ public class GetPermissionsEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(Enumerable.Empty()); + return Result.From(Enumerable.Empty()); }, info.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs index b1cc0e5f..7068b692 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; using Lumina.Contracts.DTO.Authentication; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.AddRole; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; @@ -24,7 +24,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Admin.Authorization.R [ExcludeFromCodeCoverage] public class AddRoleEndpointTests { - private readonly ICommandHandler> _mockHandler; + private readonly ICommandHandler> _mockHandler; private readonly AddRoleEndpoint _sut; /// @@ -32,7 +32,7 @@ public class AddRoleEndpointTests /// public AddRoleEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); } @@ -44,7 +44,7 @@ public class AddRoleEndpointTests CancellationToken cancellationToken = CancellationToken.None; RolePermissionsResponse expectedResponse = new(new RoleDto(Guid.NewGuid(), "Admin"), []); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -87,7 +87,7 @@ public class AddRoleEndpointTests AddRoleRequest request = new("Admin", [Guid.NewGuid()]); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(new RolePermissionsResponse(new RoleDto(Guid.NewGuid(), "Admin"), []))); + .Returns(Result.From(new RolePermissionsResponse(new RoleDto(Guid.NewGuid(), "Admin"), []))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -114,7 +114,7 @@ public class AddRoleEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new RolePermissionsResponse(new RoleDto(Guid.NewGuid(), "Admin"), [])); + return Result.From(new RolePermissionsResponse(new RoleDto(Guid.NewGuid(), "Admin"), [])); }, info.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs index 20399910..4f8be6da 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; using Lumina.Contracts.Requests.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; @@ -21,7 +21,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Admin.Authorization.R [ExcludeFromCodeCoverage] public class DeleteRoleEndpointTests { - private readonly ICommandHandler> _mockHandler; + private readonly ICommandHandler> _mockHandler; private readonly DeleteRoleEndpoint _sut; /// @@ -29,7 +29,7 @@ public class DeleteRoleEndpointTests /// public DeleteRoleEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); } @@ -40,7 +40,7 @@ public class DeleteRoleEndpointTests DeleteRoleRequest request = new(Guid.NewGuid()); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(Result.Deleted)); + .Returns(Result.From(Result.Deleted)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -83,7 +83,7 @@ public class DeleteRoleEndpointTests DeleteRoleRequest request = new(roleId); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(Result.Deleted)); + .Returns(Result.From(Result.Deleted)); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -108,7 +108,7 @@ public class DeleteRoleEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(Result.Deleted); + return Result.From(Result.Deleted); }, info.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs index ed31a762..a6804307 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; using Lumina.Contracts.DTO.Authentication; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions; using Microsoft.AspNetCore.Http; @@ -24,7 +24,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Admin.Authorization.R [ExcludeFromCodeCoverage] public class GetRolePermissionsEndpointTests { - private readonly IQueryHandler> _mockHandler; + private readonly IQueryHandler> _mockHandler; private readonly GetRolePermissionsEndpoint _sut; /// @@ -32,7 +32,7 @@ public class GetRolePermissionsEndpointTests /// public GetRolePermissionsEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); } @@ -47,7 +47,7 @@ public class GetRolePermissionsEndpointTests [new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanViewUsers)] ); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -91,7 +91,7 @@ public class GetRolePermissionsEndpointTests GetRolePermissionsRequest request = new(roleId); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(new RolePermissionsResponse( + .Returns(Result.From(new RolePermissionsResponse( new RoleDto(Guid.NewGuid(), "Admin"), [] ))); @@ -119,7 +119,7 @@ public class GetRolePermissionsEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new RolePermissionsResponse( + return Result.From(new RolePermissionsResponse( new RoleDto(Guid.NewGuid(), "Admin"), [] )); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs index 4d4059db..895adfd5 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.GetRoles; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; @@ -23,7 +23,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Admin.Authorization.R [ExcludeFromCodeCoverage] public class GetRolesEndpointTests { - private readonly IQueryHandler>> _mockHandler; + private readonly IQueryHandler>> _mockHandler; private readonly GetRolesEndpoint _sut; /// @@ -31,7 +31,7 @@ public class GetRolesEndpointTests /// public GetRolesEndpointTests() { - _mockHandler = Substitute.For>>>(); + _mockHandler = Substitute.For>>>(); _sut = Factory.Create(_mockHandler); } @@ -45,7 +45,7 @@ public class GetRolesEndpointTests new RoleResponse(Guid.NewGuid(), "Admin") ]; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); @@ -86,7 +86,7 @@ public class GetRolesEndpointTests // Arrange CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(new List + .Returns(Result.From(new List { new(Guid.NewGuid(), "Admin") } as IEnumerable)); @@ -114,7 +114,7 @@ public class GetRolesEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new List() as IEnumerable); + return Result.From(new List() as IEnumerable); }, info.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs index e36bc26c..9f32b1d3 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs @@ -1,17 +1,16 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; using Lumina.Contracts.DTO.Authentication; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.UpdateRole; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; @@ -26,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Admin.Authorization.R [ExcludeFromCodeCoverage] public class UpdateRoleEndpointTests { - private readonly ICommandHandler> _mockHandler; + private readonly ICommandHandler> _mockHandler; private readonly UpdateRoleEndpoint _sut; /// @@ -34,7 +33,7 @@ public class UpdateRoleEndpointTests /// public UpdateRoleEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); } @@ -49,7 +48,7 @@ public class UpdateRoleEndpointTests [new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanViewUsers)] ); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -92,7 +91,7 @@ public class UpdateRoleEndpointTests UpdateRoleRequest request = new(Guid.NewGuid(), "UpdatedAdmin", [Guid.NewGuid()]); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(new RolePermissionsResponse( + .Returns(Result.From(new RolePermissionsResponse( new RoleDto(Guid.NewGuid(), "UpdatedAdmin"), [] ))); @@ -123,7 +122,7 @@ public class UpdateRoleEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new RolePermissionsResponse( + return Result.From(new RolePermissionsResponse( new RoleDto(Guid.NewGuid(), "UpdatedAdmin"), [] )); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs index 376ee6f5..7443689f 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.Common.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/Fixtures/BaseEndpointFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/Fixtures/BaseEndpointFixture.cs index a3081e5f..a256b0bc 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/Fixtures/BaseEndpointFixture.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/Fixtures/BaseEndpointFixture.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs index d0403a76..b859460c 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; using Lumina.Contracts.Requests.FileSystemManagement.Directories; using Lumina.Contracts.Responses.FileSystemManagement.Directories; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; @@ -28,7 +28,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. public class GetDirectoriesEndpointTests { private readonly IFixture _fixture; - private readonly IQueryHandler>> _mockHandler; + private readonly IQueryHandler>> _mockHandler; private readonly GetDirectoriesEndpoint _sut; /// @@ -37,7 +37,7 @@ public class GetDirectoriesEndpointTests public GetDirectoriesEndpointTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _mockHandler = Substitute.For>>>(); + _mockHandler = Substitute.For>>>(); _sut = Factory.Create(_mockHandler); } @@ -47,9 +47,9 @@ public class GetDirectoriesEndpointTests // Arrange GetDirectoriesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - List expectedResponses = _fixture.CreateMany(3).ToList(); + List expectedResponses = [.. _fixture.CreateMany(3)]; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + .Returns(Result.From(expectedResponses.AsEnumerable())); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -118,7 +118,7 @@ public class GetDirectoriesEndpointTests GetDirectoriesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); + .Returns(Result.From(Enumerable.Empty())); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -144,7 +144,7 @@ public class GetDirectoriesEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(_fixture.CreateMany(3).AsEnumerable()); + return Result.From(_fixture.CreateMany(3).AsEnumerable()); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs index 28c9223b..1e0e0a67 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.GetDrives; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; @@ -25,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class GetDrivesEndpointTests { - private readonly IQueryHandler>> _mockHandler; + private readonly IQueryHandler>> _mockHandler; private readonly GetDrivesEndpoint _sut; private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; @@ -34,7 +34,7 @@ public class GetDrivesEndpointTests /// public GetDrivesEndpointTests() { - _mockHandler = Substitute.For>>>(); + _mockHandler = Substitute.For>>>(); _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); _sut = Factory.Create(_mockHandler); } @@ -46,7 +46,7 @@ public class GetDrivesEndpointTests CancellationToken cancellationToken = CancellationToken.None; List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + .Returns(Result.From(expectedResponses.AsEnumerable())); // Act IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); @@ -87,7 +87,7 @@ public class GetDrivesEndpointTests // Arrange CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); + .Returns(Result.From(Enumerable.Empty())); // Act await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); @@ -110,7 +110,7 @@ public class GetDrivesEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1).AsEnumerable()); + return Result.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1).AsEnumerable()); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs index 0e207562..1351a284 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; using Lumina.Contracts.Requests.FileSystemManagement.Files; using Lumina.Contracts.Responses.FileSystemManagement.Files; -using Lumina.Presentation.Api.Common.Http; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetFiles; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; @@ -16,7 +15,6 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Reflection; using System.Threading; using System.Threading.Tasks; #endregion @@ -30,7 +28,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. public class GetFilesEndpointTests { private readonly IFixture _fixture; - private readonly IQueryHandler>> _mockHandler; + private readonly IQueryHandler>> _mockHandler; private readonly GetFilesEndpoint _sut; /// @@ -39,7 +37,7 @@ public class GetFilesEndpointTests public GetFilesEndpointTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _mockHandler = Substitute.For>>>(); + _mockHandler = Substitute.For>>>(); _sut = Factory.Create(_mockHandler); } @@ -49,9 +47,9 @@ public class GetFilesEndpointTests // Arrange GetFilesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - List expectedResponses = _fixture.CreateMany(3).ToList(); + List expectedResponses = [.. _fixture.CreateMany(3)]; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + .Returns(Result.From(expectedResponses.AsEnumerable())); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -120,7 +118,7 @@ public class GetFilesEndpointTests GetFilesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); + .Returns(Result.From(Enumerable.Empty())); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -147,7 +145,7 @@ public class GetFilesEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(_fixture.CreateMany(3).AsEnumerable()); + return Result.From(_fixture.CreateMany(3).AsEnumerable()); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs index 455ce8be..69ca18ed 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; using Lumina.Contracts.Requests.FileSystemManagement.Files; using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; @@ -29,7 +29,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. public class GetTreeFilesEndpointTests { private readonly IFixture _fixture; - private readonly IQueryHandler>> _mockHandler; + private readonly IQueryHandler>> _mockHandler; private readonly GetTreeFilesEndpoint _sut; private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; @@ -39,7 +39,7 @@ public class GetTreeFilesEndpointTests public GetTreeFilesEndpointTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _mockHandler = Substitute.For>>>(); + _mockHandler = Substitute.For>>>(); _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); _sut = Factory.Create(_mockHandler); } @@ -52,7 +52,7 @@ public class GetTreeFilesEndpointTests CancellationToken cancellationToken = CancellationToken.None; List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + .Returns(Result.From(expectedResponses.AsEnumerable())); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -121,7 +121,7 @@ public class GetTreeFilesEndpointTests GetTreeFilesRequest request = _fixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); + .Returns(Result.From(Enumerable.Empty())); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -148,7 +148,7 @@ public class GetTreeFilesEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5).AsEnumerable()); + return Result.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5).AsEnumerable()); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs index 86ade8a8..da53bac9 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; @@ -24,7 +24,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class CheckPathExistsEndpointTests { - private readonly IQueryHandler> _mockHandler; + private readonly IQueryHandler> _mockHandler; private readonly CheckPathExistsEndpoint _sut; private readonly CheckPathExistsRequestFixture _checkPathExistsRequestFixture; @@ -33,7 +33,7 @@ public class CheckPathExistsEndpointTests /// public CheckPathExistsEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = Factory.Create(_mockHandler); _checkPathExistsRequestFixture = new CheckPathExistsRequestFixture(); } @@ -89,7 +89,7 @@ public class CheckPathExistsEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new PathExistsResponse(true)); + return Result.From(new PathExistsResponse(true)); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs index cbc83e0c..dbee370b 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CombinePath; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; @@ -23,7 +23,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class CombinePathEndpointTests { - private readonly ICommandHandler> _mockHandler; + private readonly ICommandHandler> _mockHandler; private readonly CombinePathEndpoint _sut; private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; private readonly CombinePathRequestFixture _combinePathRequestFixture; @@ -33,7 +33,7 @@ public class CombinePathEndpointTests /// public CombinePathEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); _pathSegmentResponseFixture = new PathSegmentResponseFixture(); _combinePathRequestFixture = new CombinePathRequestFixture(); @@ -47,7 +47,7 @@ public class CombinePathEndpointTests CancellationToken cancellationToken = CancellationToken.None; PathSegmentResponse expectedResponse = _pathSegmentResponseFixture.Create(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -116,7 +116,7 @@ public class CombinePathEndpointTests CombinePathRequest request = _combinePathRequestFixture.Create("C:\\Users", "TestUser"); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.Create())); + .Returns(Result.From(_pathSegmentResponseFixture.Create())); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -142,7 +142,7 @@ public class CombinePathEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(_pathSegmentResponseFixture.Create()); + return Result.From(_pathSegmentResponseFixture.Create()); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs index ec7c18f5..3bf48f13 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathParent; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; @@ -26,7 +26,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class GetPathParentEndpointTests { - private readonly IQueryHandler>> _mockHandler; + private readonly IQueryHandler>> _mockHandler; private readonly GetPathParentEndpoint _sut; private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; private readonly GetPathParentRequestFixture _getPathParentRequestFixture; @@ -36,7 +36,7 @@ public class GetPathParentEndpointTests /// public GetPathParentEndpointTests() { - _mockHandler = Substitute.For>>>(); + _mockHandler = Substitute.For>>>(); _sut = Factory.Create(_mockHandler); _pathSegmentResponseFixture = new PathSegmentResponseFixture(); _getPathParentRequestFixture = new GetPathParentRequestFixture(); @@ -50,7 +50,7 @@ public class GetPathParentEndpointTests CancellationToken cancellationToken = CancellationToken.None; IEnumerable expectedResponse = _pathSegmentResponseFixture.CreateMany(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -119,7 +119,7 @@ public class GetPathParentEndpointTests GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser"); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.CreateMany().AsEnumerable())); + .Returns(Result.From(_pathSegmentResponseFixture.CreateMany().AsEnumerable())); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -143,7 +143,7 @@ public class GetPathParentEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(_pathSegmentResponseFixture.CreateMany().AsEnumerable()); + return Result.From(_pathSegmentResponseFixture.CreateMany().AsEnumerable()); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs index 96ad81fb..c5b06a4a 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; @@ -24,7 +24,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class GetPathRootEndpointTests { - private readonly IQueryHandler> _mockHandler; + private readonly IQueryHandler> _mockHandler; private readonly GetPathRootEndpoint _sut; private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; private readonly GetPathRootRequestFixture _getPathRootRequestFixture; @@ -34,7 +34,7 @@ public class GetPathRootEndpointTests /// public GetPathRootEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = Factory.Create(_mockHandler); _pathSegmentResponseFixture = new PathSegmentResponseFixture(); _getPathRootRequestFixture = new GetPathRootRequestFixture(); @@ -48,7 +48,7 @@ public class GetPathRootEndpointTests CancellationToken cancellationToken = CancellationToken.None; PathSegmentResponse expectedResponse = _pathSegmentResponseFixture.Create(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -117,7 +117,7 @@ public class GetPathRootEndpointTests GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser"); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.Create())); + .Returns(Result.From(_pathSegmentResponseFixture.Create())); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -141,7 +141,7 @@ public class GetPathRootEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(_pathSegmentResponseFixture.Create()); + return Result.From(_pathSegmentResponseFixture.Create()); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs index 3eadf322..7c7fe6e4 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.SplitPath; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; @@ -25,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class SplitPathEndpointTests { - private readonly ICommandHandler>> _mockHandler; + private readonly ICommandHandler>> _mockHandler; private readonly SplitPathEndpoint _sut; private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; private readonly SplitPathRequestFixture _splitPathRequestFixture; @@ -35,7 +35,7 @@ public class SplitPathEndpointTests /// public SplitPathEndpointTests() { - _mockHandler = Substitute.For>>>(); + _mockHandler = Substitute.For>>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); _pathSegmentResponseFixture = new PathSegmentResponseFixture(); _splitPathRequestFixture = new SplitPathRequestFixture(); @@ -49,7 +49,7 @@ public class SplitPathEndpointTests CancellationToken cancellationToken = CancellationToken.None; IEnumerable expectedResponse = _pathSegmentResponseFixture.CreateMany(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -93,7 +93,7 @@ public class SplitPathEndpointTests SplitPathRequest request = _splitPathRequestFixture.Create(@"C:\Users\TestUser\Documents"); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.CreateMany().AsEnumerable())); + .Returns(Result.From(_pathSegmentResponseFixture.CreateMany().AsEnumerable())); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -119,7 +119,7 @@ public class SplitPathEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new List + return Result.From(new List { _pathSegmentResponseFixture.Create() }.AsEnumerable()); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs index 3cd52a83..7ff2d1d2 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs @@ -1,15 +1,14 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.ValidatePath; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; -using Microsoft.AspNetCore.Mvc; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -25,7 +24,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class ValidatePathEndpointTests { - private readonly IQueryHandler> _mockHandler; + private readonly IQueryHandler> _mockHandler; private readonly ValidatePathEndpoint _sut; private readonly ValidatePathRequestFixture _validatePathRequestFixture; @@ -34,7 +33,7 @@ public class ValidatePathEndpointTests /// public ValidatePathEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = Factory.Create(_mockHandler); _validatePathRequestFixture = new ValidatePathRequestFixture(); } @@ -116,7 +115,7 @@ public class ValidatePathEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new PathValidResponse(true)); + return Result.From(new PathValidResponse(true)); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs index 9fd3fcfd..d087b5a4 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Utilities; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; @@ -25,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class GetThumbnailEndpointTests { - private readonly IQueryHandler> _mockHandler; + private readonly IQueryHandler> _mockHandler; private readonly GetThumbnailEndpoint _sut; private readonly GetThumbnailRequestFixture _getThumbnailRequestFixture; @@ -34,7 +34,7 @@ public class GetThumbnailEndpointTests /// public GetThumbnailEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = Factory.Create(_mockHandler); _getThumbnailRequestFixture = new GetThumbnailRequestFixture(); } @@ -47,7 +47,7 @@ public class GetThumbnailEndpointTests CancellationToken cancellationToken = CancellationToken.None; ThumbnailResponse expectedResponse = ThumbnailResponseFixture.CreateThumbnailResponse(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -117,7 +117,7 @@ public class GetThumbnailEndpointTests GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/file.jpg", 80); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(ThumbnailResponseFixture.CreateThumbnailResponse())); + .Returns(Result.From(ThumbnailResponseFixture.CreateThumbnailResponse())); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -141,7 +141,7 @@ public class GetThumbnailEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(ThumbnailResponseFixture.CreateThumbnailResponse()); + return Result.From(ThumbnailResponseFixture.CreateThumbnailResponse()); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs index 25381421..1f422d8b 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs @@ -1,11 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; -using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; -using Lumina.Contracts.Responses.UsersManagement; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.ApplicationSetup.Fixtures; using Microsoft.AspNetCore.Http; @@ -25,7 +23,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.Applicati [ExcludeFromCodeCoverage] public class SetupApplicationEndpointTests { - private readonly ICommandHandler> _mockHandler; + private readonly ICommandHandler> _mockHandler; private readonly SetupApplicationEndpoint _sut; private readonly RegistrationRequestFixture _registrationRequestFixture; @@ -34,7 +32,7 @@ public class SetupApplicationEndpointTests /// public SetupApplicationEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); _registrationRequestFixture = new RegistrationRequestFixture(); } @@ -47,7 +45,7 @@ public class SetupApplicationEndpointTests CancellationToken cancellationToken = CancellationToken.None; RegistrationResponse expectedResponse = new(Guid.NewGuid(), "testUser", "TOTP123"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -91,7 +89,7 @@ public class SetupApplicationEndpointTests RegistrationRequest request = _registrationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123"))); + .Returns(Result.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123"))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -121,7 +119,7 @@ public class SetupApplicationEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123")); + return Result.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123")); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs index c72a5ce6..243f0ed7 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.ChangePassword; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword.Fixtures; using Microsoft.AspNetCore.Http; @@ -23,7 +23,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authe [ExcludeFromCodeCoverage] public class ChangePasswordEndpointTests { - private readonly ICommandHandler> _mockHandler; + private readonly ICommandHandler> _mockHandler; private readonly ChangePasswordEndpoint _sut; private readonly ChangePasswordRequestFixture _changePasswordRequestFixture; @@ -32,7 +32,7 @@ public class ChangePasswordEndpointTests /// public ChangePasswordEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); _changePasswordRequestFixture = new ChangePasswordRequestFixture(); } @@ -45,7 +45,7 @@ public class ChangePasswordEndpointTests CancellationToken cancellationToken = CancellationToken.None; ChangePasswordResponse expectedResponse = new(IsPasswordChanged: true); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -87,7 +87,7 @@ public class ChangePasswordEndpointTests ChangePasswordRequest request = _changePasswordRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(new ChangePasswordResponse(true))); + .Returns(Result.From(new ChangePasswordResponse(true))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -117,7 +117,7 @@ public class ChangePasswordEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new ChangePasswordResponse(true)); + return Result.From(new ChangePasswordResponse(true)); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs index e366677f..132e33d9 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUsers; using Lumina.Contracts.Responses.UsersManagement.Users; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.GetUsers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; @@ -23,14 +23,14 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authe [ExcludeFromCodeCoverage] public class GetUsersEndpointTests { - private readonly IQueryHandler>> _mockHandler; + private readonly IQueryHandler>> _mockHandler; private readonly GetUsersEndpoint _sut; /// /// Initializes a new instance of the class. /// public GetUsersEndpointTests() { - _mockHandler = Substitute.For>>>(); + _mockHandler = Substitute.For>>>(); _sut = Factory.Create(_mockHandler); } @@ -44,7 +44,7 @@ public class GetUsersEndpointTests new UserResponse(Guid.NewGuid(), "testUser", DateTime.UtcNow, null) ]; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); @@ -85,7 +85,7 @@ public class GetUsersEndpointTests // Arrange CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(Array.Empty() as IEnumerable)); + .Returns(Result.From(Array.Empty() as IEnumerable)); // Act await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); @@ -110,7 +110,7 @@ public class GetUsersEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(Array.Empty() as IEnumerable); + return Result.From(Array.Empty() as IEnumerable); }, info.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs index 06e08639..0e6a6b52 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Login; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.Login.Fixtures; using Microsoft.AspNetCore.Http; @@ -24,7 +24,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authe [ExcludeFromCodeCoverage] public class LoginEndpointTests { - private readonly IQueryHandler> _mockHandler; + private readonly IQueryHandler> _mockHandler; private readonly LoginEndpoint _sut; private readonly LoginRequestFixture _loginRequestFixture; @@ -33,7 +33,7 @@ public class LoginEndpointTests /// public LoginEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = Factory.Create(_mockHandler); _loginRequestFixture = new LoginRequestFixture(); } @@ -46,7 +46,7 @@ public class LoginEndpointTests CancellationToken cancellationToken = CancellationToken.None; LoginResponse expectedResponse = new(Guid.NewGuid(), "testUser", "jwt_token", true); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -88,7 +88,7 @@ public class LoginEndpointTests LoginRequest request = _loginRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(new LoginResponse(Guid.NewGuid(), "testUser", "jwt_token", true))); + .Returns(Result.From(new LoginResponse(Guid.NewGuid(), "testUser", "jwt_token", true))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -117,7 +117,7 @@ public class LoginEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new LoginResponse(Guid.NewGuid(), "testUser", "jwt_token", true)); + return Result.From(new LoginResponse(Guid.NewGuid(), "testUser", "jwt_token", true)); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs index 51cfc579..4045c969 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword.Fixtures; using Microsoft.AspNetCore.Http; @@ -23,7 +23,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authe [ExcludeFromCodeCoverage] public class RecoverPasswordEndpointTests { - private readonly ICommandHandler> _mockHandler; + private readonly ICommandHandler> _mockHandler; private readonly RecoverPasswordEndpoint _sut; private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture; @@ -32,7 +32,7 @@ public class RecoverPasswordEndpointTests /// public RecoverPasswordEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); _recoverPasswordRequestFixture = new RecoverPasswordRequestFixture(); } @@ -45,7 +45,7 @@ public class RecoverPasswordEndpointTests CancellationToken cancellationToken = CancellationToken.None; RecoverPasswordResponse expectedResponse = new(IsPasswordReset: true); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -87,7 +87,7 @@ public class RecoverPasswordEndpointTests RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(new RecoverPasswordResponse(true))); + .Returns(Result.From(new RecoverPasswordResponse(true))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -115,7 +115,7 @@ public class RecoverPasswordEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new RecoverPasswordResponse(true)); + return Result.From(new RecoverPasswordResponse(true)); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs index 36a54655..f003d344 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.ApplicationSetup.Fixtures; using Microsoft.AspNetCore.Http; @@ -23,7 +23,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authe [ExcludeFromCodeCoverage] public class RegisterEndpointTests { - private readonly ICommandHandler> _mockHandler; + private readonly ICommandHandler> _mockHandler; private readonly RegisterEndpoint _sut; private readonly RegistrationRequestFixture _registrationRequestFixture; @@ -32,7 +32,7 @@ public class RegisterEndpointTests /// public RegisterEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); _registrationRequestFixture = new RegistrationRequestFixture(); } @@ -45,7 +45,7 @@ public class RegisterEndpointTests CancellationToken cancellationToken = CancellationToken.None; RegistrationResponse expectedResponse = new(Guid.NewGuid(), "testUser", "TOTP123"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -88,7 +88,7 @@ public class RegisterEndpointTests RegistrationRequest request = _registrationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123"))); + .Returns(Result.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123"))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -118,7 +118,7 @@ public class RegisterEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123")); + return Result.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123")); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs index 11a20c0a..2e38b242 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.GetAuthorization; using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authorization.GetAuthorization.Fixtures; @@ -27,7 +27,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Autho [ExcludeFromCodeCoverage] public class GetAuthorizationEndpointTests { - private readonly IQueryHandler> _mockHandler; + private readonly IQueryHandler> _mockHandler; private readonly GetAuthorizationEndpoint _sut; /// @@ -35,7 +35,7 @@ public class GetAuthorizationEndpointTests /// public GetAuthorizationEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = Factory.Create(_mockHandler); } @@ -51,7 +51,7 @@ public class GetAuthorizationEndpointTests new HashSet { AuthorizationPermission.CanViewUsers }); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -96,7 +96,7 @@ public class GetAuthorizationEndpointTests CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(new AuthorizationResponse( + .Returns(Result.From(new AuthorizationResponse( request.UserId!.Value, string.Empty, new HashSet().ToHashSet() @@ -127,7 +127,7 @@ public class GetAuthorizationEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new AuthorizationResponse( + return Result.From(new AuthorizationResponse( request.UserId!.Value, string.Empty, new HashSet().ToHashSet() diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs index d44fca3f..b2145950 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.GetUserPermissions; using Microsoft.AspNetCore.Http; @@ -25,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Autho [ExcludeFromCodeCoverage] public class GetUserPermissionsEndpointTests { - private readonly IQueryHandler>> _mockHandler; + private readonly IQueryHandler>> _mockHandler; private readonly GetUserPermissionsEndpoint _sut; /// @@ -33,7 +33,7 @@ public class GetUserPermissionsEndpointTests /// public GetUserPermissionsEndpointTests() { - _mockHandler = Substitute.For>>>(); + _mockHandler = Substitute.For>>>(); _sut = Factory.Create(_mockHandler); } @@ -49,7 +49,7 @@ public class GetUserPermissionsEndpointTests new PermissionResponse(Guid.NewGuid(), AuthorizationPermission.CanDeleteUsers) ]; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -93,7 +93,7 @@ public class GetUserPermissionsEndpointTests GetUserPermissionsRequest request = new(userId); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(Array.Empty() as IEnumerable)); + .Returns(Result.From(Array.Empty() as IEnumerable)); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -118,7 +118,7 @@ public class GetUserPermissionsEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(Array.Empty() as IEnumerable); + return Result.From(Array.Empty() as IEnumerable); }, info.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs index dfc6627d..1ec03f87 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.GetUserRole; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; @@ -23,7 +23,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Autho [ExcludeFromCodeCoverage] public class GetUserRoleEndpointTests { - private readonly IQueryHandler> _mockHandler; + private readonly IQueryHandler> _mockHandler; private readonly GetUserRoleEndpoint _sut; /// @@ -31,7 +31,7 @@ public class GetUserRoleEndpointTests /// public GetUserRoleEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = Factory.Create(_mockHandler); } @@ -43,7 +43,7 @@ public class GetUserRoleEndpointTests CancellationToken cancellationToken = CancellationToken.None; RoleResponse expectedResponse = new(Guid.NewGuid(), "Admin"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -87,7 +87,7 @@ public class GetUserRoleEndpointTests GetUserRoleRequest request = new(userId); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(new RoleResponse(Guid.NewGuid(), "Admin"))); + .Returns(Result.From(new RoleResponse(Guid.NewGuid(), "Admin"))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -112,7 +112,7 @@ public class GetUserRoleEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new RoleResponse(Guid.NewGuid(), "Admin")); + return Result.From(new RoleResponse(Guid.NewGuid(), "Admin")); }, info.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs index 9b4235c7..c7c93607 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.UpdateUserRoleAndPermissions; using Microsoft.AspNetCore.Http; @@ -25,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Autho [ExcludeFromCodeCoverage] public class UpdateUserRoleAndPermissionsEndpointTests { - private readonly ICommandHandler> _mockHandler; + private readonly ICommandHandler> _mockHandler; private readonly UpdateUserRoleAndPermissionsEndpoint _sut; /// @@ -33,7 +33,7 @@ public class UpdateUserRoleAndPermissionsEndpointTests /// public UpdateUserRoleAndPermissionsEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); } @@ -53,7 +53,7 @@ public class UpdateUserRoleAndPermissionsEndpointTests new HashSet { AuthorizationPermission.CanViewUsers } ); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -104,7 +104,7 @@ public class UpdateUserRoleAndPermissionsEndpointTests ); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(new AuthorizationResponse( + .Returns(Result.From(new AuthorizationResponse( Guid.NewGuid(), "Admin", new HashSet { AuthorizationPermission.CanViewUsers } @@ -136,7 +136,7 @@ public class UpdateUserRoleAndPermissionsEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new AuthorizationResponse( + return Result.From(new AuthorizationResponse( Guid.NewGuid(), "Admin", new HashSet { AuthorizationPermission.CanViewUsers }