mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 15:11:10 +00:00
Merge pull request #145 from BinaryAlley/refactor/replace-repository-reflection-based-instantiation
Replaces reflection-based repository instantiation with unit of work property accessors
This commit is contained in:
87 files changed
+538
-732
No files matched your search
+1
-1
@@ -31,7 +31,7 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD
|
|||||||
{
|
{
|
||||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
|
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
|
||||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
|
ILibraryRepository libraryRepository = unitOfWork.LibraryRepository;
|
||||||
// execution logic
|
// execution logic
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||||
|
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||||
|
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||||
|
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||||
|
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
#endregion
|
#endregion
|
||||||
@@ -11,11 +16,69 @@ namespace Lumina.Application.Common.DataAccess.UoW;
|
|||||||
public interface IUnitOfWork
|
public interface IUnitOfWork
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Exposes a repository of type <typeparamref name="TRepository"/> to the Business Layer.
|
/// Gets the permission repository.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="TRepository">The type of the exposed repository.</typeparam>
|
IPermissionRepository PermissionRepository { get; }
|
||||||
/// <returns>A repository of type <typeparamref name="TRepository"/>.</returns>
|
|
||||||
TRepository GetRepository<TRepository>();
|
/// <summary>
|
||||||
|
/// Gets the role permission repository.
|
||||||
|
/// </summary>
|
||||||
|
IRolePermissionRepository RolePermissionRepository { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the role repository.
|
||||||
|
/// </summary>
|
||||||
|
IRoleRepository RoleRepository { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the role user repository.
|
||||||
|
/// </summary>
|
||||||
|
IUserRoleRepository UserRoleRepository { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the book repository.
|
||||||
|
/// </summary>
|
||||||
|
IBookRepository BookRepository { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the directory scan fingerprint repository.
|
||||||
|
/// </summary>
|
||||||
|
IDirectoryScanFingerprintRepository DirectoryScanFingerprintRepository { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the library repository.
|
||||||
|
/// </summary>
|
||||||
|
ILibraryRepository LibraryRepository { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the library scan repository.
|
||||||
|
/// </summary>
|
||||||
|
ILibraryScanRepository LibraryScanRepository { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the library scan snapshot repository.
|
||||||
|
/// </summary>
|
||||||
|
ILibraryScanSnapshotRepository LibraryScanSnapshotRepository { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the library scan staging results repository.
|
||||||
|
/// </summary>
|
||||||
|
ILibraryScanStagingResultsRepository LibraryScanStagingResultsRepository { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the library metadata provider configuration repository.
|
||||||
|
/// </summary>
|
||||||
|
ILibraryMetadataProviderConfigurationRepository LibraryMetadataProviderConfigurationRepository { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the plugin repository.
|
||||||
|
/// </summary>
|
||||||
|
IPluginRepository PluginRepository { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the user repository.
|
||||||
|
/// </summary>
|
||||||
|
IUserRepository UserRepository { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Saves all changes made to the database.
|
/// Saves all changes made to the database.
|
||||||
@@ -24,12 +87,24 @@ public interface IUnitOfWork
|
|||||||
Task SaveChangesAsync(CancellationToken cancellationToken);
|
Task SaveChangesAsync(CancellationToken cancellationToken);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Opens a transaction.
|
/// Begins a new database transaction.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
void OpenTransaction();
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
|
/// <returns>A task representing the asynchronous operation.</returns>
|
||||||
|
Task BeginTransactionAsync(CancellationToken cancellationToken);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Commits a transaction.
|
/// Commits the current transaction.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
void CommitTransaction();
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
|
/// <returns>A task representing the asynchronous operation.</returns>
|
||||||
|
Task CommitTransactionAsync(CancellationToken cancellationToken);
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Rolls back the current transaction.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
|
/// <returns>A task representing the asynchronous operation.</returns>
|
||||||
|
Task RollbackTransactionAsync(CancellationToken cancellationToken);
|
||||||
}
|
}
|
||||||
+3
-3
@@ -22,8 +22,8 @@ namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPer
|
|||||||
public class GetPermissionsQueryHandler : IQueryHandler<GetPermissionsQuery, Result<IEnumerable<PermissionResponse>>>
|
public class GetPermissionsQueryHandler : IQueryHandler<GetPermissionsQuery, Result<IEnumerable<PermissionResponse>>>
|
||||||
{
|
{
|
||||||
private readonly ICurrentUserService _currentUserService;
|
private readonly ICurrentUserService _currentUserService;
|
||||||
|
private readonly IUnitOfWork _unitOfWork;
|
||||||
private readonly IAuthorizationService _authorizationService;
|
private readonly IAuthorizationService _authorizationService;
|
||||||
private readonly IPermissionRepository _permissionRepository;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Initializes a new instance of the <see cref="GetPermissionsQueryHandler"/> class.
|
/// Initializes a new instance of the <see cref="GetPermissionsQueryHandler"/> class.
|
||||||
@@ -35,7 +35,7 @@ public class GetPermissionsQueryHandler : IQueryHandler<GetPermissionsQuery, Res
|
|||||||
{
|
{
|
||||||
_authorizationService = authorizationService;
|
_authorizationService = authorizationService;
|
||||||
_currentUserService = currentUserService;
|
_currentUserService = currentUserService;
|
||||||
_permissionRepository = unitOfWork.GetRepository<IPermissionRepository>();
|
_unitOfWork = unitOfWork;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -52,7 +52,7 @@ public class GetPermissionsQueryHandler : IQueryHandler<GetPermissionsQuery, Res
|
|||||||
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
||||||
if (!isAdmin)
|
if (!isAdmin)
|
||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
Result<IEnumerable<PermissionEntity>> getPermissionsResult = await _permissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<PermissionEntity>> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||||
return getPermissionsResult.Match(value => Result.From(value.ToResponses()), errors => errors);
|
return getPermissionsResult.Match(value => Result.From(value.ToResponses()), errors => errors);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-4
@@ -62,8 +62,6 @@ public class AddRoleCommandHandler : ICommandHandler<AddRoleCommand, Result<Role
|
|||||||
if (!isAdmin)
|
if (!isAdmin)
|
||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
|
|
||||||
|
|
||||||
// create the new role, with its permissions
|
// create the new role, with its permissions
|
||||||
RoleEntity newRole = new()
|
RoleEntity newRole = new()
|
||||||
{
|
{
|
||||||
@@ -77,12 +75,12 @@ public class AddRoleCommandHandler : ICommandHandler<AddRoleCommand, Result<Role
|
|||||||
})]
|
})]
|
||||||
};
|
};
|
||||||
// save the new role in the repository
|
// save the new role in the repository
|
||||||
Result<Created> insertRoleResult = await roleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false);
|
Result<Created> insertRoleResult = await _unitOfWork.RoleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false);
|
||||||
if (insertRoleResult.IsFailure)
|
if (insertRoleResult.IsFailure)
|
||||||
return insertRoleResult.Errors;
|
return insertRoleResult.Errors;
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
// retrieve the newly saved authorization role from the persistence medium and return it
|
// retrieve the newly saved authorization role from the persistence medium and return it
|
||||||
Result<RoleEntity?> getRoleResult = await roleRepository.GetByNameAsync(request.RoleName, cancellationToken).ConfigureAwait(false);
|
Result<RoleEntity?> getRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync(request.RoleName, cancellationToken).ConfigureAwait(false);
|
||||||
if (getRoleResult.IsFailure)
|
if (getRoleResult.IsFailure)
|
||||||
return getRoleResult.Errors;
|
return getRoleResult.Errors;
|
||||||
if (getRoleResult.Value is null)
|
if (getRoleResult.Value is null)
|
||||||
|
|||||||
+2
-3
@@ -62,8 +62,7 @@ public class DeleteRoleCommandHandler : ICommandHandler<DeleteRoleCommand, Resul
|
|||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
// check if a role with the requested Id exists
|
// check if a role with the requested Id exists
|
||||||
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
|
Result<RoleEntity?> getExistingRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
|
||||||
Result<RoleEntity?> getExistingRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getExistingRoleResult.IsFailure)
|
if (getExistingRoleResult.IsFailure)
|
||||||
return getExistingRoleResult.Errors;
|
return getExistingRoleResult.Errors;
|
||||||
else if (getExistingRoleResult.Value is null)
|
else if (getExistingRoleResult.Value is null)
|
||||||
@@ -71,7 +70,7 @@ public class DeleteRoleCommandHandler : ICommandHandler<DeleteRoleCommand, Resul
|
|||||||
else if (getExistingRoleResult.Value.RoleName == "Admin")
|
else if (getExistingRoleResult.Value.RoleName == "Admin")
|
||||||
return Errors.Authorization.AdminRoleCannotBeDeleted;
|
return Errors.Authorization.AdminRoleCannotBeDeleted;
|
||||||
// delete the role and its permissions
|
// delete the role and its permissions
|
||||||
Result<Deleted> deleteRoleResult = await roleRepository.DeleteByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
|
Result<Deleted> deleteRoleResult = await _unitOfWork.RoleRepository.DeleteByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
|
||||||
if (deleteRoleResult.IsFailure)
|
if (deleteRoleResult.IsFailure)
|
||||||
return deleteRoleResult.Errors;
|
return deleteRoleResult.Errors;
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|||||||
+2
-4
@@ -62,8 +62,6 @@ public class UpdateRoleCommandHandler : ICommandHandler<UpdateRoleCommand, Resul
|
|||||||
if (!isAdmin)
|
if (!isAdmin)
|
||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
|
|
||||||
|
|
||||||
// update the role and its permissions
|
// update the role and its permissions
|
||||||
RoleEntity newRole = new()
|
RoleEntity newRole = new()
|
||||||
{
|
{
|
||||||
@@ -78,12 +76,12 @@ public class UpdateRoleCommandHandler : ICommandHandler<UpdateRoleCommand, Resul
|
|||||||
}).ToList()
|
}).ToList()
|
||||||
};
|
};
|
||||||
// save the updated role in the repository
|
// save the updated role in the repository
|
||||||
Result<Updated> updateRoleResult = await roleRepository.UpdateAsync(newRole, cancellationToken).ConfigureAwait(false);
|
Result<Updated> updateRoleResult = await _unitOfWork.RoleRepository.UpdateAsync(newRole, cancellationToken).ConfigureAwait(false);
|
||||||
if (updateRoleResult.IsFailure)
|
if (updateRoleResult.IsFailure)
|
||||||
return updateRoleResult.Errors;
|
return updateRoleResult.Errors;
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
// retrieve the updated authorization role from the persistence medium and return it
|
// retrieve the updated authorization role from the persistence medium and return it
|
||||||
Result<RoleEntity?> getRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
|
Result<RoleEntity?> getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
|
||||||
if (getRoleResult.IsFailure)
|
if (getRoleResult.IsFailure)
|
||||||
return getRoleResult.Errors;
|
return getRoleResult.Errors;
|
||||||
if (getRoleResult.Value is null)
|
if (getRoleResult.Value is null)
|
||||||
|
|||||||
+1
-1
@@ -38,7 +38,7 @@ public class GetRolePermissionsQueryHandler : IQueryHandler<GetRolePermissionsQu
|
|||||||
{
|
{
|
||||||
_authorizationService = authorizationService;
|
_authorizationService = authorizationService;
|
||||||
_currentUserService = currentUserService;
|
_currentUserService = currentUserService;
|
||||||
_roleRepository = unitOfWork.GetRepository<IRoleRepository>();
|
_roleRepository = unitOfWork.RoleRepository;
|
||||||
_validator = validator;
|
_validator = validator;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -35,7 +35,7 @@ public class GetRolesQueryHandler : IQueryHandler<GetRolesQuery, Result<IEnumera
|
|||||||
{
|
{
|
||||||
_authorizationService = authorizationService;
|
_authorizationService = authorizationService;
|
||||||
_currentUserService = currentUserService;
|
_currentUserService = currentUserService;
|
||||||
_roleRepository = unitOfWork.GetRepository<IRoleRepository>();
|
_roleRepository = unitOfWork.RoleRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
+2
-3
@@ -80,8 +80,7 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
|
|||||||
return validationResult;
|
return validationResult;
|
||||||
|
|
||||||
// check if any users already exists (admin account is only set once!)
|
// check if any users already exists (admin account is only set once!)
|
||||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
Result<IEnumerable<UserEntity>> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||||
Result<IEnumerable<UserEntity>> selectUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
if (selectUsersResult.IsFailure)
|
if (selectUsersResult.IsFailure)
|
||||||
return selectUsersResult.Errors;
|
return selectUsersResult.Errors;
|
||||||
else if (selectUsersResult.Value.Any())
|
else if (selectUsersResult.Value.Any())
|
||||||
@@ -112,7 +111,7 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
|
|||||||
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
|
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
|
||||||
}
|
}
|
||||||
// insert the user
|
// insert the user
|
||||||
Result<Created> insertUserResult = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
|
Result<Created> insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
|
||||||
if (insertUserResult.IsFailure)
|
if (insertUserResult.IsFailure)
|
||||||
return insertUserResult.Errors;
|
return insertUserResult.Errors;
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|||||||
+1
-2
@@ -38,9 +38,8 @@ public class CheckInitializationQueryHandler : IQueryHandler<CheckInitialization
|
|||||||
/// </returns>
|
/// </returns>
|
||||||
public async Task<InitializationResponse> HandleAsync(CheckInitializationQuery query, CancellationToken cancellationToken)
|
public async Task<InitializationResponse> HandleAsync(CheckInitializationQuery query, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
|
||||||
// if the repository reports an error, or there are no users, the application has not been initialized
|
// if the repository reports an error, or there are no users, the application has not been initialized
|
||||||
Result<IEnumerable<UserEntity>> selectUsersResult = await userRepository.GetAllAsync(cancellationToken);
|
Result<IEnumerable<UserEntity>> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken);
|
||||||
if (!selectUsersResult.IsFailure)
|
if (!selectUsersResult.IsFailure)
|
||||||
return new InitializationResponse(selectUsersResult.Value.Any());
|
return new InitializationResponse(selectUsersResult.Value.Any());
|
||||||
return new InitializationResponse(false);
|
return new InitializationResponse(false);
|
||||||
|
|||||||
+2
-4
@@ -116,18 +116,16 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
|
|||||||
if (createLibraryResult.IsFailure)
|
if (createLibraryResult.IsFailure)
|
||||||
return createLibraryResult.Errors;
|
return createLibraryResult.Errors;
|
||||||
|
|
||||||
// get a library repository
|
|
||||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
|
||||||
// convert the domain library entity to a repository library entity
|
// convert the domain library entity to a repository library entity
|
||||||
LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity();
|
LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity();
|
||||||
// insert the repository entity and save changes
|
// insert the repository entity and save changes
|
||||||
Result<Created> insertLibraryResult = await libraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false);
|
Result<Created> insertLibraryResult = await _unitOfWork.LibraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false);
|
||||||
if (insertLibraryResult.IsFailure)
|
if (insertLibraryResult.IsFailure)
|
||||||
return insertLibraryResult.Errors;
|
return insertLibraryResult.Errors;
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
// retrieve the newly saved media library from the persistence medium and return it
|
// retrieve the newly saved media library from the persistence medium and return it
|
||||||
Result<LibraryEntity?> getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
Result<LibraryEntity?> getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getCreatedLibraryResult.IsFailure)
|
if (getCreatedLibraryResult.IsFailure)
|
||||||
return getCreatedLibraryResult.Errors;
|
return getCreatedLibraryResult.Errors;
|
||||||
if (getCreatedLibraryResult.Value is null)
|
if (getCreatedLibraryResult.Value is null)
|
||||||
|
|||||||
+2
-4
@@ -56,10 +56,8 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler<CancelLibraries
|
|||||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||||
public async Task<Result<Success>> HandleAsync(CancelLibrariesScanCommand command, CancellationToken cancellationToken)
|
public async Task<Result<Success>> HandleAsync(CancelLibrariesScanCommand command, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
|
||||||
|
|
||||||
// get the running library scans of the current user from the repository
|
// get the running library scans of the current user from the repository
|
||||||
Result<IEnumerable<LibraryScanEntity>> getRunningLibraryScansResult = await libraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<LibraryScanEntity>> getRunningLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
|
||||||
if (getRunningLibraryScansResult.IsFailure)
|
if (getRunningLibraryScansResult.IsFailure)
|
||||||
return getRunningLibraryScansResult.Errors;
|
return getRunningLibraryScansResult.Errors;
|
||||||
|
|
||||||
@@ -88,7 +86,7 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler<CancelLibraries
|
|||||||
return cancelScanResult.Errors;
|
return cancelScanResult.Errors;
|
||||||
|
|
||||||
// update the status of the library scan in the repository
|
// update the status of the library scan in the repository
|
||||||
Result<Updated> updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
Result<Updated> updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||||
if (updateLibraryScanResult.IsFailure)
|
if (updateLibraryScanResult.IsFailure)
|
||||||
return updateLibraryScanResult.Errors;
|
return updateLibraryScanResult.Errors;
|
||||||
|
|
||||||
|
|||||||
+2
-4
@@ -65,10 +65,8 @@ public class CancelLibraryScanCommandHandler : ICommandHandler<CancelLibraryScan
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
return validationResult;
|
||||||
|
|
||||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
|
||||||
|
|
||||||
// get the library scan from the repository
|
// get the library scan from the repository
|
||||||
Result<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false);
|
Result<LibraryScanEntity?> getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibraryScansResult.IsFailure)
|
if (getLibraryScansResult.IsFailure)
|
||||||
return getLibraryScansResult.Errors;
|
return getLibraryScansResult.Errors;
|
||||||
if (getLibraryScansResult.Value is null)
|
if (getLibraryScansResult.Value is null)
|
||||||
@@ -90,7 +88,7 @@ public class CancelLibraryScanCommandHandler : ICommandHandler<CancelLibraryScan
|
|||||||
return cancelScanResult.Errors;
|
return cancelScanResult.Errors;
|
||||||
|
|
||||||
// update the status of the library scan in the repository
|
// update the status of the library scan in the repository
|
||||||
Result<Updated> updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
Result<Updated> updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||||
if (updateLibraryScanResult.IsFailure)
|
if (updateLibraryScanResult.IsFailure)
|
||||||
return updateLibraryScanResult.Errors;
|
return updateLibraryScanResult.Errors;
|
||||||
|
|
||||||
|
|||||||
+2
-3
@@ -66,8 +66,7 @@ public class DeleteLibraryCommandHandler : ICommandHandler<DeleteLibraryCommand,
|
|||||||
return validationResult;
|
return validationResult;
|
||||||
|
|
||||||
// get the library with the specified id from the repository
|
// get the library with the specified id from the repository
|
||||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||||
Result<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getLibraryResult.IsFailure)
|
if (getLibraryResult.IsFailure)
|
||||||
return getLibraryResult.Errors;
|
return getLibraryResult.Errors;
|
||||||
else if (getLibraryResult.Value is null)
|
else if (getLibraryResult.Value is null)
|
||||||
@@ -93,7 +92,7 @@ public class DeleteLibraryCommandHandler : ICommandHandler<DeleteLibraryCommand,
|
|||||||
_domainEventsQueue.Enqueue(domainEvent);
|
_domainEventsQueue.Enqueue(domainEvent);
|
||||||
|
|
||||||
// perform the deletion
|
// perform the deletion
|
||||||
Result<Deleted> deletePersistenceLibraryResult = await libraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
Result<Deleted> deletePersistenceLibraryResult = await _unitOfWork.LibraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||||
if (deletePersistenceLibraryResult.IsFailure)
|
if (deletePersistenceLibraryResult.IsFailure)
|
||||||
return deletePersistenceLibraryResult.Errors;
|
return deletePersistenceLibraryResult.Errors;
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|||||||
+3
-6
@@ -59,11 +59,8 @@ public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand,
|
|||||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||||
public async Task<Result<IEnumerable<MediaLibraryScanResponse>>> HandleAsync(ScanLibrariesCommand command, CancellationToken cancellationToken)
|
public async Task<Result<IEnumerable<MediaLibraryScanResponse>>> HandleAsync(ScanLibrariesCommand command, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
|
||||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
|
||||||
|
|
||||||
// get all media libraries that are enabled and unlocked from the persistence medium
|
// get all media libraries that are enabled and unlocked from the persistence medium
|
||||||
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await libraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibrariesResult.IsFailure)
|
if (getLibrariesResult.IsFailure)
|
||||||
return getLibrariesResult.Errors;
|
return getLibrariesResult.Errors;
|
||||||
|
|
||||||
@@ -85,7 +82,7 @@ public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand,
|
|||||||
|
|
||||||
// get the past month's scans for this library
|
// get the past month's scans for this library
|
||||||
Result<IEnumerable<LibraryScanEntity>> pastLibraryScansResult =
|
Result<IEnumerable<LibraryScanEntity>> pastLibraryScansResult =
|
||||||
await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(domainLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
await _unitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(domainLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (pastLibraryScansResult.IsFailure)
|
if (pastLibraryScansResult.IsFailure)
|
||||||
return pastLibraryScansResult.Errors;
|
return pastLibraryScansResult.Errors;
|
||||||
|
|
||||||
@@ -111,7 +108,7 @@ public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand,
|
|||||||
continue;
|
continue;
|
||||||
|
|
||||||
// add the library scan to the persistence medium
|
// add the library scan to the persistence medium
|
||||||
Result<Created> insertLibraryScanResult = await libraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
Result<Created> insertLibraryScanResult = await _unitOfWork.LibraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||||
if (insertLibraryScanResult.IsFailure)
|
if (insertLibraryScanResult.IsFailure)
|
||||||
return insertLibraryScanResult.Errors;
|
return insertLibraryScanResult.Errors;
|
||||||
|
|
||||||
|
|||||||
+3
-6
@@ -71,11 +71,8 @@ public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, Res
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
return validationResult;
|
||||||
|
|
||||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
|
||||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
|
||||||
|
|
||||||
// get the media library from the persistence medium
|
// get the media library from the persistence medium
|
||||||
Result<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibraryResult.IsFailure)
|
if (getLibraryResult.IsFailure)
|
||||||
return getLibraryResult.Errors;
|
return getLibraryResult.Errors;
|
||||||
|
|
||||||
@@ -100,7 +97,7 @@ public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, Res
|
|||||||
return domainLibraryResult.Errors;
|
return domainLibraryResult.Errors;
|
||||||
|
|
||||||
// get the past month's scans for this library
|
// get the past month's scans for this library
|
||||||
Result<IEnumerable<LibraryScanEntity>> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<LibraryScanEntity>> pastLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||||
if (pastLibraryScansResult.IsFailure)
|
if (pastLibraryScansResult.IsFailure)
|
||||||
return pastLibraryScansResult.Errors;
|
return pastLibraryScansResult.Errors;
|
||||||
|
|
||||||
@@ -124,7 +121,7 @@ public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, Res
|
|||||||
return queueScanResult.Errors;
|
return queueScanResult.Errors;
|
||||||
|
|
||||||
// add the library scan to the persistence medium
|
// add the library scan to the persistence medium
|
||||||
Result<Created> insertLibraryScanResult = await libraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
Result<Created> insertLibraryScanResult = await _unitOfWork.LibraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||||
if (insertLibraryScanResult.IsFailure)
|
if (insertLibraryScanResult.IsFailure)
|
||||||
return insertLibraryScanResult.Errors;
|
return insertLibraryScanResult.Errors;
|
||||||
|
|
||||||
|
|||||||
+3
-4
@@ -97,8 +97,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// get a library repository and retrieve the library to update
|
// get a library repository and retrieve the library to update
|
||||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||||
Result<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getLibraryResult.IsFailure)
|
if (getLibraryResult.IsFailure)
|
||||||
return getLibraryResult.Errors;
|
return getLibraryResult.Errors;
|
||||||
else if (getLibraryResult.Value is null)
|
else if (getLibraryResult.Value is null)
|
||||||
@@ -131,13 +130,13 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
|
|||||||
LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity();
|
LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity();
|
||||||
|
|
||||||
// update the repository entity and save changes
|
// update the repository entity and save changes
|
||||||
Result<Updated> updateLibraryResult = await libraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false);
|
Result<Updated> updateLibraryResult = await _unitOfWork.LibraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false);
|
||||||
if (updateLibraryResult.IsFailure)
|
if (updateLibraryResult.IsFailure)
|
||||||
return updateLibraryResult.Errors;
|
return updateLibraryResult.Errors;
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
// retrieve the updated media library from the persistence medium and return it
|
// retrieve the updated media library from the persistence medium and return it
|
||||||
Result<LibraryEntity?> getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
Result<LibraryEntity?> getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getCreatedLibraryResult.IsFailure)
|
if (getCreatedLibraryResult.IsFailure)
|
||||||
return getCreatedLibraryResult.Errors;
|
return getCreatedLibraryResult.Errors;
|
||||||
if (getCreatedLibraryResult.Value is null)
|
if (getCreatedLibraryResult.Value is null)
|
||||||
|
|||||||
+1
-2
@@ -66,8 +66,7 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDo
|
|||||||
throw new EventualConsistencyException(saveCoverImageResult.FirstError, saveCoverImageResult.Errors);
|
throw new EventualConsistencyException(saveCoverImageResult.FirstError, saveCoverImageResult.Errors);
|
||||||
domainEvent.Library.SetInternalLibraryCoverImagePath(saveCoverImageResult.Value);
|
domainEvent.Library.SetInternalLibraryCoverImagePath(saveCoverImageResult.Value);
|
||||||
// update the media library with the new cover location
|
// update the media library with the new cover location
|
||||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
Result<Updated> updateLibraryResult = await _unitOfWork.LibraryRepository.UpdateAsync(domainEvent.Library.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||||
Result<Updated> updateLibraryResult = await libraryRepository.UpdateAsync(domainEvent.Library.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
|
||||||
if (updateLibraryResult.IsFailure)
|
if (updateLibraryResult.IsFailure)
|
||||||
throw new EventualConsistencyException(updateLibraryResult.FirstError, updateLibraryResult.Errors);
|
throw new EventualConsistencyException(updateLibraryResult.FirstError, updateLibraryResult.Errors);
|
||||||
|
|
||||||
|
|||||||
+3
-5
@@ -28,7 +28,6 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
|
|||||||
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
|
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
|
||||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||||
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
||||||
private readonly ILibraryScanRepository _libraryScanRepository;
|
|
||||||
private readonly IUnitOfWork _unitOfWork;
|
private readonly IUnitOfWork _unitOfWork;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -47,7 +46,6 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
|
|||||||
_mediaLibraryScanningService = mediaLibraryScanningService;
|
_mediaLibraryScanningService = mediaLibraryScanningService;
|
||||||
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
||||||
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
|
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
|
||||||
_libraryScanRepository = unitOfWork.GetRepository<ILibraryScanRepository>();
|
|
||||||
_unitOfWork = unitOfWork;
|
_unitOfWork = unitOfWork;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,7 +57,7 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
|
|||||||
public async ValueTask HandleAsync(LibraryScanCancelledDomainEvent domainEvent, CancellationToken cancellationToken)
|
public async ValueTask HandleAsync(LibraryScanCancelledDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
// get the library scan from the repository
|
// get the library scan from the repository
|
||||||
Result<LibraryScanEntity?> getLibraryScansResult = await _libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
Result<LibraryScanEntity?> getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibraryScansResult.IsFailure)
|
if (getLibraryScansResult.IsFailure)
|
||||||
throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors);
|
throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors);
|
||||||
if (getLibraryScansResult.Value is null)
|
if (getLibraryScansResult.Value is null)
|
||||||
@@ -76,11 +74,11 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
|
|||||||
throw new EventualConsistencyException(cancelScanResult.FirstError, cancelScanResult.Errors);
|
throw new EventualConsistencyException(cancelScanResult.FirstError, cancelScanResult.Errors);
|
||||||
|
|
||||||
// release the scan processing resources
|
// release the scan processing resources
|
||||||
ILibraryScanStagingResultsRepository stagingResultsRepository = _unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
|
||||||
MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(domainEvent.ScanId, UserId.Create(getLibraryScansResult.Value.UserId));
|
MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(domainEvent.ScanId, UserId.Create(getLibraryScansResult.Value.UserId));
|
||||||
_mediaLibrariesScanCancellationTracker.RemoveScan(compositeId);
|
_mediaLibrariesScanCancellationTracker.RemoveScan(compositeId);
|
||||||
_mediaLibrariesScanProgressTracker.RemoveScanProgress(compositeId);
|
_mediaLibrariesScanProgressTracker.RemoveScanProgress(compositeId);
|
||||||
Result<Success> clearStagingResult = await stagingResultsRepository.ClearForScanAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
Result<Success> clearStagingResult = await _unitOfWork.LibraryScanStagingResultsRepository.ClearForScanAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (clearStagingResult.IsFailure)
|
if (clearStagingResult.IsFailure)
|
||||||
throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors);
|
throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors);
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-6
@@ -54,11 +54,8 @@ public class LibraryScanFailedDomainEventHandler : IDomainEventHandler<LibrarySc
|
|||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
public async ValueTask HandleAsync(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken)
|
public async ValueTask HandleAsync(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
|
||||||
ILibraryScanStagingResultsRepository stagingResultsRepository = _unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
|
||||||
|
|
||||||
// get the library scan from the repository
|
// get the library scan from the repository
|
||||||
Result<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(
|
Result<LibraryScanEntity?> getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(
|
||||||
domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibraryScansResult.IsFailure)
|
if (getLibraryScansResult.IsFailure)
|
||||||
throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors);
|
throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors);
|
||||||
@@ -77,7 +74,7 @@ public class LibraryScanFailedDomainEventHandler : IDomainEventHandler<LibrarySc
|
|||||||
if (!failScanResult.IsFailure)
|
if (!failScanResult.IsFailure)
|
||||||
{
|
{
|
||||||
// update the status of the library scan in the repository
|
// update the status of the library scan in the repository
|
||||||
Result<Updated> updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
Result<Updated> updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||||
if (updateLibraryScanResult.IsFailure)
|
if (updateLibraryScanResult.IsFailure)
|
||||||
throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors);
|
throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors);
|
||||||
|
|
||||||
@@ -87,7 +84,7 @@ public class LibraryScanFailedDomainEventHandler : IDomainEventHandler<LibrarySc
|
|||||||
// release the scan processing resources, regardless of whether the scan was already marked as failed by a concurrent job
|
// release the scan processing resources, regardless of whether the scan was already marked as failed by a concurrent job
|
||||||
_mediaLibrariesScanCancellationTracker.RemoveScan(domainEvent.MediaLibraryScanCompositeId);
|
_mediaLibrariesScanCancellationTracker.RemoveScan(domainEvent.MediaLibraryScanCompositeId);
|
||||||
_mediaLibrariesScanProgressTracker.RemoveScanProgress(domainEvent.MediaLibraryScanCompositeId);
|
_mediaLibrariesScanProgressTracker.RemoveScanProgress(domainEvent.MediaLibraryScanCompositeId);
|
||||||
Result<Success> clearStagingResult = await stagingResultsRepository.ClearForScanAsync(domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
Result<Success> clearStagingResult = await _unitOfWork.LibraryScanStagingResultsRepository.ClearForScanAsync(domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (clearStagingResult.IsFailure)
|
if (clearStagingResult.IsFailure)
|
||||||
throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors);
|
throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors);
|
||||||
|
|
||||||
|
|||||||
+2
-4
@@ -54,10 +54,8 @@ public class LibraryScanFinishedDomainEventHandler : IDomainEventHandler<Library
|
|||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
public async ValueTask HandleAsync(LibraryScanFinishedDomainEvent domainEvent, CancellationToken cancellationToken)
|
public async ValueTask HandleAsync(LibraryScanFinishedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
|
||||||
|
|
||||||
// get the library scan from the repository
|
// get the library scan from the repository
|
||||||
Result<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(
|
Result<LibraryScanEntity?> getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(
|
||||||
domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibraryScansResult.IsFailure)
|
if (getLibraryScansResult.IsFailure)
|
||||||
throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors);
|
throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors);
|
||||||
@@ -75,7 +73,7 @@ public class LibraryScanFinishedDomainEventHandler : IDomainEventHandler<Library
|
|||||||
throw new EventualConsistencyException(finishScanResult.FirstError, finishScanResult.Errors);
|
throw new EventualConsistencyException(finishScanResult.FirstError, finishScanResult.Errors);
|
||||||
|
|
||||||
// update the library scan in the repository
|
// update the library scan in the repository
|
||||||
Result<Updated> updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
Result<Updated> updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||||
if (updateLibraryScanResult.IsFailure)
|
if (updateLibraryScanResult.IsFailure)
|
||||||
throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors);
|
throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors);
|
||||||
|
|
||||||
|
|||||||
+1
-3
@@ -48,10 +48,8 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler<LibrarySc
|
|||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
public async ValueTask HandleAsync(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken)
|
public async ValueTask HandleAsync(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
|
||||||
|
|
||||||
// get the library scan that was queued, from the repository
|
// get the library scan that was queued, from the repository
|
||||||
Result<LibraryScanEntity?> getLibraryScanResult = await libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
Result<LibraryScanEntity?> getLibraryScanResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibraryScanResult.IsFailure || getLibraryScanResult.Value is null)
|
if (getLibraryScanResult.IsFailure || getLibraryScanResult.Value is null)
|
||||||
throw new EventualConsistencyException(getLibraryScanResult.FirstError, getLibraryScanResult.Errors);
|
throw new EventualConsistencyException(getLibraryScanResult.FirstError, getLibraryScanResult.Errors);
|
||||||
|
|
||||||
|
|||||||
+1
-3
@@ -35,10 +35,8 @@ public class LibraryScanStartedDomainEventHandler : IDomainEventHandler<LibraryS
|
|||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
public async ValueTask HandleAsync(LibraryScanStartedDomainEvent domainEvent, CancellationToken cancellationToken)
|
public async ValueTask HandleAsync(LibraryScanStartedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
|
||||||
|
|
||||||
// update the status of the library scan in the repository
|
// update the status of the library scan in the repository
|
||||||
Result<Updated> updateLibraryScanResult = await libraryScanRepository.UpdateAsync(domainEvent.LibraryScan.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
Result<Updated> updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(domainEvent.LibraryScan.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||||
if (updateLibraryScanResult.IsFailure)
|
if (updateLibraryScanResult.IsFailure)
|
||||||
throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors);
|
throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors);
|
||||||
|
|
||||||
|
|||||||
+1
-2
@@ -52,8 +52,7 @@ public class GetEnabledLibrariesQueryHandler : IQueryHandler<GetEnabledLibraries
|
|||||||
public async Task<Result<LibraryResponse[]>> HandleAsync(GetEnabledLibrariesQuery query, CancellationToken cancellationToken)
|
public async Task<Result<LibraryResponse[]>> HandleAsync(GetEnabledLibrariesQuery query, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
// get the enabled libraries from the repository
|
// get the enabled libraries from the repository
|
||||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
Result<IEnumerable<LibraryEntity>> getEnabledLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAsync(cancellationToken).ConfigureAwait(false);
|
||||||
Result<IEnumerable<LibraryEntity>> getEnabledLibrariesResult = await libraryRepository.GetAllEnabledAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getEnabledLibrariesResult.IsFailure)
|
if (getEnabledLibrariesResult.IsFailure)
|
||||||
return getEnabledLibrariesResult.Errors;
|
return getEnabledLibrariesResult.Errors;
|
||||||
|
|
||||||
|
|||||||
+1
-2
@@ -52,8 +52,7 @@ public class GetLibrariesQueryHandler : IQueryHandler<GetLibrariesQuery, Result<
|
|||||||
public async Task<Result<LibraryResponse[]>> HandleAsync(GetLibrariesQuery query, CancellationToken cancellationToken)
|
public async Task<Result<LibraryResponse[]>> HandleAsync(GetLibrariesQuery query, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
// get the libraries from the repository
|
// get the libraries from the repository
|
||||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||||
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await libraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getLibrariesResult.IsFailure)
|
if (getLibrariesResult.IsFailure)
|
||||||
return getLibrariesResult.Errors;
|
return getLibrariesResult.Errors;
|
||||||
|
|
||||||
|
|||||||
+1
-2
@@ -63,8 +63,7 @@ public class GetLibraryQueryHandler : IQueryHandler<GetLibraryQuery, Result<Libr
|
|||||||
return validationResult;
|
return validationResult;
|
||||||
|
|
||||||
// get the library with the specified id from the repository
|
// get the library with the specified id from the repository
|
||||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false);
|
||||||
Result<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getLibraryResult.IsFailure)
|
if (getLibraryResult.IsFailure)
|
||||||
return getLibraryResult.Errors;
|
return getLibraryResult.Errors;
|
||||||
else if (getLibraryResult.Value is null)
|
else if (getLibraryResult.Value is null)
|
||||||
|
|||||||
+1
-2
@@ -70,8 +70,7 @@ public class GetLibraryScanProgressQueryHandler : IQueryHandler<GetLibraryScanPr
|
|||||||
return validationResult;
|
return validationResult;
|
||||||
|
|
||||||
// get the library with the specified id from the repository
|
// get the library with the specified id from the repository
|
||||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||||
Result<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getLibraryResult.IsFailure)
|
if (getLibraryResult.IsFailure)
|
||||||
return getLibraryResult.Errors;
|
return getLibraryResult.Errors;
|
||||||
else if (getLibraryResult.Value is null)
|
else if (getLibraryResult.Value is null)
|
||||||
|
|||||||
+1
-2
@@ -59,8 +59,7 @@ public class GetRunningLibraryScansQueryHandler : IQueryHandler<GetRunningLibrar
|
|||||||
public async Task<Result<IEnumerable<MediaLibraryScanProgressResponse>>> HandleAsync(GetRunningLibraryScansQuery query, CancellationToken cancellationToken)
|
public async Task<Result<IEnumerable<MediaLibraryScanProgressResponse>>> HandleAsync(GetRunningLibraryScansQuery query, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
// get the ongoing library scans from the repository
|
// get the ongoing library scans from the repository
|
||||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
Result<IEnumerable<LibraryScanEntity>> getRunningScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
|
||||||
Result<IEnumerable<LibraryScanEntity>> getRunningScansResult = await libraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getRunningScansResult.IsFailure)
|
if (getRunningScansResult.IsFailure)
|
||||||
return getRunningScansResult.Errors;
|
return getRunningScansResult.Errors;
|
||||||
|
|
||||||
|
|||||||
+1
-2
@@ -171,9 +171,8 @@ public class AddBookCommandHandler : ICommandHandler<AddBookCommand, Result<Book
|
|||||||
if (createBookResult.IsFailure)
|
if (createBookResult.IsFailure)
|
||||||
return createBookResult.Errors;
|
return createBookResult.Errors;
|
||||||
|
|
||||||
IBookRepository bookRepository = _unitOfWork.GetRepository<IBookRepository>();
|
|
||||||
BookEntity persistenceBook = createBookResult.Value.ToRepositoryEntity();
|
BookEntity persistenceBook = createBookResult.Value.ToRepositoryEntity();
|
||||||
Result<Created> insertBookResult = await bookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false);
|
Result<Created> insertBookResult = await _unitOfWork.BookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false);
|
||||||
if (insertBookResult.IsFailure)
|
if (insertBookResult.IsFailure)
|
||||||
return insertBookResult.Errors;
|
return insertBookResult.Errors;
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|||||||
+1
-3
@@ -39,10 +39,8 @@ public class GetBooksQueryHandler : IQueryHandler<GetBooksQuery, Result<IEnumera
|
|||||||
/// </returns>
|
/// </returns>
|
||||||
public async Task<Result<IEnumerable<BookResponse>>> HandleAsync(GetBooksQuery query, CancellationToken cancellationToken)
|
public async Task<Result<IEnumerable<BookResponse>>> HandleAsync(GetBooksQuery query, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
// get a books repository
|
|
||||||
IBookRepository bookRepository = _unitOfWork.GetRepository<IBookRepository>();
|
|
||||||
// get all books of the media library from the book repository
|
// get all books of the media library from the book repository
|
||||||
Result<IEnumerable<BookEntity>> getBooksResult = await bookRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<BookEntity>> getBooksResult = await _unitOfWork.BookRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||||
return getBooksResult.Match(result => Result.From(getBooksResult.Value.ToResponses()), errors => errors);
|
return getBooksResult.Match(result => Result.From(getBooksResult.Value.ToResponses()), errors => errors);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-3
@@ -47,8 +47,7 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler<Reo
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
return validationResult;
|
||||||
|
|
||||||
ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>();
|
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||||
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getConfigurationsResult.IsFailure)
|
if (getConfigurationsResult.IsFailure)
|
||||||
return getConfigurationsResult.Errors;
|
return getConfigurationsResult.Errors;
|
||||||
|
|
||||||
@@ -59,7 +58,7 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler<Reo
|
|||||||
if (configurationsByPluginId.TryGetValue(pluginId, out LibraryMetadataProviderConfigurationEntity? configuration))
|
if (configurationsByPluginId.TryGetValue(pluginId, out LibraryMetadataProviderConfigurationEntity? configuration))
|
||||||
{
|
{
|
||||||
configuration.Rank = rank + 1;
|
configuration.Rank = rank + 1;
|
||||||
Result<Updated> upsertResult = await configurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
Result<Updated> upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
||||||
if (upsertResult.IsFailure)
|
if (upsertResult.IsFailure)
|
||||||
return upsertResult.Errors;
|
return upsertResult.Errors;
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-4
@@ -47,8 +47,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler<S
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
return validationResult;
|
||||||
|
|
||||||
ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>();
|
Result<LibraryMetadataProviderConfigurationEntity?> getConfigurationResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false);
|
||||||
Result<LibraryMetadataProviderConfigurationEntity?> getConfigurationResult = await configurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getConfigurationResult.IsFailure)
|
if (getConfigurationResult.IsFailure)
|
||||||
return getConfigurationResult.Errors;
|
return getConfigurationResult.Errors;
|
||||||
|
|
||||||
@@ -61,7 +60,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler<S
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
// compute the rank to assign to the new configuration, appending it after the existing ones
|
// compute the rank to assign to the new configuration, appending it after the existing ones
|
||||||
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
|
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||||
if (getConfigurationsResult.IsFailure)
|
if (getConfigurationsResult.IsFailure)
|
||||||
return getConfigurationsResult.Errors;
|
return getConfigurationsResult.Errors;
|
||||||
int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1;
|
int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1;
|
||||||
@@ -78,7 +77,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler<S
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
Result<Updated> upsertResult = await configurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
Result<Updated> upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
||||||
if (upsertResult.IsFailure)
|
if (upsertResult.IsFailure)
|
||||||
return upsertResult.Errors;
|
return upsertResult.Errors;
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|||||||
+1
-2
@@ -45,9 +45,8 @@ public class UpdatePluginSettingsCommandHandler : ICommandHandler<UpdatePluginSe
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
return validationResult;
|
||||||
|
|
||||||
IPluginRepository pluginRepository = _unitOfWork.GetRepository<IPluginRepository>();
|
|
||||||
string? settingsJson = command.Settings is not null ? JsonSerializer.Serialize(command.Settings) : null;
|
string? settingsJson = command.Settings is not null ? JsonSerializer.Serialize(command.Settings) : null;
|
||||||
Result<Updated> updateResult = await pluginRepository.UpdateSettingsAsync(command.PluginId, settingsJson, cancellationToken).ConfigureAwait(false);
|
Result<Updated> updateResult = await _unitOfWork.PluginRepository.UpdateSettingsAsync(command.PluginId, settingsJson, cancellationToken).ConfigureAwait(false);
|
||||||
if (updateResult.IsFailure)
|
if (updateResult.IsFailure)
|
||||||
return updateResult.Errors;
|
return updateResult.Errors;
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|||||||
+2
-4
@@ -41,14 +41,12 @@ public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler<GetLibraryM
|
|||||||
/// </returns>
|
/// </returns>
|
||||||
public async Task<Result<IReadOnlyList<LibraryMetadataProviderResponse>>> HandleAsync(GetLibraryMetadataProvidersQuery query, CancellationToken cancellationToken)
|
public async Task<Result<IReadOnlyList<LibraryMetadataProviderResponse>>> HandleAsync(GetLibraryMetadataProvidersQuery query, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>();
|
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||||
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getConfigurationsResult.IsFailure)
|
if (getConfigurationsResult.IsFailure)
|
||||||
return getConfigurationsResult.Errors;
|
return getConfigurationsResult.Errors;
|
||||||
|
|
||||||
// build a plugin name lookup from the detected plugins
|
// build a plugin name lookup from the detected plugins
|
||||||
IPluginRepository pluginRepository = _unitOfWork.GetRepository<IPluginRepository>();
|
Result<IEnumerable<PluginEntity>> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||||
Result<IEnumerable<PluginEntity>> getPluginsResult = await pluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getPluginsResult.IsFailure)
|
if (getPluginsResult.IsFailure)
|
||||||
return getPluginsResult.Errors;
|
return getPluginsResult.Errors;
|
||||||
Dictionary<Guid, string> pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name);
|
Dictionary<Guid, string> pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name);
|
||||||
|
|||||||
+1
-2
@@ -46,8 +46,7 @@ public class GetPluginSettingsQueryHandler : IQueryHandler<GetPluginSettingsQuer
|
|||||||
/// </returns>
|
/// </returns>
|
||||||
public async Task<Result<PluginSettingsResponse>> HandleAsync(GetPluginSettingsQuery query, CancellationToken cancellationToken)
|
public async Task<Result<PluginSettingsResponse>> HandleAsync(GetPluginSettingsQuery query, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
IPluginRepository pluginRepository = _unitOfWork.GetRepository<IPluginRepository>();
|
Result<PluginEntity?> getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false);
|
||||||
Result<PluginEntity?> getPluginResult = await pluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getPluginResult.IsFailure)
|
if (getPluginResult.IsFailure)
|
||||||
return getPluginResult.Errors;
|
return getPluginResult.Errors;
|
||||||
PluginEntity? pluginEntity = getPluginResult.Value;
|
PluginEntity? pluginEntity = getPluginResult.Value;
|
||||||
|
|||||||
@@ -40,10 +40,7 @@ public class GetPluginsQueryHandler : IQueryHandler<GetPluginsQuery, Result<IRea
|
|||||||
/// </returns>
|
/// </returns>
|
||||||
public async Task<Result<IReadOnlyList<PluginResponse>>> HandleAsync(GetPluginsQuery query, CancellationToken cancellationToken)
|
public async Task<Result<IReadOnlyList<PluginResponse>>> HandleAsync(GetPluginsQuery query, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
IPluginRepository pluginRepository = _unitOfWork.GetRepository<IPluginRepository>();
|
Result<IEnumerable<PluginEntity>> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||||
Result<IEnumerable<PluginEntity>> getPluginsResult = await pluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
return getPluginsResult.Match(plugins => Result.From<IReadOnlyList<PluginResponse>>([.. plugins.Select(plugin => plugin.ToResponse())]), errors => errors);
|
||||||
return getPluginsResult.Match(
|
|
||||||
plugins => Result.From<IReadOnlyList<PluginResponse>>(plugins.Select(plugin => plugin.ToResponse()).ToList()),
|
|
||||||
errors => errors);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-3
@@ -55,8 +55,7 @@ public class ChangePasswordCommandHandler : ICommandHandler<ChangePasswordComman
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
return validationResult;
|
||||||
|
|
||||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
|
||||||
Result<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getUserResult.IsFailure)
|
if (getUserResult.IsFailure)
|
||||||
return getUserResult.Errors;
|
return getUserResult.Errors;
|
||||||
else if (getUserResult.Value is null)
|
else if (getUserResult.Value is null)
|
||||||
@@ -69,7 +68,7 @@ public class ChangePasswordCommandHandler : ICommandHandler<ChangePasswordComman
|
|||||||
getUserResult.Value.TempPassword = null;
|
getUserResult.Value.TempPassword = null;
|
||||||
getUserResult.Value.TempPasswordCreated = null;
|
getUserResult.Value.TempPasswordCreated = null;
|
||||||
// update the user
|
// update the user
|
||||||
Result<Updated> updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
|
Result<Updated> updateUserResult = await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (updateUserResult.IsFailure)
|
if (updateUserResult.IsFailure)
|
||||||
return updateUserResult.Errors;
|
return updateUserResult.Errors;
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|||||||
+2
-3
@@ -65,8 +65,7 @@ public class RecoverPasswordCommandHandler : ICommandHandler<RecoverPasswordComm
|
|||||||
return validationResult;
|
return validationResult;
|
||||||
|
|
||||||
// check if any users already exists
|
// check if any users already exists
|
||||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
|
||||||
Result<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getUserResult.IsFailure)
|
if (getUserResult.IsFailure)
|
||||||
return getUserResult.Errors;
|
return getUserResult.Errors;
|
||||||
else if (getUserResult.Value is null)
|
else if (getUserResult.Value is null)
|
||||||
@@ -86,7 +85,7 @@ public class RecoverPasswordCommandHandler : ICommandHandler<RecoverPasswordComm
|
|||||||
getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator
|
getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator
|
||||||
getUserResult.Value.TempPasswordCreated = DateTime.UtcNow;
|
getUserResult.Value.TempPasswordCreated = DateTime.UtcNow;
|
||||||
// update the user
|
// update the user
|
||||||
Result<Updated> updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
|
Result<Updated> updateUserResult = await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (updateUserResult.IsFailure)
|
if (updateUserResult.IsFailure)
|
||||||
return updateUserResult.Errors;
|
return updateUserResult.Errors;
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|||||||
+2
-3
@@ -74,8 +74,7 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
|
|||||||
return validationResult;
|
return validationResult;
|
||||||
|
|
||||||
// check if any users already exists (admin account is only set once!)
|
// check if any users already exists (admin account is only set once!)
|
||||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
|
||||||
Result<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getUserResult.IsFailure)
|
if (getUserResult.IsFailure)
|
||||||
return getUserResult.Errors;
|
return getUserResult.Errors;
|
||||||
else if (getUserResult.Value is not null)
|
else if (getUserResult.Value is not null)
|
||||||
@@ -105,7 +104,7 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
|
|||||||
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
|
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
|
||||||
}
|
}
|
||||||
// insert the user
|
// insert the user
|
||||||
Result<Created> insertUserResult = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
|
Result<Created> insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
|
||||||
if (insertUserResult.IsFailure)
|
if (insertUserResult.IsFailure)
|
||||||
return insertUserResult.Errors;
|
return insertUserResult.Errors;
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|||||||
+3
-3
@@ -22,9 +22,9 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUser
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class GetUsersQueryHandler : IQueryHandler<GetUsersQuery, Result<IEnumerable<UserResponse>>>
|
public class GetUsersQueryHandler : IQueryHandler<GetUsersQuery, Result<IEnumerable<UserResponse>>>
|
||||||
{
|
{
|
||||||
|
private readonly IUnitOfWork _unitOfWork;
|
||||||
private readonly ICurrentUserService _currentUserService;
|
private readonly ICurrentUserService _currentUserService;
|
||||||
private readonly IAuthorizationService _authorizationService;
|
private readonly IAuthorizationService _authorizationService;
|
||||||
private readonly IUserRepository _userRepository;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Initializes a new instance of the <see cref="GetUsersQueryHandler"/> class.
|
/// Initializes a new instance of the <see cref="GetUsersQueryHandler"/> class.
|
||||||
@@ -36,7 +36,7 @@ public class GetUsersQueryHandler : IQueryHandler<GetUsersQuery, Result<IEnumera
|
|||||||
{
|
{
|
||||||
_authorizationService = authorizationService;
|
_authorizationService = authorizationService;
|
||||||
_currentUserService = currentUserService;
|
_currentUserService = currentUserService;
|
||||||
_userRepository = unitOfWork.GetRepository<IUserRepository>();
|
_unitOfWork = unitOfWork;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -53,7 +53,7 @@ public class GetUsersQueryHandler : IQueryHandler<GetUsersQuery, Result<IEnumera
|
|||||||
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
||||||
if (!isAdmin)
|
if (!isAdmin)
|
||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
Result<IEnumerable<UserEntity>> getRolesResult = await _userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<UserEntity>> getRolesResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||||
return getRolesResult.Match(value => Result.From(value.ToResponses()), errors => errors);
|
return getRolesResult.Match(value => Result.From(value.ToResponses()), errors => errors);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-3
@@ -74,8 +74,7 @@ public class LoginUserQueryHandler : IQueryHandler<LoginUserQuery, Result<LoginR
|
|||||||
return validationResult;
|
return validationResult;
|
||||||
|
|
||||||
// check if any users already exists
|
// check if any users already exists
|
||||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(query.Username!, cancellationToken).ConfigureAwait(false);
|
||||||
Result<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(query.Username!, cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getUserResult.IsFailure)
|
if (getUserResult.IsFailure)
|
||||||
return getUserResult.Errors;
|
return getUserResult.Errors;
|
||||||
else if (getUserResult.Value is null)
|
else if (getUserResult.Value is null)
|
||||||
@@ -91,7 +90,7 @@ public class LoginUserQueryHandler : IQueryHandler<LoginUserQuery, Result<LoginR
|
|||||||
{
|
{
|
||||||
getUserResult.Value.TempPassword = null;
|
getUserResult.Value.TempPassword = null;
|
||||||
getUserResult.Value.TempPasswordCreated = null;
|
getUserResult.Value.TempPasswordCreated = null;
|
||||||
await userRepository.UpdateAsync(getUserResult.Value, cancellationToken);
|
await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken);
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||||
return Errors.Authentication.TempPasswordExpired;
|
return Errors.Authentication.TempPasswordExpired;
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-12
@@ -65,13 +65,8 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
|
|||||||
if (!isAdmin)
|
if (!isAdmin)
|
||||||
return ApplicationErrors.Authorization.NotAuthorized;
|
return ApplicationErrors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
// get repositories
|
|
||||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
|
||||||
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
|
|
||||||
IPermissionRepository permissionRepository = _unitOfWork.GetRepository<IPermissionRepository>();
|
|
||||||
|
|
||||||
// get the user to update
|
// get the user to update
|
||||||
Result<UserEntity?> getUserResult = await userRepository.GetByIdAsync(command.UserId, cancellationToken).ConfigureAwait(false);
|
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(command.UserId, cancellationToken).ConfigureAwait(false);
|
||||||
if (getUserResult.IsFailure || getUserResult.Value is null)
|
if (getUserResult.IsFailure || getUserResult.Value is null)
|
||||||
return DomainErrors.Users.UserDoesNotExist;
|
return DomainErrors.Users.UserDoesNotExist;
|
||||||
|
|
||||||
@@ -79,7 +74,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
|
|||||||
if (command.RoleId is not null)
|
if (command.RoleId is not null)
|
||||||
{
|
{
|
||||||
// get the new role
|
// get the new role
|
||||||
getRoleResult = await roleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken).ConfigureAwait(false);
|
getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getRoleResult.IsFailure || getRoleResult.Value is null)
|
if (getRoleResult.IsFailure || getRoleResult.Value is null)
|
||||||
return ApplicationErrors.Authorization.RoleNotFound;
|
return ApplicationErrors.Authorization.RoleNotFound;
|
||||||
|
|
||||||
@@ -87,7 +82,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
|
|||||||
if (getUserResult.Value.UserRole?.Role.RoleName == "Admin" && getRoleResult.Value.RoleName != "Admin")
|
if (getUserResult.Value.UserRole?.Role.RoleName == "Admin" && getRoleResult.Value.RoleName != "Admin")
|
||||||
{
|
{
|
||||||
// count how many admins we have
|
// count how many admins we have
|
||||||
Result<IEnumerable<UserEntity>> getAllUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<UserEntity>> getAllUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||||
if (getAllUsersResult.IsFailure)
|
if (getAllUsersResult.IsFailure)
|
||||||
return getAllUsersResult.Errors;
|
return getAllUsersResult.Errors;
|
||||||
|
|
||||||
@@ -98,7 +93,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
|
|||||||
}
|
}
|
||||||
// get the permissions to assign
|
// get the permissions to assign
|
||||||
Result<IEnumerable<PermissionEntity>> getPermissionsResult =
|
Result<IEnumerable<PermissionEntity>> getPermissionsResult =
|
||||||
await permissionRepository.GetByIdsAsync(command.Permissions, cancellationToken).ConfigureAwait(false);
|
await _unitOfWork.PermissionRepository.GetByIdsAsync(command.Permissions, cancellationToken).ConfigureAwait(false);
|
||||||
if (getPermissionsResult.IsFailure)
|
if (getPermissionsResult.IsFailure)
|
||||||
return getPermissionsResult.Errors;
|
return getPermissionsResult.Errors;
|
||||||
|
|
||||||
@@ -127,18 +122,18 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
|
|||||||
TempPasswordCreated = userToUpdate.TempPasswordCreated,
|
TempPasswordCreated = userToUpdate.TempPasswordCreated,
|
||||||
Libraries = userToUpdate.Libraries,
|
Libraries = userToUpdate.Libraries,
|
||||||
UserRole = userRole,
|
UserRole = userRole,
|
||||||
UserPermissions = command.Permissions.Select(permissionId => new UserPermissionEntity
|
UserPermissions = [.. command.Permissions.Select(permissionId => new UserPermissionEntity
|
||||||
{
|
{
|
||||||
UserId = userToUpdate.Id,
|
UserId = userToUpdate.Id,
|
||||||
PermissionId = permissionId,
|
PermissionId = permissionId,
|
||||||
Permission = getPermissionsResult.Value.First(permission => permission.Id == permissionId),
|
Permission = getPermissionsResult.Value.First(permission => permission.Id == permissionId),
|
||||||
User = userToUpdate
|
User = userToUpdate
|
||||||
}).ToList(),
|
})],
|
||||||
LibraryScans = userToUpdate.LibraryScans
|
LibraryScans = userToUpdate.LibraryScans
|
||||||
};
|
};
|
||||||
|
|
||||||
// save changes and return result
|
// save changes and return result
|
||||||
Result<Updated> updateResult = await userRepository.UpdateAsync(updatedUser, cancellationToken).ConfigureAwait(false);
|
Result<Updated> updateResult = await _unitOfWork.UserRepository.UpdateAsync(updatedUser, cancellationToken).ConfigureAwait(false);
|
||||||
if (updateResult.IsFailure)
|
if (updateResult.IsFailure)
|
||||||
return updateResult.Errors;
|
return updateResult.Errors;
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -23,9 +23,9 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserP
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class GetUserPermissionsQueryHandler : IQueryHandler<GetUserPermissionsQuery, Result<IEnumerable<PermissionResponse>>>
|
public class GetUserPermissionsQueryHandler : IQueryHandler<GetUserPermissionsQuery, Result<IEnumerable<PermissionResponse>>>
|
||||||
{
|
{
|
||||||
|
private readonly IUnitOfWork _unitOfWork;
|
||||||
private readonly ICurrentUserService _currentUserService;
|
private readonly ICurrentUserService _currentUserService;
|
||||||
private readonly IAuthorizationService _authorizationService;
|
private readonly IAuthorizationService _authorizationService;
|
||||||
private readonly IUserRepository _userRepository;
|
|
||||||
private readonly IValidator<GetUserPermissionsQuery> _validator;
|
private readonly IValidator<GetUserPermissionsQuery> _validator;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -39,7 +39,7 @@ public class GetUserPermissionsQueryHandler : IQueryHandler<GetUserPermissionsQu
|
|||||||
{
|
{
|
||||||
_authorizationService = authorizationService;
|
_authorizationService = authorizationService;
|
||||||
_currentUserService = currentUserService;
|
_currentUserService = currentUserService;
|
||||||
_userRepository = unitOfWork.GetRepository<IUserRepository>();
|
_unitOfWork = unitOfWork;
|
||||||
_validator = validator;
|
_validator = validator;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,7 +62,7 @@ public class GetUserPermissionsQueryHandler : IQueryHandler<GetUserPermissionsQu
|
|||||||
if (!isAdmin)
|
if (!isAdmin)
|
||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
// get the user from the repository and return its permissions
|
// get the user from the repository and return its permissions
|
||||||
Result<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false);
|
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getUserResult.IsFailure)
|
if (getUserResult.IsFailure)
|
||||||
return getUserResult.Errors;
|
return getUserResult.Errors;
|
||||||
else if (getUserResult.Value is null)
|
else if (getUserResult.Value is null)
|
||||||
|
|||||||
+3
-3
@@ -22,9 +22,9 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserR
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class GetUserRoleQueryHandler : IQueryHandler<GetUserRoleQuery, Result<RoleResponse?>>
|
public class GetUserRoleQueryHandler : IQueryHandler<GetUserRoleQuery, Result<RoleResponse?>>
|
||||||
{
|
{
|
||||||
|
private readonly IUnitOfWork _unitOfWork;
|
||||||
private readonly ICurrentUserService _currentUserService;
|
private readonly ICurrentUserService _currentUserService;
|
||||||
private readonly IAuthorizationService _authorizationService;
|
private readonly IAuthorizationService _authorizationService;
|
||||||
private readonly IUserRepository _userRepository;
|
|
||||||
private readonly IValidator<GetUserRoleQuery> _validator;
|
private readonly IValidator<GetUserRoleQuery> _validator;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -38,7 +38,7 @@ public class GetUserRoleQueryHandler : IQueryHandler<GetUserRoleQuery, Result<Ro
|
|||||||
{
|
{
|
||||||
_authorizationService = authorizationService;
|
_authorizationService = authorizationService;
|
||||||
_currentUserService = currentUserService;
|
_currentUserService = currentUserService;
|
||||||
_userRepository = unitOfWork.GetRepository<IUserRepository>();
|
_unitOfWork = unitOfWork;
|
||||||
_validator = validator;
|
_validator = validator;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,7 +61,7 @@ public class GetUserRoleQueryHandler : IQueryHandler<GetUserRoleQuery, Result<Ro
|
|||||||
if (!isAdmin)
|
if (!isAdmin)
|
||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
// get the user from the repository and return its roles
|
// get the user from the repository and return its roles
|
||||||
Result<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false);
|
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getUserResult.IsFailure)
|
if (getUserResult.IsFailure)
|
||||||
return getUserResult.Errors;
|
return getUserResult.Errors;
|
||||||
else if (getUserResult.Value is null)
|
else if (getUserResult.Value is null)
|
||||||
|
|||||||
@@ -1,18 +1,14 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
|
||||||
using Lumina.Application.Common.DataAccess.Seed;
|
using Lumina.Application.Common.DataAccess.Seed;
|
||||||
using Lumina.Application.Common.DataAccess.UoW;
|
using Lumina.Application.Common.DataAccess.UoW;
|
||||||
using Lumina.DataAccess.Common.Interceptors;
|
using Lumina.DataAccess.Common.Interceptors;
|
||||||
using Lumina.DataAccess.Core.Repositories.Common.Factory;
|
|
||||||
using Lumina.DataAccess.Core.Seed;
|
using Lumina.DataAccess.Core.Seed;
|
||||||
using Lumina.DataAccess.Core.UoW;
|
using Lumina.DataAccess.Core.UoW;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
@@ -41,28 +37,6 @@ public static class DataAccessLayerServices
|
|||||||
});
|
});
|
||||||
services.AddScoped<IUnitOfWork, UnitOfWork>();
|
services.AddScoped<IUnitOfWork, UnitOfWork>();
|
||||||
services.AddScoped<UpdateAuditableEntitiesInterceptor>();
|
services.AddScoped<UpdateAuditableEntitiesInterceptor>();
|
||||||
|
|
||||||
Type[]? dataAccessLayerTypes = Assembly.GetExecutingAssembly().GetTypes();
|
|
||||||
Type? genericRepositoryType = typeof(IRepository<>);
|
|
||||||
Type? repositoryFactoryType = typeof(RepositoryFactory);
|
|
||||||
Type? iRepositoryFactoryType = typeof(IRepositoryFactory);
|
|
||||||
|
|
||||||
services.AddScoped(iRepositoryFactoryType!, repositoryFactoryType!);
|
|
||||||
|
|
||||||
// get all classes implementing IRepository (all repository classes) and register them as their corresponding repository interface
|
|
||||||
IEnumerable<Type> repositoryTypes = dataAccessLayerTypes.Where(type => !type.IsInterface &&
|
|
||||||
type.GetInterfaces()
|
|
||||||
.Any(type => type.IsGenericType &&
|
|
||||||
type.GetGenericTypeDefinition() == genericRepositoryType));
|
|
||||||
foreach (Type type in repositoryTypes)
|
|
||||||
{
|
|
||||||
services.AddScoped(type.GetInterfaces() // TODO: change to scoped when DbContext is implemented
|
|
||||||
.Where(type => !type.IsGenericType &&
|
|
||||||
type.GetInterfaces()
|
|
||||||
.Any(type => type.GetGenericTypeDefinition() == genericRepositoryType))
|
|
||||||
.First(), type);
|
|
||||||
}
|
|
||||||
|
|
||||||
services.AddScoped<IDataSeedService, DataSeedService>();
|
services.AddScoped<IDataSeedService, DataSeedService>();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
namespace Lumina.DataAccess.Core.Repositories.Common.Factory;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Interface for the repositories factory.
|
|
||||||
/// </summary>
|
|
||||||
public interface IRepositoryFactory
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Creates a new repository of type <typeparamref name="TRepository"/>.
|
|
||||||
/// </summary>
|
|
||||||
/// <typeparam name="TRepository">The type of repository to create.</typeparam>
|
|
||||||
/// <returns>A repository of type <typeparamref name="TRepository"/>.</returns>
|
|
||||||
/// <exception cref="ArgumentException">Thrown when the type of the requested repository has not been registered.</exception>
|
|
||||||
TRepository CreateRepository<TRepository>() where TRepository : notnull;
|
|
||||||
}
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
|
||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
namespace Lumina.DataAccess.Core.Repositories.Common.Factory;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Custom collection for storing repositories.
|
|
||||||
/// </summary>
|
|
||||||
public class RepositoryDictionary
|
|
||||||
{
|
|
||||||
private readonly List<KeyValuePair<Type, object>> _container = [];
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets the number of added repositories.
|
|
||||||
/// </summary>
|
|
||||||
public int Count => _container.Count;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Resets the collection of repositories.
|
|
||||||
/// </summary>
|
|
||||||
public void Clear()
|
|
||||||
{
|
|
||||||
_container.Clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Adds a repository of type <typeparamref name="TParam"/> to the collection.
|
|
||||||
/// </summary>
|
|
||||||
/// <typeparam name="TParam">The type of the repository to add to the collection.</typeparam>
|
|
||||||
/// <param name="value">The repository to add.</param>
|
|
||||||
public void Add<TParam>(TParam value) where TParam : notnull
|
|
||||||
{
|
|
||||||
// enforce adding rules
|
|
||||||
if (value == null)
|
|
||||||
throw new ArgumentException("Value cannot be null!");
|
|
||||||
if (_container.Any(e => e.Key == value.GetType()))
|
|
||||||
throw new ArgumentException("Duplicate values are not allowed!");
|
|
||||||
// check if the value implements an interface that implements IRepository
|
|
||||||
bool implementsRepository = value.GetType()
|
|
||||||
.GetInterfaces()
|
|
||||||
.Any(e => e.GetInterfaces()
|
|
||||||
.Any(i => i.IsGenericType &&
|
|
||||||
i.GetGenericTypeDefinition() == typeof(IRepository<>)));
|
|
||||||
if (implementsRepository)
|
|
||||||
_container.Add(new KeyValuePair<Type, object>(value.GetType(), value));
|
|
||||||
else
|
|
||||||
throw new ArgumentException("Value must implement IRepository interface!");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets a repository of type <typeparamref name="TResult"/> from the collection.
|
|
||||||
/// </summary>
|
|
||||||
/// <typeparam name="TResult">The type of the repository interface to get from the collection.</typeparam>
|
|
||||||
/// <param name="key">The concrete type of the repository interface to get.</param>
|
|
||||||
/// <returns>A repository implementing <typeparamref name="TResult"/>.</returns>
|
|
||||||
public TResult Get<TResult>(Type key)
|
|
||||||
{
|
|
||||||
return (TResult)_container.FirstOrDefault(e => e.Key == key).Value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using System;
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
namespace Lumina.DataAccess.Core.Repositories.Common.Factory;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Concrete implementation for the repositories factory.
|
|
||||||
/// </summary>
|
|
||||||
public class RepositoryFactory : IRepositoryFactory
|
|
||||||
{
|
|
||||||
private readonly IServiceProvider _serviceProvider;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Initializes a new instance of the <see cref="RepositoryFactory"/> class.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="serviceProvider">The service provider.</param>
|
|
||||||
public RepositoryFactory(IServiceProvider serviceProvider)
|
|
||||||
{
|
|
||||||
_serviceProvider = serviceProvider;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Creates a new repository of type <typeparamref name="TRepository"/>.
|
|
||||||
/// </summary>
|
|
||||||
/// <typeparam name="TRepository">The type of repository to create.</typeparam>
|
|
||||||
/// <returns>A repository of type <typeparamref name="TRepository"/>.</returns>
|
|
||||||
/// <exception cref="ArgumentException">Thrown when the type of the requested repository has not been registered.</exception>
|
|
||||||
public TRepository CreateRepository<TRepository>() where TRepository : notnull
|
|
||||||
{
|
|
||||||
return _serviceProvider.GetRequiredService<TRepository>() ?? throw new ArgumentException();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -44,7 +44,6 @@ public class DataSeedService : IDataSeedService
|
|||||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||||
public async Task<Result<Created>> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken)
|
public async Task<Result<Created>> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
IPermissionRepository permissionRepository = _unitOfWork.GetRepository<IPermissionRepository>();
|
|
||||||
// create the default authorization permissions and add them to the repository.
|
// create the default authorization permissions and add them to the repository.
|
||||||
PermissionEntity[] defaultPermissions =
|
PermissionEntity[] defaultPermissions =
|
||||||
[
|
[
|
||||||
@@ -55,7 +54,7 @@ public class DataSeedService : IDataSeedService
|
|||||||
];
|
];
|
||||||
foreach (PermissionEntity permission in defaultPermissions)
|
foreach (PermissionEntity permission in defaultPermissions)
|
||||||
{
|
{
|
||||||
Result<Created> insertPermissionResult = await permissionRepository.InsertAsync(permission, cancellationToken).ConfigureAwait(false);
|
Result<Created> insertPermissionResult = await _unitOfWork.PermissionRepository.InsertAsync(permission, cancellationToken).ConfigureAwait(false);
|
||||||
if (insertPermissionResult.IsFailure)
|
if (insertPermissionResult.IsFailure)
|
||||||
return insertPermissionResult.Errors;
|
return insertPermissionResult.Errors;
|
||||||
}
|
}
|
||||||
@@ -71,8 +70,6 @@ public class DataSeedService : IDataSeedService
|
|||||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||||
public async Task<Result<Created>> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken)
|
public async Task<Result<Created>> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
|
|
||||||
|
|
||||||
// create the default authorization roles and add them to the repository
|
// create the default authorization roles and add them to the repository
|
||||||
RoleEntity[] defaultRoles =
|
RoleEntity[] defaultRoles =
|
||||||
[
|
[
|
||||||
@@ -80,7 +77,7 @@ public class DataSeedService : IDataSeedService
|
|||||||
];
|
];
|
||||||
foreach (RoleEntity role in defaultRoles)
|
foreach (RoleEntity role in defaultRoles)
|
||||||
{
|
{
|
||||||
Result<Created> insertRoleResult = await roleRepository.InsertAsync(role, cancellationToken).ConfigureAwait(false);
|
Result<Created> insertRoleResult = await _unitOfWork.RoleRepository.InsertAsync(role, cancellationToken).ConfigureAwait(false);
|
||||||
if (insertRoleResult.IsFailure)
|
if (insertRoleResult.IsFailure)
|
||||||
return insertRoleResult.Errors;
|
return insertRoleResult.Errors;
|
||||||
}
|
}
|
||||||
@@ -96,12 +93,8 @@ public class DataSeedService : IDataSeedService
|
|||||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||||
public async Task<Result<Created>> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken)
|
public async Task<Result<Created>> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
IRolePermissionRepository rolePermissionRepository = _unitOfWork.GetRepository<IRolePermissionRepository>();
|
|
||||||
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
|
|
||||||
IPermissionRepository permissionRepository = _unitOfWork.GetRepository<IPermissionRepository>();
|
|
||||||
|
|
||||||
// get the admin role
|
// get the admin role
|
||||||
Result<RoleEntity?> getAdminRoleResult = await roleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false);
|
Result<RoleEntity?> getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false);
|
||||||
if (getAdminRoleResult.IsFailure)
|
if (getAdminRoleResult.IsFailure)
|
||||||
return getAdminRoleResult.Errors;
|
return getAdminRoleResult.Errors;
|
||||||
|
|
||||||
@@ -109,7 +102,7 @@ public class DataSeedService : IDataSeedService
|
|||||||
return Errors.Authorization.AdminAccountNotFound;
|
return Errors.Authorization.AdminAccountNotFound;
|
||||||
|
|
||||||
// get all permissions
|
// get all permissions
|
||||||
Result<IEnumerable<PermissionEntity>> getPermissionsResult = await permissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<PermissionEntity>> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||||
if (getPermissionsResult.IsFailure)
|
if (getPermissionsResult.IsFailure)
|
||||||
return getPermissionsResult.Errors;
|
return getPermissionsResult.Errors;
|
||||||
|
|
||||||
@@ -125,7 +118,7 @@ public class DataSeedService : IDataSeedService
|
|||||||
CreatedBy = userId,
|
CreatedBy = userId,
|
||||||
CreatedOnUtc = _dateTimeProvider.UtcNow
|
CreatedOnUtc = _dateTimeProvider.UtcNow
|
||||||
};
|
};
|
||||||
Result<Created> insertRolePermissionResult = await rolePermissionRepository.InsertAsync(rolePermissionEntity, cancellationToken).ConfigureAwait(false);
|
Result<Created> insertRolePermissionResult = await _unitOfWork.RolePermissionRepository.InsertAsync(rolePermissionEntity, cancellationToken).ConfigureAwait(false);
|
||||||
if (insertRolePermissionResult.IsFailure)
|
if (insertRolePermissionResult.IsFailure)
|
||||||
return insertRolePermissionResult.Errors;
|
return insertRolePermissionResult.Errors;
|
||||||
}
|
}
|
||||||
@@ -141,13 +134,8 @@ public class DataSeedService : IDataSeedService
|
|||||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||||
public async Task<Result<Created>> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken)
|
public async Task<Result<Created>> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
IUserRoleRepository userRoleRepository = _unitOfWork.GetRepository<IUserRoleRepository>();
|
|
||||||
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
|
|
||||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
|
||||||
|
|
||||||
|
|
||||||
// get the admin role
|
// get the admin role
|
||||||
Result<RoleEntity?> getAdminRoleResult = await roleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false);
|
Result<RoleEntity?> getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false);
|
||||||
if (getAdminRoleResult.IsFailure)
|
if (getAdminRoleResult.IsFailure)
|
||||||
return getAdminRoleResult.Errors;
|
return getAdminRoleResult.Errors;
|
||||||
|
|
||||||
@@ -155,7 +143,7 @@ public class DataSeedService : IDataSeedService
|
|||||||
return Errors.Authorization.AdminRoleNotFound;
|
return Errors.Authorization.AdminRoleNotFound;
|
||||||
|
|
||||||
// get admin user
|
// get admin user
|
||||||
Result<UserEntity?> getUserResult = await userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||||
if (getUserResult.IsFailure)
|
if (getUserResult.IsFailure)
|
||||||
return getUserResult.Errors;
|
return getUserResult.Errors;
|
||||||
|
|
||||||
@@ -172,7 +160,7 @@ public class DataSeedService : IDataSeedService
|
|||||||
User = getUserResult.Value,
|
User = getUserResult.Value,
|
||||||
UserId = getUserResult.Value.Id
|
UserId = getUserResult.Value.Id
|
||||||
};
|
};
|
||||||
Result<Created> insertUserRoleResult = await userRoleRepository.InsertAsync(userRole, cancellationToken).ConfigureAwait(false);
|
Result<Created> insertUserRoleResult = await _unitOfWork.UserRoleRepository.InsertAsync(userRole, cancellationToken).ConfigureAwait(false);
|
||||||
if (insertUserRoleResult.IsFailure)
|
if (insertUserRoleResult.IsFailure)
|
||||||
return insertUserRoleResult.Errors;
|
return insertUserRoleResult.Errors;
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||||
|
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||||
|
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||||
|
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||||
|
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||||
using Lumina.Application.Common.DataAccess.UoW;
|
using Lumina.Application.Common.DataAccess.UoW;
|
||||||
using Lumina.DataAccess.Core.Repositories.Common.Factory;
|
using Lumina.DataAccess.Core.Repositories.Authorization;
|
||||||
|
using Lumina.DataAccess.Core.Repositories.Books;
|
||||||
|
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||||
|
using Lumina.DataAccess.Core.Repositories.Plugins;
|
||||||
|
using Lumina.DataAccess.Core.Repositories.Users;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Reflection;
|
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
#endregion
|
#endregion
|
||||||
@@ -15,79 +21,188 @@ namespace Lumina.DataAccess.Core.UoW;
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Interaction boundary with the Data Access Layer.
|
/// Interaction boundary with the Data Access Layer.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class UnitOfWork : IUnitOfWork
|
public class UnitOfWork : IUnitOfWork, IDisposable
|
||||||
{
|
{
|
||||||
private readonly LuminaDbContext _luminaDbContext;
|
private readonly LuminaDbContext _luminaDbContext;
|
||||||
private readonly IRepositoryFactory _repositoryFactory;
|
private IDbContextTransaction? _transaction;
|
||||||
|
|
||||||
|
private IPermissionRepository? _permissionRepository;
|
||||||
|
private IRolePermissionRepository? _rolePermissionRepository;
|
||||||
|
private IRoleRepository? _roleRepository;
|
||||||
|
private IUserRoleRepository? _userRoleRepository;
|
||||||
|
private IBookRepository? _bookRepository;
|
||||||
|
private IDirectoryScanFingerprintRepository? _directoryScanFingerprintRepository;
|
||||||
|
private ILibraryRepository? _libraryRepository;
|
||||||
|
private ILibraryScanRepository? _libraryScanRepository;
|
||||||
|
private ILibraryScanSnapshotRepository? _libraryScanSnapshotRepository;
|
||||||
|
private ILibraryScanStagingResultsRepository? _libraryScanStagingResultsRepository;
|
||||||
|
private ILibraryMetadataProviderConfigurationRepository? _libraryMetadataProviderConfigurationRepository;
|
||||||
|
private IPluginRepository? _pluginRepository;
|
||||||
|
private IUserRepository? _userRepository;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets the collection of available repositories.
|
/// Gets the permission repository.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal RepositoryDictionary Repositories { get; private set; } = new RepositoryDictionary();
|
public IPermissionRepository PermissionRepository
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Initializes a new instance of the <see cref="UnitOfWork"/> class.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="repositoryFactory">The factory used to generate repositories.</param>
|
|
||||||
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
|
|
||||||
public UnitOfWork(IRepositoryFactory repositoryFactory, LuminaDbContext luminaDbContext)
|
|
||||||
{
|
{
|
||||||
_repositoryFactory = repositoryFactory;
|
get
|
||||||
_luminaDbContext = luminaDbContext;
|
|
||||||
AddRepositories();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Adds all the repositories from the Data Access Layer so that they can be exposed to the Business Layer.
|
|
||||||
/// </summary>
|
|
||||||
internal void AddRepositories()
|
|
||||||
{
|
|
||||||
// get all the concrete implementations of IRepository<>
|
|
||||||
IEnumerable<Type> repositoryClassTypes =
|
|
||||||
Assembly.GetExecutingAssembly()
|
|
||||||
.GetTypes()
|
|
||||||
.Where(t => !t.IsInterface && !t.IsAbstract && t.GetInterfaces()
|
|
||||||
.Any(i => i.IsGenericType &&
|
|
||||||
i.GetGenericTypeDefinition() == typeof(IRepository<>)));
|
|
||||||
// store all repositories
|
|
||||||
foreach (Type repositoryClassType in repositoryClassTypes)
|
|
||||||
{
|
{
|
||||||
// get the interface that implements IRepository<> of the currently iterated repository class
|
_permissionRepository ??= new PermissionRepository(_luminaDbContext);
|
||||||
Type repositoryInterfaceType = repositoryClassType.GetInterfaces()
|
return _permissionRepository;
|
||||||
.Where(i => !i.IsGenericType &&
|
|
||||||
i.GetInterfaces()
|
|
||||||
.Any(a => a.GetGenericTypeDefinition() == typeof(IRepository<>)))
|
|
||||||
.First();
|
|
||||||
// ask the concrete type for the repository interface type from the repositories factory;
|
|
||||||
// because the method for creating a repository is generic and we need to call it with a runtime type, reflection is the only option
|
|
||||||
object repositoryClass = typeof(IRepositoryFactory).GetMethod("CreateRepository")!
|
|
||||||
.MakeGenericMethod(repositoryInterfaceType)
|
|
||||||
.Invoke(_repositoryFactory, null)!;
|
|
||||||
Repositories.Add(repositoryClass);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Exposes a repository of type <typeparamref name="TRepository"/> to the Business Logic Layer.
|
/// Gets the role permission repository.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="TRepository">The type of the exposed repository.</typeparam>
|
public IRolePermissionRepository RolePermissionRepository
|
||||||
/// <returns>A repository of type <typeparamref name="TRepository"/>.</returns>
|
|
||||||
public TRepository GetRepository<TRepository>()
|
|
||||||
{
|
{
|
||||||
// get the repository type based on the type of the provided repository interface
|
get
|
||||||
Type repositoryType = Assembly.GetExecutingAssembly()
|
{
|
||||||
.GetTypes()
|
_rolePermissionRepository ??= new RolePermissionRepository(_luminaDbContext);
|
||||||
.Where(type => !type.IsInterface && !type.IsAbstract && typeof(TRepository).IsAssignableFrom(type))
|
return _rolePermissionRepository;
|
||||||
.First();
|
}
|
||||||
return Repositories.Get<TRepository>(repositoryType);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Resets the list of repositories.
|
/// Gets the role repository.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal void ResetRepositories()
|
public IRoleRepository RoleRepository
|
||||||
{
|
{
|
||||||
Repositories.Clear();
|
get
|
||||||
|
{
|
||||||
|
_roleRepository ??= new RoleRepository(_luminaDbContext);
|
||||||
|
return _roleRepository;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the user role repository.
|
||||||
|
/// </summary>
|
||||||
|
public IUserRoleRepository UserRoleRepository
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_userRoleRepository ??= new UserRoleRepository(_luminaDbContext);
|
||||||
|
return _userRoleRepository;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the book repository.
|
||||||
|
/// </summary>
|
||||||
|
public IBookRepository BookRepository
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_bookRepository ??= new BookRepository(_luminaDbContext);
|
||||||
|
return _bookRepository;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the directory scan fingerprint repository.
|
||||||
|
/// </summary>
|
||||||
|
public IDirectoryScanFingerprintRepository DirectoryScanFingerprintRepository
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_directoryScanFingerprintRepository ??= new DirectoryScanFingerprintRepository(_luminaDbContext);
|
||||||
|
return _directoryScanFingerprintRepository;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the library repository.
|
||||||
|
/// </summary>
|
||||||
|
public ILibraryRepository LibraryRepository
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_libraryRepository ??= new LibraryRepository(_luminaDbContext);
|
||||||
|
return _libraryRepository;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the library scan repository.
|
||||||
|
/// </summary>
|
||||||
|
public ILibraryScanRepository LibraryScanRepository
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_libraryScanRepository ??= new LibraryScanRepository(_luminaDbContext);
|
||||||
|
return _libraryScanRepository;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the library scan snapshot repository.
|
||||||
|
/// </summary>
|
||||||
|
public ILibraryScanSnapshotRepository LibraryScanSnapshotRepository
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_libraryScanSnapshotRepository ??= new LibraryScanSnapshotRepository(_luminaDbContext);
|
||||||
|
return _libraryScanSnapshotRepository;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the library scan staging results repository.
|
||||||
|
/// </summary>
|
||||||
|
public ILibraryScanStagingResultsRepository LibraryScanStagingResultsRepository
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_libraryScanStagingResultsRepository ??= new LibraryScanStagingResultsRepository(_luminaDbContext);
|
||||||
|
return _libraryScanStagingResultsRepository;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the library metadata provider configuration repository.
|
||||||
|
/// </summary>
|
||||||
|
public ILibraryMetadataProviderConfigurationRepository LibraryMetadataProviderConfigurationRepository
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_libraryMetadataProviderConfigurationRepository ??= new LibraryMetadataProviderConfigurationRepository(_luminaDbContext);
|
||||||
|
return _libraryMetadataProviderConfigurationRepository;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the plugin repository.
|
||||||
|
/// </summary>
|
||||||
|
public IPluginRepository PluginRepository
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_pluginRepository ??= new PluginRepository(_luminaDbContext);
|
||||||
|
return _pluginRepository;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the user repository.
|
||||||
|
/// </summary>
|
||||||
|
public IUserRepository UserRepository
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_userRepository ??= new UserRepository(_luminaDbContext);
|
||||||
|
return _userRepository;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="UnitOfWork"/> class.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
|
||||||
|
public UnitOfWork(LuminaDbContext luminaDbContext)
|
||||||
|
{
|
||||||
|
_luminaDbContext = luminaDbContext;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -100,18 +215,51 @@ public class UnitOfWork : IUnitOfWork
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Opens a transaction.
|
/// Begins a new database transaction.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public void OpenTransaction()
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
|
/// <returns>A task representing the asynchronous operation.</returns>
|
||||||
|
public async Task BeginTransactionAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
throw new NotImplementedException();
|
_transaction = await _luminaDbContext.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Commits a transaction.
|
/// Commits the current transaction.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public void CommitTransaction()
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
|
/// <returns>A task representing the asynchronous operation.</returns>
|
||||||
|
public async Task CommitTransactionAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
throw new NotImplementedException();
|
if (_transaction is not null)
|
||||||
|
{
|
||||||
|
await _transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
await _transaction.DisposeAsync().ConfigureAwait(false);
|
||||||
|
_transaction = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Rolls back the current transaction.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
|
/// <returns>A task representing the asynchronous operation.</returns>
|
||||||
|
public async Task RollbackTransactionAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (_transaction is not null)
|
||||||
|
{
|
||||||
|
await _transaction.RollbackAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
await _transaction.DisposeAsync().ConfigureAwait(false);
|
||||||
|
_transaction = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Disposes the unit of work and its resources.
|
||||||
|
/// </summary>
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_transaction?.Dispose();
|
||||||
|
_luminaDbContext.Dispose();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -23,7 +23,7 @@ namespace Lumina.Infrastructure.Core.Authorization;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class AuthorizationService : IAuthorizationService
|
public class AuthorizationService : IAuthorizationService
|
||||||
{
|
{
|
||||||
private readonly IUserRepository _userRepository;
|
private readonly IUnitOfWork _unitOfWork;
|
||||||
private readonly IAuthorizationPolicyFactory _authorizationPolicyFactory;
|
private readonly IAuthorizationPolicyFactory _authorizationPolicyFactory;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -33,7 +33,7 @@ public class AuthorizationService : IAuthorizationService
|
|||||||
/// <param name="authorizationPolicyFactory">The factory used to generate authorization policies.</param>
|
/// <param name="authorizationPolicyFactory">The factory used to generate authorization policies.</param>
|
||||||
public AuthorizationService(IUnitOfWork unitOfWork, IAuthorizationPolicyFactory authorizationPolicyFactory)
|
public AuthorizationService(IUnitOfWork unitOfWork, IAuthorizationPolicyFactory authorizationPolicyFactory)
|
||||||
{
|
{
|
||||||
_userRepository = unitOfWork.GetRepository<IUserRepository>();
|
_unitOfWork = unitOfWork;
|
||||||
_authorizationPolicyFactory = authorizationPolicyFactory;
|
_authorizationPolicyFactory = authorizationPolicyFactory;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,7 +46,7 @@ public class AuthorizationService : IAuthorizationService
|
|||||||
/// <returns><see langword="true"/> if the user has the specified permission, <see langword="false"/> otherwise.</returns>
|
/// <returns><see langword="true"/> if the user has the specified permission, <see langword="false"/> otherwise.</returns>
|
||||||
public async Task<bool> HasPermissionAsync(Guid userId, AuthorizationPermission permission, CancellationToken cancellationToken)
|
public async Task<bool> HasPermissionAsync(Guid userId, AuthorizationPermission permission, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
Result<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||||
if (getUserResult.IsFailure || getUserResult.Value is null)
|
if (getUserResult.IsFailure || getUserResult.Value is null)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
@@ -68,7 +68,7 @@ public class AuthorizationService : IAuthorizationService
|
|||||||
/// <returns><see langword="true"/> if the user is in the specified role, <see langword="false"/> otherwise.</returns>
|
/// <returns><see langword="true"/> if the user is in the specified role, <see langword="false"/> otherwise.</returns>
|
||||||
public async Task<bool> IsInRoleAsync(Guid userId, string role, CancellationToken cancellationToken)
|
public async Task<bool> IsInRoleAsync(Guid userId, string role, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
Result<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||||
if (getUserResult.IsFailure || getUserResult.Value is null)
|
if (getUserResult.IsFailure || getUserResult.Value is null)
|
||||||
return false;
|
return false;
|
||||||
return getUserResult.Value.UserRole?.Role.RoleName == role;
|
return getUserResult.Value.UserRole?.Role.RoleName == role;
|
||||||
@@ -96,7 +96,7 @@ public class AuthorizationService : IAuthorizationService
|
|||||||
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="UserAuthorizationEntity"/>, or an error.</returns>
|
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="UserAuthorizationEntity"/>, or an error.</returns>
|
||||||
public async Task<Result<UserAuthorizationEntity>> GetUserAuthorizationAsync(Guid userId, CancellationToken cancellationToken)
|
public async Task<Result<UserAuthorizationEntity>> GetUserAuthorizationAsync(Guid userId, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
Result<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
if (getUserResult.IsFailure)
|
if (getUserResult.IsFailure)
|
||||||
return getUserResult.Errors;
|
return getUserResult.Errors;
|
||||||
@@ -108,9 +108,7 @@ public class AuthorizationService : IAuthorizationService
|
|||||||
string? role = getUserResult.Value.UserRole?.Role.RoleName;
|
string? role = getUserResult.Value.UserRole?.Role.RoleName;
|
||||||
|
|
||||||
// get direct user permissions
|
// get direct user permissions
|
||||||
HashSet<AuthorizationPermission> directPermissions = getUserResult.Value.UserPermissions
|
HashSet<AuthorizationPermission> directPermissions = [.. getUserResult.Value.UserPermissions.Select(userPermission => userPermission.Permission.PermissionName)];
|
||||||
.Select(userPermission => userPermission.Permission.PermissionName)
|
|
||||||
.ToHashSet();
|
|
||||||
|
|
||||||
// get permissions from roles
|
// get permissions from roles
|
||||||
HashSet<AuthorizationPermission>? rolePermissions = getUserResult.Value.UserRole?.Role.RolePermissions
|
HashSet<AuthorizationPermission>? rolePermissions = getUserResult.Value.UserRole?.Role.RolePermissions
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ namespace Lumina.Infrastructure.Core.Authorization.Policies.Over18;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class Over18Policy : IOver18Policy
|
public class Over18Policy : IOver18Policy
|
||||||
{
|
{
|
||||||
private readonly IUserRepository _userRepository;
|
private readonly IUnitOfWork _unitOfWork;
|
||||||
private readonly IDateTimeProvider _dateTimeProvider;
|
private readonly IDateTimeProvider _dateTimeProvider;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -27,7 +27,7 @@ public class Over18Policy : IOver18Policy
|
|||||||
/// <param name="dateTimeProvider">Injected service for time related functionality.</param>
|
/// <param name="dateTimeProvider">Injected service for time related functionality.</param>
|
||||||
public Over18Policy(IUnitOfWork unitOfWork, IDateTimeProvider dateTimeProvider)
|
public Over18Policy(IUnitOfWork unitOfWork, IDateTimeProvider dateTimeProvider)
|
||||||
{
|
{
|
||||||
_userRepository = unitOfWork.GetRepository<IUserRepository>();
|
_unitOfWork = unitOfWork;
|
||||||
_dateTimeProvider = dateTimeProvider;
|
_dateTimeProvider = dateTimeProvider;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ public class Over18Policy : IOver18Policy
|
|||||||
/// <returns><see langword="true"/> if the policy evaluation succeeds, <see langword="false"/> otherwise.</returns>
|
/// <returns><see langword="true"/> if the policy evaluation succeeds, <see langword="false"/> otherwise.</returns>
|
||||||
public async Task<bool> EvaluateAsync(Guid userId, CancellationToken cancellationToken)
|
public async Task<bool> EvaluateAsync(Guid userId, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
Result<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||||
if (getUserResult.IsFailure || getUserResult.Value is null)
|
if (getUserResult.IsFailure || getUserResult.Value is null)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -59,7 +59,7 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra
|
|||||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||||
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
|
||||||
|
|
||||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||||
|
|
||||||
@@ -69,7 +69,7 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra
|
|||||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||||
|
|
||||||
// mark the staging results against the media library scan snapshot of the previous scan
|
// mark the staging results against the media library scan snapshot of the previous scan
|
||||||
Result<Updated> markChangesResult = await stagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
Result<Updated> markChangesResult = await unitOfWork.LibraryScanStagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (markChangesResult.IsFailure)
|
if (markChangesResult.IsFailure)
|
||||||
throw new InvalidOperationException(markChangesResult.FirstError.Description);
|
throw new InvalidOperationException(markChangesResult.FirstError.Description);
|
||||||
|
|
||||||
|
|||||||
+4
-4
@@ -63,13 +63,13 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
|
|||||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||||
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
|
||||||
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
|
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
|
||||||
|
|
||||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||||
|
|
||||||
// count the files that need hashing, for progress reporting purposes
|
// count the files that need hashing, for progress reporting purposes
|
||||||
Result<int> getFilesToHashCountResult = await stagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
Result<int> getFilesToHashCountResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getFilesToHashCountResult.IsFailure)
|
if (getFilesToHashCountResult.IsFailure)
|
||||||
throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description);
|
throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description);
|
||||||
int totalFilesToHash = getFilesToHashCountResult.Value;
|
int totalFilesToHash = getFilesToHashCountResult.Value;
|
||||||
@@ -89,7 +89,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
|
|||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
Result<IReadOnlyList<HashedFileSystemFileDto>> getFilesToHashPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
Result<IReadOnlyList<HashedFileSystemFileDto>> getFilesToHashPageResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||||
if (getFilesToHashPageResult.IsFailure)
|
if (getFilesToHashPageResult.IsFailure)
|
||||||
throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description);
|
throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description);
|
||||||
IReadOnlyList<HashedFileSystemFileDto> filesToHashPage = getFilesToHashPageResult.Value;
|
IReadOnlyList<HashedFileSystemFileDto> filesToHashPage = getFilesToHashPageResult.Value;
|
||||||
@@ -112,7 +112,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
|
|||||||
}, cancellationToken).ConfigureAwait(false);
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
// write the computed hashes back to the staging results
|
// write the computed hashes back to the staging results
|
||||||
Result<Updated> updateHashesResult = await stagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false);
|
Result<Updated> updateHashesResult = await unitOfWork.LibraryScanStagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false);
|
||||||
if (updateHashesResult.IsFailure)
|
if (updateHashesResult.IsFailure)
|
||||||
throw new InvalidOperationException(updateHashesResult.FirstError.Description);
|
throw new InvalidOperationException(updateHashesResult.FirstError.Description);
|
||||||
|
|
||||||
|
|||||||
+5
-8
@@ -1,14 +1,13 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using Lumina.Domain.Common.Primitives;
|
|
||||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
|
||||||
using Lumina.Application.Common.DataAccess.UoW;
|
using Lumina.Application.Common.DataAccess.UoW;
|
||||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||||
using Lumina.Contracts.DTO.Common;
|
using Lumina.Contracts.DTO.Common;
|
||||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||||
using Lumina.Domain.Common.Events;
|
using Lumina.Domain.Common.Events;
|
||||||
|
using Lumina.Domain.Common.Primitives;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||||
@@ -75,13 +74,11 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
|||||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||||
ILibraryMetadataProviderConfigurationRepository configurationRepository = unitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>();
|
|
||||||
IBookRepository bookRepository = unitOfWork.GetRepository<IBookRepository>();
|
|
||||||
|
|
||||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
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
|
// get the metadata providers configured for the media library, in their configured order, that support the media library type
|
||||||
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getConfigurationsResult.IsFailure)
|
if (getConfigurationsResult.IsFailure)
|
||||||
throw new InvalidOperationException(getConfigurationsResult.FirstError.Description);
|
throw new InvalidOperationException(getConfigurationsResult.FirstError.Description);
|
||||||
List<IRemoteMetadataProvider> providers = [];
|
List<IRemoteMetadataProvider> providers = [];
|
||||||
@@ -96,7 +93,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
|||||||
}
|
}
|
||||||
|
|
||||||
// count the books that need their metadata enriched, for progress reporting purposes
|
// count the books that need their metadata enriched, for progress reporting purposes
|
||||||
Result<int> getBooksToEnrichCountResult = await bookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
Result<int> getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getBooksToEnrichCountResult.IsFailure)
|
if (getBooksToEnrichCountResult.IsFailure)
|
||||||
throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
|
throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
|
||||||
int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
|
int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
|
||||||
@@ -116,7 +113,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
|||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
Result<IReadOnlyList<BookEntity>> getBooksPageResult = await bookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
Result<IReadOnlyList<BookEntity>> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||||
if (getBooksPageResult.IsFailure)
|
if (getBooksPageResult.IsFailure)
|
||||||
throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
|
throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
|
||||||
IReadOnlyList<BookEntity> booksPage = getBooksPageResult.Value;
|
IReadOnlyList<BookEntity> booksPage = getBooksPageResult.Value;
|
||||||
@@ -127,7 +124,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
|||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
await EnrichBookAsync(bookEntity, providers, bookRepository, cancellationToken).ConfigureAwait(false);
|
await EnrichBookAsync(bookEntity, providers, unitOfWork.BookRepository, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
// check if enough time has passed since last update
|
// check if enough time has passed since last update
|
||||||
DateTime now = DateTime.UtcNow;
|
DateTime now = DateTime.UtcNow;
|
||||||
|
|||||||
+7
-7
@@ -66,7 +66,7 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
|
|||||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||||
ILibraryScanSnapshotRepository libraryScanSnapshotRepository = unitOfWork.GetRepository<ILibraryScanSnapshotRepository>();
|
|
||||||
|
|
||||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||||
|
|
||||||
@@ -76,12 +76,12 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
|
|||||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
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
|
// 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
|
||||||
Result<IReadOnlyList<string>> getDeletedPathsResult = await libraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
|
Result<IReadOnlyList<string>> getDeletedPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getDeletedPathsResult.IsFailure)
|
if (getDeletedPathsResult.IsFailure)
|
||||||
throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description);
|
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
|
// apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan
|
||||||
Result<Updated> applySnapshotSwapResult = await libraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false);
|
Result<Updated> applySnapshotSwapResult = await unitOfWork.LibraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (applySnapshotSwapResult.IsFailure)
|
if (applySnapshotSwapResult.IsFailure)
|
||||||
throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description);
|
throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description);
|
||||||
|
|
||||||
@@ -93,21 +93,21 @@ 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
|
// materialize the books of the media library from the scan snapshot, so that they are browsable even without web metadata
|
||||||
Result<IReadOnlyList<string>> getPathsResult = await libraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
Result<IReadOnlyList<string>> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getPathsResult.IsFailure)
|
if (getPathsResult.IsFailure)
|
||||||
throw new InvalidOperationException(getPathsResult.FirstError.Description);
|
throw new InvalidOperationException(getPathsResult.FirstError.Description);
|
||||||
IBookRepository bookRepository = unitOfWork.GetRepository<IBookRepository>();
|
|
||||||
foreach (string path in getPathsResult.Value)
|
foreach (string path in getPathsResult.Value)
|
||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
Result<BookEntity?> getExistingBookResult = await bookRepository.GetByPathAsync(LibraryId.Value, path, cancellationToken).ConfigureAwait(false);
|
Result<BookEntity?> getExistingBookResult = await unitOfWork.BookRepository.GetByPathAsync(LibraryId.Value, path, cancellationToken).ConfigureAwait(false);
|
||||||
if (getExistingBookResult.IsFailure)
|
if (getExistingBookResult.IsFailure)
|
||||||
throw new InvalidOperationException(getExistingBookResult.FirstError.Description);
|
throw new InvalidOperationException(getExistingBookResult.FirstError.Description);
|
||||||
if (getExistingBookResult.Value is not null)
|
if (getExistingBookResult.Value is not null)
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
Result<Created> insertBookResult = await bookRepository.InsertAsync(CreateShellBookEntity(LibraryId.Value, path), cancellationToken).ConfigureAwait(false);
|
Result<Created> insertBookResult = await unitOfWork.BookRepository.InsertAsync(CreateShellBookEntity(LibraryId.Value, path), cancellationToken).ConfigureAwait(false);
|
||||||
if (insertBookResult.IsFailure)
|
if (insertBookResult.IsFailure)
|
||||||
throw new InvalidOperationException(insertBookResult.FirstError.Description);
|
throw new InvalidOperationException(insertBookResult.FirstError.Description);
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-9
@@ -79,14 +79,11 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
|
|||||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>()!;
|
|
||||||
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
|
||||||
IDirectoryScanFingerprintRepository directoryScanFingerprintRepository = unitOfWork.GetRepository<IDirectoryScanFingerprintRepository>();
|
|
||||||
|
|
||||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||||
|
|
||||||
// get the library from the repository
|
// get the library from the repository
|
||||||
Result<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||||
|
|
||||||
@@ -99,7 +96,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
|
|||||||
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath = null;
|
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath = null;
|
||||||
if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
|
if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
|
||||||
{
|
{
|
||||||
Result<Dictionary<string, DirectoryScanFingerprintEntity>> getFingerprintsResult = await directoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
Result<Dictionary<string, DirectoryScanFingerprintEntity>> getFingerprintsResult = await unitOfWork.DirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getFingerprintsResult.IsFailure)
|
if (getFingerprintsResult.IsFailure)
|
||||||
throw new InvalidOperationException(getFingerprintsResult.FirstError.Description);
|
throw new InvalidOperationException(getFingerprintsResult.FirstError.Description);
|
||||||
fingerprintsByPath = getFingerprintsResult.Value;
|
fingerprintsByPath = getFingerprintsResult.Value;
|
||||||
@@ -128,8 +125,8 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
|
|||||||
fingerprintsByPath,
|
fingerprintsByPath,
|
||||||
stagingBatch,
|
stagingBatch,
|
||||||
fingerprintBatch,
|
fingerprintBatch,
|
||||||
stagingResultsRepository,
|
unitOfWork.LibraryScanStagingResultsRepository,
|
||||||
directoryScanFingerprintRepository,
|
unitOfWork.DirectoryScanFingerprintRepository,
|
||||||
cancellationToken).ConfigureAwait(false);
|
cancellationToken).ConfigureAwait(false);
|
||||||
processedContentLocations++;
|
processedContentLocations++;
|
||||||
|
|
||||||
@@ -148,13 +145,13 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
|
|||||||
// flush any remaining discovered files and directory scan fingerprints that did not reach the batch size
|
// flush any remaining discovered files and directory scan fingerprints that did not reach the batch size
|
||||||
if (stagingBatch.Count > 0)
|
if (stagingBatch.Count > 0)
|
||||||
{
|
{
|
||||||
Result<Created> insertResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
|
Result<Created> insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
|
||||||
if (insertResult.IsFailure)
|
if (insertResult.IsFailure)
|
||||||
throw new InvalidOperationException(insertResult.FirstError.Description);
|
throw new InvalidOperationException(insertResult.FirstError.Description);
|
||||||
}
|
}
|
||||||
if (fingerprintBatch.Count > 0)
|
if (fingerprintBatch.Count > 0)
|
||||||
{
|
{
|
||||||
Result<Updated> upsertResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
|
Result<Updated> upsertResult = await unitOfWork.DirectoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
|
||||||
if (upsertResult.IsFailure)
|
if (upsertResult.IsFailure)
|
||||||
throw new InvalidOperationException(upsertResult.FirstError.Description);
|
throw new InvalidOperationException(upsertResult.FirstError.Description);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,7 +50,6 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
|
|||||||
|
|
||||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService<IUnitOfWork>();
|
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService<IUnitOfWork>();
|
||||||
IPluginRepository pluginRepository = unitOfWork.GetRepository<IPluginRepository>();
|
|
||||||
|
|
||||||
foreach (IPlugin plugin in _pluginManager.GetPlugins())
|
foreach (IPlugin plugin in _pluginManager.GetPlugins())
|
||||||
{
|
{
|
||||||
@@ -66,7 +65,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
|
|||||||
CreatedBy = default,
|
CreatedBy = default,
|
||||||
UpdatedBy = default
|
UpdatedBy = default
|
||||||
};
|
};
|
||||||
Result<Updated> upsertResult = await pluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false);
|
Result<Updated> upsertResult = await unitOfWork.PluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false);
|
||||||
if (upsertResult.IsFailure)
|
if (upsertResult.IsFailure)
|
||||||
_logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", plugin.Name, upsertResult.FirstError.Description);
|
_logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", plugin.Name, upsertResult.FirstError.Description);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,8 +36,7 @@ internal sealed class PluginSettingsStore : IPluginSettingsStore
|
|||||||
/// <inheritdoc/>
|
/// <inheritdoc/>
|
||||||
public async Task<IReadOnlyDictionary<string, string>?> GetSettingsAsync(Guid pluginId, CancellationToken cancellationToken)
|
public async Task<IReadOnlyDictionary<string, string>?> GetSettingsAsync(Guid pluginId, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
IPluginRepository pluginRepository = _unitOfWork.GetRepository<IPluginRepository>();
|
Result<PluginEntity?> getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(pluginId, cancellationToken).ConfigureAwait(false);
|
||||||
Result<PluginEntity?> getPluginResult = await pluginRepository.GetByIdAsync(pluginId, cancellationToken).ConfigureAwait(false);
|
|
||||||
if (getPluginResult.IsFailure)
|
if (getPluginResult.IsFailure)
|
||||||
{
|
{
|
||||||
_logger.LogWarning("Failed to read the settings of the plugin with Id '{PluginId}': {Error}", pluginId, getPluginResult.FirstError.Description);
|
_logger.LogWarning("Failed to read the settings of the plugin with Id '{PluginId}': {Error}", pluginId, getPluginResult.FirstError.Description);
|
||||||
|
|||||||
+1
-1
@@ -45,7 +45,7 @@ public class GetPermissionsQueryHandlerTests
|
|||||||
_userId = Guid.NewGuid();
|
_userId = Guid.NewGuid();
|
||||||
|
|
||||||
_mockCurrentUserService.UserId.Returns(_userId);
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
_mockUnitOfWork.GetRepository<IPermissionRepository>().Returns(_mockPermissionRepository);
|
_mockUnitOfWork.PermissionRepository.Returns(_mockPermissionRepository);
|
||||||
|
|
||||||
_sut = new GetPermissionsQueryHandler(
|
_sut = new GetPermissionsQueryHandler(
|
||||||
_mockAuthorizationService,
|
_mockAuthorizationService,
|
||||||
|
|||||||
+1
-1
@@ -51,7 +51,7 @@ public class AddRoleCommandHandlerTests
|
|||||||
_userId = Guid.NewGuid();
|
_userId = Guid.NewGuid();
|
||||||
|
|
||||||
_mockCurrentUserService.UserId.Returns(_userId);
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(_mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository);
|
||||||
|
|
||||||
_sut = new AddRoleCommandHandler(
|
_sut = new AddRoleCommandHandler(
|
||||||
_mockAuthorizationService,
|
_mockAuthorizationService,
|
||||||
|
|||||||
+1
-1
@@ -48,7 +48,7 @@ public class DeleteRoleCommandHandlerTests
|
|||||||
_userId = Guid.NewGuid();
|
_userId = Guid.NewGuid();
|
||||||
|
|
||||||
_mockCurrentUserService.UserId.Returns(_userId);
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(_mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository);
|
||||||
|
|
||||||
_sut = new DeleteRoleCommandHandler(
|
_sut = new DeleteRoleCommandHandler(
|
||||||
_mockAuthorizationService,
|
_mockAuthorizationService,
|
||||||
|
|||||||
+1
-1
@@ -51,7 +51,7 @@ public class UpdateRoleCommandHandlerTests
|
|||||||
_userId = Guid.NewGuid();
|
_userId = Guid.NewGuid();
|
||||||
|
|
||||||
_mockCurrentUserService.UserId.Returns(_userId);
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(_mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository);
|
||||||
|
|
||||||
_sut = new UpdateRoleCommandHandler(
|
_sut = new UpdateRoleCommandHandler(
|
||||||
_mockAuthorizationService,
|
_mockAuthorizationService,
|
||||||
|
|||||||
+1
-1
@@ -50,7 +50,7 @@ public class GetRolePermissionsQueryHandlerTests
|
|||||||
_userId = Guid.NewGuid();
|
_userId = Guid.NewGuid();
|
||||||
|
|
||||||
_mockCurrentUserService.UserId.Returns(_userId);
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(_mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository);
|
||||||
|
|
||||||
_sut = new GetRolePermissionsQueryHandler(
|
_sut = new GetRolePermissionsQueryHandler(
|
||||||
_mockAuthorizationService,
|
_mockAuthorizationService,
|
||||||
|
|||||||
+1
-1
@@ -46,7 +46,7 @@ public class GetRolesQueryHandlerTests
|
|||||||
_userId = Guid.NewGuid();
|
_userId = Guid.NewGuid();
|
||||||
|
|
||||||
_mockCurrentUserService.UserId.Returns(_userId);
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(_mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository);
|
||||||
|
|
||||||
_sut = new GetRolesQueryHandler(
|
_sut = new GetRolesQueryHandler(
|
||||||
_mockAuthorizationService,
|
_mockAuthorizationService,
|
||||||
|
|||||||
+1
-1
@@ -58,7 +58,7 @@ public class SetupApplicationCommandHandlerTests
|
|||||||
mockValidator.Validate(Arg.Any<SetupApplicationCommand>())
|
mockValidator.Validate(Arg.Any<SetupApplicationCommand>())
|
||||||
.Returns([]);
|
.Returns([]);
|
||||||
|
|
||||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||||
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
|
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
|
||||||
|
|
||||||
_sut = new SetupApplicationCommandHandler(
|
_sut = new SetupApplicationCommandHandler(
|
||||||
|
|||||||
+1
-1
@@ -34,7 +34,7 @@ public class CheckInitializationQueryHandlerTests
|
|||||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||||
|
|
||||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||||
|
|
||||||
_sut = new CheckInitializationQueryHandler(_mockUnitOfWork);
|
_sut = new CheckInitializationQueryHandler(_mockUnitOfWork);
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -47,7 +47,7 @@ public class AddBookCommandHandlerTests
|
|||||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||||
|
|
||||||
_mockUnitOfWork.GetRepository<IBookRepository>().Returns(_mockBookRepository);
|
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||||
|
|
||||||
IValidator<AddBookCommand> mockValidator = Substitute.For<IValidator<AddBookCommand>>();
|
IValidator<AddBookCommand> mockValidator = Substitute.For<IValidator<AddBookCommand>>();
|
||||||
mockValidator.Validate(Arg.Any<AddBookCommand>())
|
mockValidator.Validate(Arg.Any<AddBookCommand>())
|
||||||
|
|||||||
+1
-1
@@ -31,7 +31,7 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests
|
|||||||
{
|
{
|
||||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||||
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
|
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
|
||||||
_mockUnitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>().Returns(_mockConfigurationRepository);
|
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository);
|
||||||
IValidator<ReorderLibraryMetadataProvidersCommand> mockValidator = Substitute.For<IValidator<ReorderLibraryMetadataProvidersCommand>>();
|
IValidator<ReorderLibraryMetadataProvidersCommand> mockValidator = Substitute.For<IValidator<ReorderLibraryMetadataProvidersCommand>>();
|
||||||
mockValidator.Validate(Arg.Any<ReorderLibraryMetadataProvidersCommand>())
|
mockValidator.Validate(Arg.Any<ReorderLibraryMetadataProvidersCommand>())
|
||||||
.Returns([]);
|
.Returns([]);
|
||||||
|
|||||||
+1
-1
@@ -30,7 +30,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests
|
|||||||
{
|
{
|
||||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||||
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
|
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
|
||||||
_mockUnitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>().Returns(_mockConfigurationRepository);
|
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository);
|
||||||
IValidator<SetLibraryMetadataProviderEnabledCommand> mockValidator = Substitute.For<IValidator<SetLibraryMetadataProviderEnabledCommand>>();
|
IValidator<SetLibraryMetadataProviderEnabledCommand> mockValidator = Substitute.For<IValidator<SetLibraryMetadataProviderEnabledCommand>>();
|
||||||
mockValidator.Validate(Arg.Any<SetLibraryMetadataProviderEnabledCommand>())
|
mockValidator.Validate(Arg.Any<SetLibraryMetadataProviderEnabledCommand>())
|
||||||
.Returns([]);
|
.Returns([]);
|
||||||
|
|||||||
+1
-1
@@ -29,7 +29,7 @@ public class UpdatePluginSettingsCommandHandlerTests
|
|||||||
{
|
{
|
||||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||||
_mockPluginRepository = Substitute.For<IPluginRepository>();
|
_mockPluginRepository = Substitute.For<IPluginRepository>();
|
||||||
_mockUnitOfWork.GetRepository<IPluginRepository>().Returns(_mockPluginRepository);
|
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
|
||||||
IValidator<UpdatePluginSettingsCommand> mockValidator = Substitute.For<IValidator<UpdatePluginSettingsCommand>>();
|
IValidator<UpdatePluginSettingsCommand> mockValidator = Substitute.For<IValidator<UpdatePluginSettingsCommand>>();
|
||||||
mockValidator.Validate(Arg.Any<UpdatePluginSettingsCommand>())
|
mockValidator.Validate(Arg.Any<UpdatePluginSettingsCommand>())
|
||||||
.Returns([]);
|
.Returns([]);
|
||||||
|
|||||||
+1
-1
@@ -30,7 +30,7 @@ public class GetPluginsQueryHandlerTests
|
|||||||
{
|
{
|
||||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||||
_mockPluginRepository = Substitute.For<IPluginRepository>();
|
_mockPluginRepository = Substitute.For<IPluginRepository>();
|
||||||
_mockUnitOfWork.GetRepository<IPluginRepository>().Returns(_mockPluginRepository);
|
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
|
||||||
_sut = new GetPluginsQueryHandler(_mockUnitOfWork);
|
_sut = new GetPluginsQueryHandler(_mockUnitOfWork);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -38,7 +38,7 @@ public class ChangePasswordCommandHandlerTests
|
|||||||
_mockHashService = Substitute.For<IPasswordHashService>();
|
_mockHashService = Substitute.For<IPasswordHashService>();
|
||||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||||
|
|
||||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||||
|
|
||||||
IValidator<ChangePasswordCommand> mockValidator = Substitute.For<IValidator<ChangePasswordCommand>>();
|
IValidator<ChangePasswordCommand> mockValidator = Substitute.For<IValidator<ChangePasswordCommand>>();
|
||||||
mockValidator.Validate(Arg.Any<ChangePasswordCommand>())
|
mockValidator.Validate(Arg.Any<ChangePasswordCommand>())
|
||||||
|
|||||||
+1
-1
@@ -43,7 +43,7 @@ public class RecoverPasswordCommandHandlerTests
|
|||||||
_mockCryptographyService = Substitute.For<ICryptographyService>();
|
_mockCryptographyService = Substitute.For<ICryptographyService>();
|
||||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||||
|
|
||||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||||
|
|
||||||
IValidator<RecoverPasswordCommand> mockValidator = Substitute.For<IValidator<RecoverPasswordCommand>>();
|
IValidator<RecoverPasswordCommand> mockValidator = Substitute.For<IValidator<RecoverPasswordCommand>>();
|
||||||
mockValidator.Validate(Arg.Any<RecoverPasswordCommand>())
|
mockValidator.Validate(Arg.Any<RecoverPasswordCommand>())
|
||||||
|
|||||||
+1
-1
@@ -49,7 +49,7 @@ public class RegisterUserCommandHandlerTests
|
|||||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||||
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
|
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||||
|
|
||||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||||
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
|
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
|
||||||
|
|
||||||
IValidator<RegisterUserCommand> mockValidator = Substitute.For<IValidator<RegisterUserCommand>>();
|
IValidator<RegisterUserCommand> mockValidator = Substitute.For<IValidator<RegisterUserCommand>>();
|
||||||
|
|||||||
+1
-1
@@ -48,7 +48,7 @@ public class GetUsersQueryHandlerTests
|
|||||||
_userId = Guid.NewGuid();
|
_userId = Guid.NewGuid();
|
||||||
|
|
||||||
_mockCurrentUserService.UserId.Returns(_userId);
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||||
|
|
||||||
_sut = new GetUsersQueryHandler(
|
_sut = new GetUsersQueryHandler(
|
||||||
_mockAuthorizationService,
|
_mockAuthorizationService,
|
||||||
|
|||||||
+1
-1
@@ -48,7 +48,7 @@ public class LoginUserQueryHandlerTests
|
|||||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||||
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
|
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||||
|
|
||||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||||
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
|
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
|
||||||
|
|
||||||
IValidator<LoginUserQuery> mockValidator = Substitute.For<IValidator<LoginUserQuery>>();
|
IValidator<LoginUserQuery> mockValidator = Substitute.For<IValidator<LoginUserQuery>>();
|
||||||
|
|||||||
+3
-3
@@ -57,9 +57,9 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
|
|||||||
_userId = Guid.NewGuid();
|
_userId = Guid.NewGuid();
|
||||||
|
|
||||||
_mockCurrentUserService.UserId.Returns(_userId);
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(_mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository);
|
||||||
_mockUnitOfWork.GetRepository<IPermissionRepository>().Returns(_mockPermissionRepository);
|
_mockUnitOfWork.PermissionRepository.Returns(_mockPermissionRepository);
|
||||||
|
|
||||||
IValidator<UpdateUserRoleAndPermissionsCommand> mockValidator = Substitute.For<IValidator<UpdateUserRoleAndPermissionsCommand>>();
|
IValidator<UpdateUserRoleAndPermissionsCommand> mockValidator = Substitute.For<IValidator<UpdateUserRoleAndPermissionsCommand>>();
|
||||||
mockValidator.Validate(Arg.Any<UpdateUserRoleAndPermissionsCommand>())
|
mockValidator.Validate(Arg.Any<UpdateUserRoleAndPermissionsCommand>())
|
||||||
|
|||||||
+1
-1
@@ -49,7 +49,7 @@ public class GetUserPermissionsQueryHandlerTests
|
|||||||
_userId = Guid.NewGuid();
|
_userId = Guid.NewGuid();
|
||||||
|
|
||||||
_mockCurrentUserService.UserId.Returns(_userId);
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||||
|
|
||||||
IValidator<GetUserPermissionsQuery> mockValidator = Substitute.For<IValidator<GetUserPermissionsQuery>>();
|
IValidator<GetUserPermissionsQuery> mockValidator = Substitute.For<IValidator<GetUserPermissionsQuery>>();
|
||||||
mockValidator.Validate(Arg.Any<GetUserPermissionsQuery>())
|
mockValidator.Validate(Arg.Any<GetUserPermissionsQuery>())
|
||||||
|
|||||||
+1
-1
@@ -47,7 +47,7 @@ public class GetUserRoleQueryHandlerTests
|
|||||||
_userId = Guid.NewGuid();
|
_userId = Guid.NewGuid();
|
||||||
|
|
||||||
_mockCurrentUserService.UserId.Returns(_userId);
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||||
|
|
||||||
IValidator<GetUserRoleQuery> mockValidator = Substitute.For<IValidator<GetUserRoleQuery>>();
|
IValidator<GetUserRoleQuery> mockValidator = Substitute.For<IValidator<GetUserRoleQuery>>();
|
||||||
mockValidator.Validate(Arg.Any<GetUserRoleQuery>())
|
mockValidator.Validate(Arg.Any<GetUserRoleQuery>())
|
||||||
|
|||||||
+4
-8
@@ -1,11 +1,8 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
|
||||||
using Lumina.Application.Common.DataAccess.UoW;
|
using Lumina.Application.Common.DataAccess.UoW;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Time;
|
using Lumina.Application.Common.Infrastructure.Time;
|
||||||
using Lumina.DataAccess.Common.DependencyInjection;
|
using Lumina.DataAccess.Common.DependencyInjection;
|
||||||
using Lumina.DataAccess.Core.Repositories.Books;
|
|
||||||
using Lumina.DataAccess.Core.Repositories.Common.Factory;
|
|
||||||
using Lumina.DataAccess.Core.UoW;
|
using Lumina.DataAccess.Core.UoW;
|
||||||
using Lumina.DataAccess.UnitTests.Common.Setup;
|
using Lumina.DataAccess.UnitTests.Common.Setup;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
@@ -36,8 +33,6 @@ public class DataAccessLayerServicesTests
|
|||||||
// Assert
|
// Assert
|
||||||
Assert.Contains(services, sd => sd.ServiceType == typeof(LuminaDbContext));
|
Assert.Contains(services, sd => sd.ServiceType == typeof(LuminaDbContext));
|
||||||
Assert.Contains(services, sd => sd.ServiceType == typeof(IUnitOfWork) && sd.ImplementationType == typeof(UnitOfWork));
|
Assert.Contains(services, sd => sd.ServiceType == typeof(IUnitOfWork) && sd.ImplementationType == typeof(UnitOfWork));
|
||||||
Assert.Contains(services, sd => sd.ServiceType == typeof(IRepositoryFactory) && sd.ImplementationType == typeof(RepositoryFactory));
|
|
||||||
Assert.Contains(services, sd => sd.ServiceType == typeof(IBookRepository) && sd.ImplementationType == typeof(BookRepository));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -62,7 +57,7 @@ public class DataAccessLayerServicesTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void AddDataAccessLayerServices_WhenCalled_ShouldRegisterRepositories()
|
public void AddDataAccessLayerServices_WhenCalled_ShouldExposeRepositoriesThroughUnitOfWork()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
ServiceCollection services = new();
|
ServiceCollection services = new();
|
||||||
@@ -76,7 +71,8 @@ public class DataAccessLayerServicesTests
|
|||||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
IBookRepository? repository = serviceProvider.GetService<IBookRepository>();
|
IUnitOfWork unitOfWork = serviceProvider.GetRequiredService<IUnitOfWork>();
|
||||||
Assert.NotNull(repository);
|
Assert.NotNull(unitOfWork.BookRepository);
|
||||||
|
Assert.NotNull(unitOfWork.PermissionRepository);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
-6
@@ -1,6 +0,0 @@
|
|||||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory.Fixtures;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Repository fixture interface for testing non registered repositories.
|
|
||||||
/// </summary>
|
|
||||||
public interface IUnregisteredRepository { }
|
|
||||||
-107
@@ -1,107 +0,0 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
|
||||||
using AutoFixture;
|
|
||||||
using AutoFixture.AutoNSubstitute;
|
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
|
||||||
using Lumina.DataAccess.Core.Repositories.Books;
|
|
||||||
using Lumina.DataAccess.Core.Repositories.Common.Factory;
|
|
||||||
using System;
|
|
||||||
using System.Diagnostics.CodeAnalysis;
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Contains unit tests for the <see cref="RepositoryDictionary"/> class.
|
|
||||||
/// </summary>
|
|
||||||
[ExcludeFromCodeCoverage]
|
|
||||||
public class RepositoryDictionaryTests
|
|
||||||
{
|
|
||||||
private readonly IFixture _fixture;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Initializes a new instance of the <see cref="RepositoryDictionaryTests"/> class.
|
|
||||||
/// </summary>
|
|
||||||
public RepositoryDictionaryTests()
|
|
||||||
{
|
|
||||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Add_WhenValidRepositoryItemIsAdded_ShouldIncreaseCount()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
BookRepository bookRepository = _fixture.Create<BookRepository>();
|
|
||||||
RepositoryDictionary repositoryDictionary = new();
|
|
||||||
|
|
||||||
// Act
|
|
||||||
repositoryDictionary.Add<IBookRepository>(bookRepository);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.Equal(1, repositoryDictionary.Count);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Clear_WhenCalled_ShouldRemoveAllItems()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
BookRepository bookRepository = _fixture.Create<BookRepository>();
|
|
||||||
RepositoryDictionary repositoryDictionary = new();
|
|
||||||
repositoryDictionary.Add<IBookRepository>(bookRepository);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
repositoryDictionary.Clear();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.Equal(0, repositoryDictionary.Count);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Get_WhenRepositoryExists_ShouldReturnCorrectRepository()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
BookRepository expected = _fixture.Create<BookRepository>();
|
|
||||||
RepositoryDictionary repositoryDictionary = new();
|
|
||||||
repositoryDictionary.Add<IBookRepository>(expected);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
IBookRepository actual = repositoryDictionary.Get<IBookRepository>(typeof(BookRepository));
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.Same(expected, actual);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Add_WhenNullValueIsProvided_ShouldThrowArgumentException()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
RepositoryDictionary repositoryDictionary = new();
|
|
||||||
|
|
||||||
// Act & Assert
|
|
||||||
Assert.Throws<ArgumentException>(() => repositoryDictionary.Add<IBookRepository>(null!));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Add_WhenDuplicateValueIsAdded_ShouldThrowArgumentException()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
BookRepository bookRepository = _fixture.Create<BookRepository>();
|
|
||||||
RepositoryDictionary repositoryDictionary = new();
|
|
||||||
repositoryDictionary.Add<IBookRepository>(bookRepository);
|
|
||||||
|
|
||||||
// Act & Assert
|
|
||||||
ArgumentException exception = Assert.Throws<ArgumentException>(() => repositoryDictionary.Add<IBookRepository>(bookRepository));
|
|
||||||
Assert.Equal("Duplicate values are not allowed!", exception.Message);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Add_WhenNonRepositoryValueIsAdded_ShouldThrowArgumentException()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
object nonRepository = new();
|
|
||||||
RepositoryDictionary repositoryDictionary = new();
|
|
||||||
|
|
||||||
// Act & Assert
|
|
||||||
ArgumentException exception = Assert.Throws<ArgumentException>(() => repositoryDictionary.Add(nonRepository));
|
|
||||||
Assert.Equal("Value must implement IRepository interface!", exception.Message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-58
@@ -1,58 +0,0 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
|
||||||
using Lumina.Application.Common.Infrastructure.Time;
|
|
||||||
using Lumina.DataAccess.Common.DependencyInjection;
|
|
||||||
using Lumina.DataAccess.Core.Repositories.Common.Factory;
|
|
||||||
using Lumina.DataAccess.UnitTests.Common.Setup;
|
|
||||||
using Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory.Fixtures;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using System;
|
|
||||||
using System.Diagnostics.CodeAnalysis;
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Contains unit tests for the <see cref="RepositoryFactory"/> class.
|
|
||||||
/// </summary>
|
|
||||||
[ExcludeFromCodeCoverage]
|
|
||||||
public class RepositoryFactoryTests
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public void CreateRepository_WhenCalled_ShouldReturnCorrectRepository()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
ServiceCollection services = new();
|
|
||||||
DataAccessLayerServices.AddDataAccessLayerServices(services);
|
|
||||||
|
|
||||||
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
|
|
||||||
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
|
|
||||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
|
||||||
RepositoryFactory repositoryFactory = new(serviceProvider);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
IBookRepository result = repositoryFactory.CreateRepository<IBookRepository>();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.NotNull(result);
|
|
||||||
Assert.IsAssignableFrom<IBookRepository>(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void CreateRepository_WhenUnregisteredTypeRequested_ShouldThrowException()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
ServiceCollection services = new();
|
|
||||||
DataAccessLayerServices.AddDataAccessLayerServices(services);
|
|
||||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
|
||||||
RepositoryFactory repositoryFactory = new(serviceProvider);
|
|
||||||
|
|
||||||
// Act & Assert
|
|
||||||
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(
|
|
||||||
() => repositoryFactory.CreateRepository<IUnregisteredRepository>());
|
|
||||||
Assert.Equal(
|
|
||||||
"No service for type 'Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory.Fixtures.IUnregisteredRepository' has been registered.",
|
|
||||||
exception.Message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -43,7 +43,7 @@ public class DataSeedServiceTests
|
|||||||
_fixedUtcNow = DateTime.UtcNow;
|
_fixedUtcNow = DateTime.UtcNow;
|
||||||
|
|
||||||
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
|
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
|
||||||
_mockUnitOfWork.GetRepository<IPermissionRepository>().Returns(_mockPermissionRepository);
|
_mockUnitOfWork.PermissionRepository.Returns(_mockPermissionRepository);
|
||||||
|
|
||||||
_sut = new DataSeedService(_mockUnitOfWork, _mockDateTimeProvider);
|
_sut = new DataSeedService(_mockUnitOfWork, _mockDateTimeProvider);
|
||||||
}
|
}
|
||||||
@@ -126,7 +126,7 @@ public class DataSeedServiceTests
|
|||||||
// Arrange
|
// Arrange
|
||||||
Guid userId = Guid.NewGuid();
|
Guid userId = Guid.NewGuid();
|
||||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||||
mockRoleRepository
|
mockRoleRepository
|
||||||
.InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>())
|
.InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>())
|
||||||
.Returns(Result.Created);
|
.Returns(Result.Created);
|
||||||
@@ -156,7 +156,7 @@ public class DataSeedServiceTests
|
|||||||
// Arrange
|
// Arrange
|
||||||
Guid userId = Guid.NewGuid();
|
Guid userId = Guid.NewGuid();
|
||||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||||
|
|
||||||
Error expectedError = Error.Conflict("Role.Conflict", "Role already exists");
|
Error expectedError = Error.Conflict("Role.Conflict", "Role already exists");
|
||||||
mockRoleRepository
|
mockRoleRepository
|
||||||
@@ -181,7 +181,7 @@ public class DataSeedServiceTests
|
|||||||
List<string> capturedRoleNames = [];
|
List<string> capturedRoleNames = [];
|
||||||
|
|
||||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||||
|
|
||||||
mockRoleRepository
|
mockRoleRepository
|
||||||
.InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>())
|
.InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>())
|
||||||
@@ -203,7 +203,7 @@ public class DataSeedServiceTests
|
|||||||
RoleEntity? capturedRole = null;
|
RoleEntity? capturedRole = null;
|
||||||
|
|
||||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||||
|
|
||||||
mockRoleRepository
|
mockRoleRepository
|
||||||
.InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>())
|
.InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>())
|
||||||
@@ -238,9 +238,9 @@ public class DataSeedServiceTests
|
|||||||
IPermissionRepository mockPermissionRepository = Substitute.For<IPermissionRepository>();
|
IPermissionRepository mockPermissionRepository = Substitute.For<IPermissionRepository>();
|
||||||
IRolePermissionRepository mockRolePermissionRepository = Substitute.For<IRolePermissionRepository>();
|
IRolePermissionRepository mockRolePermissionRepository = Substitute.For<IRolePermissionRepository>();
|
||||||
|
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||||
_mockUnitOfWork.GetRepository<IPermissionRepository>().Returns(mockPermissionRepository);
|
_mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository);
|
||||||
_mockUnitOfWork.GetRepository<IRolePermissionRepository>().Returns(mockRolePermissionRepository);
|
_mockUnitOfWork.RolePermissionRepository.Returns(mockRolePermissionRepository);
|
||||||
|
|
||||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||||
mockPermissionRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(permissions);
|
mockPermissionRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(permissions);
|
||||||
@@ -271,7 +271,7 @@ public class DataSeedServiceTests
|
|||||||
// Arrange
|
// Arrange
|
||||||
Guid userId = Guid.NewGuid();
|
Guid userId = Guid.NewGuid();
|
||||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||||
|
|
||||||
mockRoleRepository
|
mockRoleRepository
|
||||||
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
|
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
|
||||||
@@ -297,8 +297,8 @@ public class DataSeedServiceTests
|
|||||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||||
IPermissionRepository mockPermissionRepository = Substitute.For<IPermissionRepository>();
|
IPermissionRepository mockPermissionRepository = Substitute.For<IPermissionRepository>();
|
||||||
|
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||||
_mockUnitOfWork.GetRepository<IPermissionRepository>().Returns(mockPermissionRepository);
|
_mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository);
|
||||||
|
|
||||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||||
mockPermissionRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(expectedError);
|
mockPermissionRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(expectedError);
|
||||||
@@ -326,9 +326,9 @@ public class DataSeedServiceTests
|
|||||||
IPermissionRepository mockPermissionRepository = Substitute.For<IPermissionRepository>();
|
IPermissionRepository mockPermissionRepository = Substitute.For<IPermissionRepository>();
|
||||||
IRolePermissionRepository mockRolePermissionRepository = Substitute.For<IRolePermissionRepository>();
|
IRolePermissionRepository mockRolePermissionRepository = Substitute.For<IRolePermissionRepository>();
|
||||||
|
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||||
_mockUnitOfWork.GetRepository<IPermissionRepository>().Returns(mockPermissionRepository);
|
_mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository);
|
||||||
_mockUnitOfWork.GetRepository<IRolePermissionRepository>().Returns(mockRolePermissionRepository);
|
_mockUnitOfWork.RolePermissionRepository.Returns(mockRolePermissionRepository);
|
||||||
|
|
||||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||||
mockPermissionRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(permissions);
|
mockPermissionRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(permissions);
|
||||||
@@ -352,7 +352,7 @@ public class DataSeedServiceTests
|
|||||||
Error expectedError = Error.Failure("Role.NotFound", "Failed to retrieve admin role");
|
Error expectedError = Error.Failure("Role.NotFound", "Failed to retrieve admin role");
|
||||||
|
|
||||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||||
|
|
||||||
mockRoleRepository
|
mockRoleRepository
|
||||||
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
|
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
|
||||||
@@ -383,9 +383,9 @@ public class DataSeedServiceTests
|
|||||||
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
|
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
|
||||||
IUserRoleRepository mockUserRoleRepository = Substitute.For<IUserRoleRepository>();
|
IUserRoleRepository mockUserRoleRepository = Substitute.For<IUserRoleRepository>();
|
||||||
|
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(mockUserRepository);
|
_mockUnitOfWork.UserRepository.Returns(mockUserRepository);
|
||||||
_mockUnitOfWork.GetRepository<IUserRoleRepository>().Returns(mockUserRoleRepository);
|
_mockUnitOfWork.UserRoleRepository.Returns(mockUserRoleRepository);
|
||||||
|
|
||||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||||
mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>()).Returns(adminUser);
|
mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>()).Returns(adminUser);
|
||||||
@@ -417,7 +417,7 @@ public class DataSeedServiceTests
|
|||||||
// Arrange
|
// Arrange
|
||||||
Guid userId = Guid.NewGuid();
|
Guid userId = Guid.NewGuid();
|
||||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||||
|
|
||||||
mockRoleRepository
|
mockRoleRepository
|
||||||
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
|
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
|
||||||
@@ -442,8 +442,8 @@ public class DataSeedServiceTests
|
|||||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||||
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
|
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
|
||||||
|
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(mockUserRepository);
|
_mockUnitOfWork.UserRepository.Returns(mockUserRepository);
|
||||||
|
|
||||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||||
mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>()).Returns((UserEntity?)null);
|
mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>()).Returns((UserEntity?)null);
|
||||||
@@ -472,9 +472,9 @@ public class DataSeedServiceTests
|
|||||||
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
|
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
|
||||||
IUserRoleRepository mockUserRoleRepository = Substitute.For<IUserRoleRepository>();
|
IUserRoleRepository mockUserRoleRepository = Substitute.For<IUserRoleRepository>();
|
||||||
|
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(mockUserRepository);
|
_mockUnitOfWork.UserRepository.Returns(mockUserRepository);
|
||||||
_mockUnitOfWork.GetRepository<IUserRoleRepository>().Returns(mockUserRoleRepository);
|
_mockUnitOfWork.UserRoleRepository.Returns(mockUserRoleRepository);
|
||||||
|
|
||||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||||
mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>()).Returns(adminUser);
|
mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>()).Returns(adminUser);
|
||||||
@@ -498,7 +498,7 @@ public class DataSeedServiceTests
|
|||||||
Error expectedError = Error.Failure("Role.NotFound", "Failed to retrieve admin role");
|
Error expectedError = Error.Failure("Role.NotFound", "Failed to retrieve admin role");
|
||||||
|
|
||||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||||
|
|
||||||
mockRoleRepository
|
mockRoleRepository
|
||||||
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
|
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
|
||||||
@@ -525,8 +525,8 @@ public class DataSeedServiceTests
|
|||||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||||
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
|
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
|
||||||
|
|
||||||
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
|
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(mockUserRepository);
|
_mockUnitOfWork.UserRepository.Returns(mockUserRepository);
|
||||||
|
|
||||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||||
mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>()).Returns(expectedError);
|
mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>()).Returns(expectedError);
|
||||||
|
|||||||
@@ -1,18 +1,22 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using AutoFixture;
|
using AutoFixture;
|
||||||
using AutoFixture.AutoNSubstitute;
|
using AutoFixture.AutoNSubstitute;
|
||||||
|
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||||
|
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||||
|
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||||
|
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||||
using Lumina.Application.Common.DataAccess.UoW;
|
using Lumina.Application.Common.DataAccess.UoW;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Time;
|
using Lumina.Application.Common.Infrastructure.Time;
|
||||||
using Lumina.DataAccess.Common.DependencyInjection;
|
using Lumina.DataAccess.Common.DependencyInjection;
|
||||||
using Lumina.DataAccess.Core.Repositories.Common.Factory;
|
|
||||||
using Lumina.DataAccess.Core.UoW;
|
using Lumina.DataAccess.Core.UoW;
|
||||||
using Lumina.DataAccess.UnitTests.Common.Setup;
|
using Lumina.DataAccess.UnitTests.Common.Setup;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using NSubstitute;
|
using NSubstitute;
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -43,100 +47,50 @@ public class UnitOfWorkTests
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
/// <summary>
|
||||||
public void ResetRepositories_WhenCalled_ShouldClearAllRepositories()
|
/// Provides the repository properties exposed by the unit of work.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>An enumerable of tuples containing the repository property name and its accessor.</returns>
|
||||||
|
public static IEnumerable<object[]> GetRepositoryProperties()
|
||||||
{
|
{
|
||||||
// Arrange
|
yield return new object[] { nameof(IUnitOfWork.PermissionRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.PermissionRepository) };
|
||||||
ServiceCollection services = new();
|
yield return new object[] { nameof(IUnitOfWork.RolePermissionRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.RolePermissionRepository) };
|
||||||
DataAccessLayerServices.AddDataAccessLayerServices(services);
|
yield return new object[] { nameof(IUnitOfWork.RoleRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.RoleRepository) };
|
||||||
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
|
yield return new object[] { nameof(IUnitOfWork.UserRoleRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.UserRoleRepository) };
|
||||||
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
|
yield return new object[] { nameof(IUnitOfWork.BookRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.BookRepository) };
|
||||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
yield return new object[] { nameof(IUnitOfWork.DirectoryScanFingerprintRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.DirectoryScanFingerprintRepository) };
|
||||||
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
|
yield return new object[] { nameof(IUnitOfWork.LibraryRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryRepository) };
|
||||||
|
yield return new object[] { nameof(IUnitOfWork.LibraryScanRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryScanRepository) };
|
||||||
// Act
|
yield return new object[] { nameof(IUnitOfWork.LibraryScanSnapshotRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryScanSnapshotRepository) };
|
||||||
unitOfWork.ResetRepositories();
|
yield return new object[] { nameof(IUnitOfWork.LibraryScanStagingResultsRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryScanStagingResultsRepository) };
|
||||||
|
yield return new object[] { nameof(IUnitOfWork.LibraryMetadataProviderConfigurationRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryMetadataProviderConfigurationRepository) };
|
||||||
// Assert
|
yield return new object[] { nameof(IUnitOfWork.PluginRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.PluginRepository) };
|
||||||
Assert.Equal(0, unitOfWork.Repositories.Count);
|
yield return new object[] { nameof(IUnitOfWork.UserRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.UserRepository) };
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void AddRepositories_WhenCalled_ShouldAddRepositories()
|
[MemberData(nameof(GetRepositoryProperties))]
|
||||||
|
public void RepositoryProperty_WhenAccessed_ShouldReturnRepositoryAndCacheInstance(string propertyName, Func<UnitOfWork, object> repositoryAccessor)
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
ServiceCollection services = new();
|
UnitOfWork unitOfWork = CreateUnitOfWork();
|
||||||
DataAccessLayerServices.AddDataAccessLayerServices(services);
|
|
||||||
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
|
|
||||||
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
|
|
||||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
|
||||||
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
|
|
||||||
int initialCount = unitOfWork.Repositories.Count;
|
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
unitOfWork.ResetRepositories();
|
object firstAccess = repositoryAccessor(unitOfWork);
|
||||||
unitOfWork.AddRepositories();
|
object secondAccess = repositoryAccessor(unitOfWork);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.True(unitOfWork.Repositories.Count > 0);
|
Assert.NotNull(firstAccess);
|
||||||
Assert.Equal(initialCount, unitOfWork.Repositories.Count);
|
Assert.Same(firstAccess, secondAccess);
|
||||||
}
|
Assert.EndsWith(propertyName, firstAccess.GetType().Name);
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Constructor_WhenCalled_ShouldAddRepositories()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
IRepositoryFactory repositoryFactory = _fixture.Create<IRepositoryFactory>();
|
|
||||||
LuminaDbContext dbContext = _fixture.Create<LuminaDbContext>();
|
|
||||||
|
|
||||||
// Act
|
|
||||||
UnitOfWork unitOfWork = new(repositoryFactory, dbContext);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.True(unitOfWork.Repositories.Count > 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetRepository_WhenRepositoryNotAdded_ShouldReturnNull()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
ServiceCollection services = new();
|
|
||||||
DataAccessLayerServices.AddDataAccessLayerServices(services);
|
|
||||||
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
|
|
||||||
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
|
|
||||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
|
||||||
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
|
|
||||||
unitOfWork.ResetRepositories();
|
|
||||||
|
|
||||||
// Act
|
|
||||||
IBookRepository result = unitOfWork.GetRepository<IBookRepository>();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.Null(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetRepository_WhenRepositoriesAdded_ShouldReturnRepositories()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
ServiceCollection services = new();
|
|
||||||
DataAccessLayerServices.AddDataAccessLayerServices(services);
|
|
||||||
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
|
|
||||||
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
|
|
||||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
|
||||||
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
|
|
||||||
|
|
||||||
// Act & Assert
|
|
||||||
Assert.NotNull(unitOfWork.GetRepository<IBookRepository>());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task SaveChangesAsync_WhenCalled_ShouldCallDbContextSaveChangesAsync()
|
public async Task SaveChangesAsync_WhenCalled_ShouldCallDbContextSaveChangesAsync()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
IRepositoryFactory repositoryFactory = _fixture.Create<IRepositoryFactory>();
|
|
||||||
LuminaDbContext dbContext = _fixture.Create<LuminaDbContext>();
|
LuminaDbContext dbContext = _fixture.Create<LuminaDbContext>();
|
||||||
UnitOfWork unitOfWork = new(repositoryFactory, dbContext);
|
UnitOfWork unitOfWork = new(dbContext);
|
||||||
CancellationToken cancellationToken = new();
|
CancellationToken cancellationToken = new();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
@@ -145,4 +99,28 @@ public class UnitOfWorkTests
|
|||||||
// Assert
|
// Assert
|
||||||
await dbContext.Received(1).SaveChangesAsync(cancellationToken);
|
await dbContext.Received(1).SaveChangesAsync(cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void UnitOfWork_WhenResolvedFromServiceProvider_ShouldExposeRepositories()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
ServiceCollection services = new();
|
||||||
|
DataAccessLayerServices.AddDataAccessLayerServices(services);
|
||||||
|
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
|
||||||
|
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
|
||||||
|
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
IUnitOfWork unitOfWork = serviceProvider.GetRequiredService<IUnitOfWork>();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.NotNull(unitOfWork.PermissionRepository);
|
||||||
|
Assert.NotNull(unitOfWork.RoleRepository);
|
||||||
|
Assert.NotNull(unitOfWork.UserRepository);
|
||||||
|
}
|
||||||
|
|
||||||
|
private UnitOfWork CreateUnitOfWork()
|
||||||
|
{
|
||||||
|
return new(_fixture.Create<LuminaDbContext>());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -41,7 +41,7 @@ public class AuthorizationServiceTests
|
|||||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||||
_mockAuthorizationPolicyFactory = Substitute.For<IAuthorizationPolicyFactory>();
|
_mockAuthorizationPolicyFactory = Substitute.For<IAuthorizationPolicyFactory>();
|
||||||
|
|
||||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||||
|
|
||||||
_sut = new AuthorizationService(_mockUnitOfWork, _mockAuthorizationPolicyFactory);
|
_sut = new AuthorizationService(_mockUnitOfWork, _mockAuthorizationPolicyFactory);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user