Refactors the get books and get books lite slices across the stack

This commit is contained in:
BinaryAlley committed 2026-09-13 04:16:59 -07:00
1 parent 001146eefc
commit 1d35cd01db
44 files changed
+1681 -418

No files matched your search

@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Lightweight read model of a book, containing only the fields needed to display the book in a card-based grid or a list.
/// </summary>
public sealed record BookLiteRow
{
/// <summary>
/// Gets the Id of the book.
/// </summary>
public required Guid Id { get; init; }
/// <summary>
/// Gets the title of the book.
/// </summary>
public required string Title { get; init; }
/// <summary>
/// Gets the release year of the book (re-release year, if available, or original release year), if known.
/// </summary>
public int? ReleaseYear { get; init; }
/// <summary>
/// Gets the path of the image representing the cover of the book, if available.
/// </summary>
public string? CoverPath { get; init; }
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
/// <summary>
/// Interface defining the "get all lite" action for interacting with a generic persistence medium.
/// It retrieves lightweight read models of the stored data, projecting only the fields needed to display
/// the data in grids or card-based navigation, without loading the full entities and their related data.
/// </summary>
/// <typeparam name="TModel">The type stored in the persistence medium, which is projected into the lightweight read models. It should implement <see cref="IStorageEntity"/>.</typeparam>
/// <typeparam name="TLiteRow">The type of the lightweight read models returned by the action.</typeparam>
public interface IGetAllLiteRepositoryAction<TModel, TLiteRow> where TModel : IStorageEntity
{
/// <summary>
/// Gets the lightweight read models of type <typeparamref name="TLiteRow"/>, projected from the data of type <typeparamref name="TModel"/> stored in the storage medium.
/// </summary>
/// <typeparam name="TFilter">The type of the filter carrying the criteria used to filter the results.</typeparam>
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all matching data is returned.</param>
/// <param name="sortBy">The name of the field by which to sort the results.</param>
/// <param name="sortOrder">The direction in which to sort the results.</param>
/// <param name="filterModel">The model containing the parameters used to filter the results.</param>
/// <param name="includeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a paginated result of type <typeparamref name="TLiteRow"/>, or an error.</returns>
Task<Result<PaginatedResultDto<TLiteRow>>> GetAllLiteAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool includeNavigationProperties = false, bool shouldTrackEntities = false, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto;
}
@@ -256,46 +256,4 @@ public static class BookEntityMapping
NumberOfPages = repositoryEntities.NumberOfPages
};
}
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="BookLiteResponse"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <returns>The converted response entity.</returns>
public static BookLiteResponse ToLiteResponse(this BookEntity repositoryEntity)
{
return new BookLiteResponse(
repositoryEntity.Id,
repositoryEntity.Title,
repositoryEntity.ReReleaseYear ?? repositoryEntity.OriginalReleaseYear,
repositoryEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover)?.FileName
);
}
/// <summary>
/// Converts <paramref name="repositoryEntities"/> to a collection of <see cref="BookLiteResponse"/>.
/// </summary>
/// <param name="repositoryEntities">The repository entities to be converted.</param>
/// <returns>The converted reponses.</returns>
public static IReadOnlyList<BookLiteResponse> ToLiteResponses(this IEnumerable<BookEntity> repositoryEntities)
{
return [.. repositoryEntities.Select(repositoryEntity => repositoryEntity.ToLiteResponse())];
}
/// <summary>
/// Converts <paramref name="repositoryEntities"/> to a paginated collection of <see cref="BookLiteResponse"/>.
/// </summary>
/// <param name="repositoryEntities">The paginated repository entities to be converted.</param>
/// <returns>The converted paginated responses.</returns>
public static PaginatedResponse<BookLiteResponse> ToLiteResponses(this PaginatedResultDto<BookEntity> repositoryEntities)
{
return new PaginatedResponse<BookLiteResponse>
{
Data = repositoryEntities.Data.ToLiteResponses(),
CurrentPage = repositoryEntities.CurrentPage,
PerPage = repositoryEntities.PerPage,
Count = repositoryEntities.Count,
NumberOfPages = repositoryEntities.NumberOfPages
};
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Extension methods for converting <see cref="BookLiteRow"/>.
/// </summary>
public static class BookLiteRowMapping
{
/// <summary>
/// Converts <paramref name="readModel"/> to <see cref="BookLiteResponse"/>.
/// </summary>
/// <param name="readModel">The read model to be converted.</param>
/// <returns>The converted response.</returns>
public static BookLiteResponse ToResponse(this BookLiteRow readModel)
{
return new BookLiteResponse(
readModel.Id,
readModel.Title,
readModel.ReleaseYear,
readModel.CoverPath);
}
/// <summary>
/// Converts <paramref name="readModels"/> to a collection of <see cref="BookLiteResponse"/>.
/// </summary>
/// <param name="readModels">The read models to be converted.</param>
/// <returns>The converted responses.</returns>
public static IReadOnlyList<BookLiteResponse> ToResponses(this IEnumerable<BookLiteRow> readModels)
{
return [.. readModels.Select(readModel => readModel.ToResponse())];
}
/// <summary>
/// Converts <paramref name="readModels"/> to a paginated collection of <see cref="BookLiteResponse"/>.
/// </summary>
/// <param name="readModels">The paginated read models to be converted.</param>
/// <returns>The converted paginated responses.</returns>
public static PaginatedResponse<BookLiteResponse> ToResponses(this PaginatedResultDto<BookLiteRow> readModels)
{
return new PaginatedResponse<BookLiteResponse>
{
Data = readModels.Data.ToResponses(),
CurrentPage = readModels.CurrentPage,
PerPage = readModels.PerPage,
Count = readModels.Count,
NumberOfPages = readModels.NumberOfPages
};
}
}
@@ -16,26 +16,26 @@ public static class GetBooksLiteRequestMapping
/// Converts <paramref name="request"/> to <see cref="GetBooksLiteQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <param name="libraryId">The Id of the library whose books are retrieved, taken from the route.</param>
/// <returns>The converted query.</returns>
public static GetBooksLiteQuery ToQuery(this GetBooksLiteRequest request)
public static GetBooksLiteQuery ToQuery(this GetBooksLiteRequest request, string? libraryId)
{
PaginationDataDto? paginationData = null;
if (request.CurrentPage is not null || request.PerPage is not null)
{
paginationData = new PaginationDataDto
{
CurrentPage = request.CurrentPage ?? 1,
PerPage = request.PerPage ?? 200
};
}
LibraryFilterDto libraryFilter = new()
{
LibraryId = request.LibraryId,
SearchTerm = request.SearchTerm,
FilterAlphaKey = request.FilterAlphaKey,
ShouldIgnoreThePrefixForAlphaPicker = request.ShouldIgnoreThePrefixForAlphaPicker
};
return new GetBooksLiteQuery(paginationData, libraryFilter, request.SortBy, request.SortOrder);
return new GetBooksLiteQuery(
libraryId,
paginationData,
request.SearchTerm,
request.FilterAlphaKey,
request.ShouldIgnoreThePrefixForAlphaPicker,
request.SortBy,
request.SortOrder
);
}
}
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
@@ -16,8 +15,9 @@ public static class GetBooksRequestMapping
/// Converts <paramref name="request"/> to <see cref="GetBooksQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <param name="libraryId">The Id of the library whose books are retrieved, taken from the route.</param>
/// <returns>The converted query.</returns>
public static GetBooksQuery ToQuery(this GetBooksRequest request)
public static GetBooksQuery ToQuery(this GetBooksRequest request, string? libraryId)
{
PaginationDataDto? paginationData = null;
if (request.CurrentPage is not null || request.PerPage is not null)
@@ -27,12 +27,6 @@ public static class GetBooksRequestMapping
PerPage = request.PerPage ?? 200
};
LibraryFilterDto libraryFilter = new()
{
LibraryId = request.LibraryId,
SearchTerm = request.SearchTerm
};
return new GetBooksQuery(paginationData, libraryFilter, request.SortBy, request.SortOrder);
return new GetBooksQuery(libraryId, paginationData, request.SearchTerm, request.SortBy, request.SortOrder);
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
#endregion
@@ -10,13 +9,15 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <summary>
/// Query for getting all the books of a media library.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library whose books are retrieved, taken from the route.</param>
/// <param name="PaginationData">The object containing the requested pagination data.</param>
/// <param name="Filter">The object containing the criteria used to filter the results.</param>
/// <param name="SearchTerm">The search term used to filter results.</param>
/// <param name="SortBy">The name of the field by which to sort the results.</param>
/// <param name="SortOrder">The direction in which to sort the results.</param>
public record GetBooksQuery(
string? LibraryId,
PaginationDataDto? PaginationData,
LibraryFilterDto Filter,
string? SearchTerm,
string? SortBy,
SortOrder? SortOrder
) : IQuery;
@@ -16,6 +16,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
#endregion
@@ -60,25 +61,34 @@ public class GetBooksQueryHandler : IQueryHandler<GetBooksQuery, Result<Paginate
if (validationResult.Count > 0)
return validationResult;
// an authenticated request must always carry a user identity
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// admins can see all libraries; for everyone else, only the libraries they own
// The validator guarantees that the library id of the route is a non-empty Guid before this point.
Guid libraryId = Guid.Parse(query.LibraryId!);
// Admins can see all libraries; for everyone else, only the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(query.Filter.LibraryId), cancellationToken).ConfigureAwait(false);
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return Errors.Authorization.NotAuthorized;
// get all books of the media library from the book repository
Result<PaginatedResultDto<BookEntity>> getBooksResult = await _unitOfWork.BookRepository.GetPaginatedAsync(
// Get all books of the media library from the book repository.
LibraryFilterDto libraryFilter = new()
{
LibraryId = libraryId,
SearchTerm = query.SearchTerm
};
Result<PaginatedResultDto<BookEntity>> getBooksResult = await _unitOfWork.BookRepository.GetAllAsync(
query.PaginationData,
query.SortBy,
query.SortOrder,
query.Filter,
cancellationToken).ConfigureAwait(false);
libraryFilter,
shouldTrackEntities: false,
cancellationToken: cancellationToken).ConfigureAwait(false);
return getBooksResult.Match(value => Result.From(value.ToResponses()), errors => errors);
}
}
@@ -17,10 +17,14 @@ public class GetBooksQueryValidator : AbstractValidator<GetBooksQuery>
/// </summary>
public GetBooksQueryValidator()
{
RuleFor(query => query.Filter.LibraryId)
// Validates the identifier of the media library whose books are retrieved, taken from the route.
RuleFor(query => query.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(query => query.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(query => query.LibraryId is not null && query.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
#endregion
@@ -10,13 +9,19 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <summary>
/// Query for getting the lightweight details of all the books of a media library.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library whose books are retrieved, taken from the route.</param>
/// <param name="PaginationData">The object containing the requested pagination data.</param>
/// <param name="Filter">The object containing the criteria used to filter the results.</param>
/// <param name="SearchTerm">The search term used to filter results.</param>
/// <param name="FilterAlphaKey">The alpha key used to filter results by the first character of their title.</param>
/// <param name="ShouldIgnoreThePrefixForAlphaPicker">Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.</param>
/// <param name="SortBy">The name of the field by which to sort the results.</param>
/// <param name="SortOrder">The direction in which to sort the results.</param>
public record GetBooksLiteQuery(
string? LibraryId,
PaginationDataDto? PaginationData,
LibraryFilterDto Filter,
string? SearchTerm,
string? FilterAlphaKey,
bool ShouldIgnoreThePrefixForAlphaPicker,
string? SortBy,
SortOrder? SortOrder
) : IQuery;
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
@@ -16,6 +16,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
#endregion
@@ -60,25 +61,37 @@ public class GetBooksLiteQueryHandler : IQueryHandler<GetBooksLiteQuery, Result<
if (validationResult.Count > 0)
return validationResult;
// an authenticated request must always carry a user identity
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// admins can see all libraries; for everyone else, only the libraries they own
// The validator guarantees that the library id of the route is a non-empty Guid before this point.
Guid libraryId = Guid.Parse(query.LibraryId!);
// Admins can see all libraries; for everyone else, only the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(query.Filter.LibraryId), cancellationToken).ConfigureAwait(false);
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return Errors.Authorization.NotAuthorized;
// get all books of the media library from the book repository
Result<PaginatedResultDto<BookEntity>> getBooksResult = await _unitOfWork.BookRepository.GetPaginatedAsync(
LibraryFilterDto libraryFilter = new()
{
LibraryId = libraryId,
SearchTerm = query.SearchTerm,
FilterAlphaKey = query.FilterAlphaKey,
ShouldIgnoreThePrefixForAlphaPicker = query.ShouldIgnoreThePrefixForAlphaPicker
};
// Get the lightweight read models of the books of the media library from the book repository, projecting only the fields needed for a grid or a list.
Result<PaginatedResultDto<BookLiteRow>> getBooksResult = await _unitOfWork.BookRepository.GetAllLiteAsync(
query.PaginationData,
query.SortBy,
query.SortOrder,
query.Filter,
cancellationToken).ConfigureAwait(false);
return getBooksResult.Match(value => Result.From(value.ToLiteResponses()), errors => errors);
libraryFilter,
shouldTrackEntities: false,
cancellationToken: cancellationToken).ConfigureAwait(false);
return getBooksResult.Match(value => Result.From(value.ToResponses()), errors => errors);
}
}
@@ -18,15 +18,19 @@ public class GetBooksLiteQueryValidator : AbstractValidator<GetBooksLiteQuery>
/// </summary>
public GetBooksLiteQueryValidator()
{
RuleFor(query => query.Filter.LibraryId)
// Validates the identifier of the media library whose books are retrieved, taken from the route.
RuleFor(query => query.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(query => query.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(query => query.LibraryId is not null && query.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// the alpha key must be exactly one of the three picker bucket kinds, so that the filter specification can
// derive the key of a title unambiguously: no filter, a number bucket, a symbol bucket, or a single ASCII letter
RuleFor(query => query.Filter.FilterAlphaKey)
RuleFor(query => query.FilterAlphaKey)
.Must(alphaKey => alphaKey is null
|| alphaKey == LibraryItemAlphaKeys.NUMBER
|| alphaKey == LibraryItemAlphaKeys.SYMBOL