Adds pagination and filtering to the API

This commit is contained in:
BinaryAlley committed 2026-08-16 03:10:47 -07:00
1 parent ad984910a2
commit ce4ebf36bc
59 files changed
+4423 -242

No files matched your search

@@ -0,0 +1,12 @@
namespace Lumina.Application.Common.DTO.Filtering;
/// <summary>
/// Data transfer object that defines common filter properties used when querying paginated data. Implementations may add additional properties specific to their module or domain.
/// </summary>
public record BaseFilterDto
{
/// <summary>
/// The search term used to filter results.
/// </summary>
public string? SearchTerm { get; init; }
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Application.Common.DTO.Filtering;
/// <summary>
/// Data transfer object that represents the parameters required to filter by library data.
/// </summary>
public record LibraryFilterDto : BaseFilterDto
{
/// <summary>
/// The Id of the media library used to filter data.
/// </summary>
public required Guid LibraryId { get; init; }
}
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Common.DTO.Pagination;
/// <summary>
/// Represents a paginated result containing a subset of data and pagination metadata for the current page.
/// </summary>
/// <typeparam name="TData">The type of the data items contained in the paginated result.</typeparam>
public sealed record PaginatedResultDto<TData>
{
/// <summary>
/// Gets the collection of data items associated with this instance.
/// </summary>
public required IReadOnlyList<TData> Data { get; init; }
/// <summary>
/// Gets the current page number in a paginated collection.
/// </summary>
public required int CurrentPage { get; init; }
/// <summary>
/// Gets or sets the number of items to include per page in paginated results.
/// </summary>
public required int PerPage { get; init; }
/// <summary>
/// Gets the total number of elements available in the paginated result set.
/// </summary>
public required int Count { get; init; }
/// <summary>
/// Gets the total number of pages based on elements available in the result set and per page.
/// </summary>
public required int NumberOfPages { get; init; }
}
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Application.Common.DTO.Pagination;
/// <summary>
/// Data transfer object for pagination metadata.
/// </summary>
public sealed record PaginationDataDto
{
private int perPage = 200;
private int currentPage = 1;
/// <summary>
/// Gets the current page number in a paginated collection.
/// </summary>
public int CurrentPage
{
get { return currentPage; }
set
{
currentPage = Math.Max(value, 1);
}
}
/// <summary>
/// Gets or sets the number of items to include per page in paginated results.
/// </summary>
public int PerPage
{
get { return perPage; }
set
{
perPage = Math.Max(value, 1);
}
}
}
@@ -18,7 +18,8 @@ public interface IBookRepository : IRepository<BookEntity>,
IInsertRepositoryAction<BookEntity>,
IUpdateRepositoryAction<BookEntity>,
IGetByIdRepositoryAction<BookEntity, Guid>,
IGetAllRepositoryAction<BookEntity>
IGetAllRepositoryAction<BookEntity>,
IGetPaginatedRepositoryAction<BookEntity>
{
/// <summary>
/// Gets all the books of the media library identified by <paramref name="libraryId"/>.
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Domain.Common.Primitives;
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 paginated" action for interacting with a generic persistence medium.
/// </summary>
/// <typeparam name="TModel">The type used as a result for the "get paginated" action. It should implement <see cref="IStorageEntity"/>.</typeparam>
public interface IGetPaginatedRepositoryAction<TModel> where TModel : IStorageEntity
{
/// <summary>
/// Gets paginated data of type <typeparamref name="TModel"/> from 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 current page and 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 parameters used to filter results.</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="TModel"/>, or an error.</returns>
Task<Result<PaginatedResultDto<TModel>>> GetPaginatedAsync<TFilter>(PaginationDataDto? paginationData, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto;
}
@@ -1,19 +1,20 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -225,8 +226,68 @@ public static class BookEntityMapping
/// </summary>
/// <param name="repositoryEntities">The repository entities to be converted.</param>
/// <returns>The converted reponses.</returns>
public static IEnumerable<BookResponse> ToResponses(this IEnumerable<BookEntity> repositoryEntities)
public static IReadOnlyList<BookResponse> ToResponses(this IEnumerable<BookEntity> repositoryEntities)
{
return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToResponse());
return [.. repositoryEntities.Select(repositoryEntity => repositoryEntity.ToResponse())];
}
/// <summary>
/// Converts <paramref name="repositoryEntities"/> to a paginated collection of <see cref="BookResponse"/>.
/// </summary>
/// <param name="repositoryEntities">The paginated repository entities to be converted.</param>
/// <returns>The converted paginated responses.</returns>
public static PaginatedResponse<BookResponse> ToResponses(this PaginatedResultDto<BookEntity> repositoryEntities)
{
return new PaginatedResponse<BookResponse>
{
Data = repositoryEntities.Data.ToResponses(),
CurrentPage = repositoryEntities.CurrentPage,
PerPage = repositoryEntities.PerPage,
Count = repositoryEntities.Count,
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,
// TODO: populate from the book cover when cover support is implemented
null
);
}
/// <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,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Extension methods for converting <see cref="GetBooksLiteRequest"/>.
/// </summary>
public static class GetBooksLiteRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetBooksLiteQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetBooksLiteQuery ToQuery(this GetBooksLiteRequest request)
{
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
};
return new GetBooksLiteQuery(paginationData, libraryFilter, request.SortBy, request.SortOrder);
}
}
@@ -1,4 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
#endregion
@@ -17,6 +19,20 @@ public static class GetBooksRequestMapping
/// <returns>The converted query.</returns>
public static GetBooksQuery ToQuery(this GetBooksRequest request)
{
return new GetBooksQuery(request.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
};
return new GetBooksQuery(paginationData, libraryFilter, request.SortBy, request.SortOrder);
}
}
@@ -0,0 +1,45 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Linq.Expressions;
#endregion
namespace Lumina.Application.Common.Specifications;
/// <summary>
/// Represents a filter specification that combines two filter specifications using a logical AND operation.
/// </summary>
/// <typeparam name="T">The type of entity to which the filter specification is applied.</typeparam>
internal class AndFilterSpecification<T> : FilterSpecification<T>
{
private readonly FilterSpecification<T> _left;
private readonly FilterSpecification<T> _right;
/// <summary>
/// Overload C-tor.
/// </summary>
/// <param name="left">The first filter specification to combine.</param>
/// <param name="right">The second filter specification to combine.</param>
public AndFilterSpecification(FilterSpecification<T> left, FilterSpecification<T> right)
{
_left = left;
_right = right;
}
/// <summary>
/// Creates a LINQ expression that represents the predicate defined by the current specification.
/// </summary>
/// <returns>An expression tree that can be used to evaluate whether an object of type <typeparamref name="T"/> satisfies the specification criteria.</returns>
public override Expression<Func<T, bool>> ToExpression()
{
Expression<Func<T, bool>> leftExpression = _left.ToExpression();
Expression<Func<T, bool>> rightExpression = _right.ToExpression();
ParameterExpression parameter = Expression.Parameter(typeof(T));
BinaryExpression combined = Expression.AndAlso(
Expression.Invoke(leftExpression, parameter),
Expression.Invoke(rightExpression, parameter)
);
return Expression.Lambda<Func<T, bool>>(combined, parameter);
}
}
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Linq.Expressions;
#endregion
namespace Lumina.Application.Common.Specifications;
/// <summary>
/// Represents the abstract base for a filtering specification, enabling the encapsulation of business query logic as reusable objects.
/// </summary>
/// <typeparam name="T">The type of entity to which the specification applies.</typeparam>
public abstract class FilterSpecification<T>
{
/// <summary>
/// Creates a LINQ expression that represents the predicate defined by the current specification.
/// </summary>
/// <returns>An expression tree that can be used to evaluate whether an object of type <typeparamref name="T"/> satisfies the specification criteria.</returns>
public abstract Expression<Func<T, bool>> ToExpression();
/// <summary>
/// Determines whether the specified entity satisfies the criteria defined by the specification.
/// </summary>
/// <param name="entity">The entity to evaluate against the specification criteria.</param>
/// <returns><see langword="true"/> if the entity satisfies the specification; <see langword="false"/> otherwise.</returns>
public bool IsSatisfiedBy(T entity)
{
Func<T, bool> predicate = ToExpression().Compile();
return predicate(entity);
}
/// <summary>
/// Combines the current filter specification with another specification using a logical AND operation.
/// </summary>
/// <param name="specification">The filter specification to combine with the current specification.</param>
/// <returns>A new filter specification that is satisfied if both the current specification and the specified specification is satisfied.</returns>
public FilterSpecification<T> And(FilterSpecification<T> specification)
{
return new AndFilterSpecification<T>(this, specification);
}
/// <summary>
/// Combines the current filter specification with another specification using a logical OR operation.
/// </summary>
/// <param name="specification">The filter specification to combine with the current specification.</param>
/// <returns>A new filter specification that is satisfied if either the current specification or the specified specification is satisfied.</returns>
public FilterSpecification<T> Or(FilterSpecification<T> specification)
{
return new OrFilterSpecification<T>(this, specification);
}
}
@@ -0,0 +1,45 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Linq.Expressions;
#endregion
namespace Lumina.Application.Common.Specifications;
/// <summary>
/// Represents a filter specification that combines two filter specifications using a logical OR operation.
/// </summary>
/// <typeparam name="T">The type of entity to which the filter specification is applied.</typeparam>
internal class OrFilterSpecification<T> : FilterSpecification<T>
{
private readonly FilterSpecification<T> _left;
private readonly FilterSpecification<T> _right;
/// <summary>
/// Overload C-tor.
/// </summary>
/// <param name="left">The first filter specification to combine.</param>
/// <param name="right">The second filter specification to combine.</param>
public OrFilterSpecification(FilterSpecification<T> left, FilterSpecification<T> right)
{
_left = left;
_right = right;
}
/// <summary>
/// Creates a LINQ expression that represents the predicate defined by the current specification.
/// </summary>
/// <returns>An expression tree that can be used to evaluate whether an object of type <typeparamref name="T"/> satisfies the specification criteria.</returns>
public override Expression<Func<T, bool>> ToExpression()
{
Expression<Func<T, bool>> leftExpression = _left.ToExpression();
Expression<Func<T, bool>> rightExpression = _right.ToExpression();
ParameterExpression parameter = Expression.Parameter(typeof(T));
BinaryExpression combined = Expression.OrElse(
Expression.Invoke(leftExpression, parameter),
Expression.Invoke(rightExpression, parameter)
);
return Expression.Lambda<Func<T, bool>>(combined, parameter);
}
}
@@ -1,6 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
@@ -8,7 +10,13 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar
/// <summary>
/// Query for getting all the books of a media library.
/// </summary>
/// <param name="LibraryId">The Id of the media library whose books are retrieved.</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="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(
Guid LibraryId
PaginationDataDto? PaginationData,
LibraryFilterDto Filter,
string? SortBy,
SortOrder? SortOrder
) : IQuery;
@@ -9,6 +9,13 @@ using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Lumina.Contracts.Responses.Common;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DTO.Pagination;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
@@ -16,17 +23,26 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar
/// <summary>
/// Handler for the query to get all books.
/// </summary>
public class GetBooksQueryHandler : IQueryHandler<GetBooksQuery, Result<IEnumerable<BookResponse>>>
public class GetBooksQueryHandler : IQueryHandler<GetBooksQuery, Result<PaginatedResponse<BookResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetBooksQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetBooksQueryHandler(IUnitOfWork unitOfWork)
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public GetBooksQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetBooksQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
@@ -37,10 +53,28 @@ public class GetBooksQueryHandler : IQueryHandler<GetBooksQuery, Result<IEnumera
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a collection of <see cref="BookResponse"/>, or an error message.
/// </returns>
public async Task<Result<IEnumerable<BookResponse>>> HandleAsync(GetBooksQuery query, CancellationToken cancellationToken)
public async Task<Result<PaginatedResponse<BookResponse>>> HandleAsync(GetBooksQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// check if the user has the rights to access the library they are requesting (admins can see all libraries)
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin) // if its not an admin, then it must own the library
{
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Filter.LibraryId, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value?.UserId != _currentUserService.UserId)
return Errors.Authorization.NotAuthorized;
}
// get all books of the media library from the book repository
Result<IEnumerable<BookEntity>> getBooksResult = await _unitOfWork.BookRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
return getBooksResult.Match(result => Result.From(getBooksResult.Value.ToResponses()), errors => errors);
Result<PaginatedResultDto<BookEntity>> getBooksResult = await _unitOfWork.BookRepository.GetPaginatedAsync(
query.PaginationData,
query.SortBy,
query.SortOrder,
query.Filter,
cancellationToken).ConfigureAwait(false);
return getBooksResult.Match(value => Result.From(value.ToResponses()), errors => errors);
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
/// <summary>
/// Validates the needed validation rules for <see cref="GetBooksQuery"/>.
/// </summary>
public class GetBooksQueryValidator : AbstractValidator<GetBooksQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksQueryValidator"/> class.
/// </summary>
public GetBooksQueryValidator()
{
RuleFor(query => query.Filter.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -0,0 +1,22 @@
#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
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
/// <summary>
/// Query for getting the lightweight details of all the books of a media library.
/// </summary>
/// <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="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(
PaginationDataDto? PaginationData,
LibraryFilterDto Filter,
string? SortBy,
SortOrder? SortOrder
) : IQuery;
@@ -0,0 +1,80 @@
#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.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Lumina.Contracts.Responses.Common;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DTO.Pagination;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
/// <summary>
/// Handler for the query to get the lightweight details of all books.
/// </summary>
public class GetBooksLiteQueryHandler : IQueryHandler<GetBooksLiteQuery, Result<PaginatedResponse<BookLiteResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetBooksLiteQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksLiteQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public GetBooksLiteQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetBooksLiteQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the lightweight details of all books.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a collection of <see cref="BookLiteResponse"/>, or an error message.
/// </returns>
public async Task<Result<PaginatedResponse<BookLiteResponse>>> HandleAsync(GetBooksLiteQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// check if the user has the rights to access the library they are requesting (admins can see all libraries)
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin) // if its not an admin, then it must own the library
{
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Filter.LibraryId, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value?.UserId != _currentUserService.UserId)
return Errors.Authorization.NotAuthorized;
}
// get all books of the media library from the book repository
Result<PaginatedResultDto<BookEntity>> getBooksResult = await _unitOfWork.BookRepository.GetPaginatedAsync(
query.PaginationData,
query.SortBy,
query.SortOrder,
query.Filter,
cancellationToken).ConfigureAwait(false);
return getBooksResult.Match(value => Result.From(value.ToLiteResponses()), errors => errors);
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
/// <summary>
/// Validates the needed validation rules for <see cref="GetBooksLiteQuery"/>.
/// </summary>
public class GetBooksLiteQueryValidator : AbstractValidator<GetBooksLiteQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksLiteQueryValidator"/> class.
/// </summary>
public GetBooksLiteQueryValidator()
{
RuleFor(query => query.Filter.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -25,8 +25,4 @@
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Common\CQRS\" />
</ItemGroup>
</Project>
@@ -0,0 +1,12 @@
namespace Lumina.Contracts.DTO.Common.Filtering;
/// <summary>
/// Data transfer object that defines common filter properties used when quering paginated data. Implementations may add additional properties specific to their module or domain.
/// </summary>
public record BaseFilterDto
{
/// <summary>
/// The search term used to filter results.
/// </summary>
public string? SearchTerm { get; init; }
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Contracts.DTO.Common.Filtering;
/// <summary>
/// Data transfer object that represents the parameters required to filter by library data.
/// </summary>
public record LibraryFilterDto : BaseFilterDto
{
/// <summary>
/// The Id of the media library used to filter data.
/// </summary>
public required Guid LibraryId { get; init; }
}
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Contracts.DTO.Common.Pagination;
/// <summary>
/// Data transfer object for pagination metadata.
/// </summary>
public sealed record PaginationDataDto
{
private int perPage = 200;
private int currentPage = 1;
/// <summary>
/// Gets the current page number in a paginated collection.
/// </summary>
public int CurrentPage
{
get { return currentPage; }
set
{
currentPage = Math.Max(value, 1);
}
}
/// <summary>
/// Gets or sets the number of items to include per page in paginated results.
/// </summary>
public int PerPage
{
get { return perPage; }
set
{
perPage = Math.Max(value, 1);
}
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Represents a request to get the lightweight details of the books of a media library.
/// </summary>
/// <param name="LibraryId">The Id of the media library whose books are retrieved. Required.</param>
/// <param name="CurrentPage">The page of results to retrieve. Optional.</param>
/// <param name="PerPage">The maximum number of books to retrieve per page. Optional.</param>
/// <param name="SearchTerm">The search term used to filter results. Optional.</param>
/// <param name="SortBy">The name of the field by which to sort the results. Optional.</param>
/// <param name="SortOrder">The direction in which to sort the results. Optional.</param>
[DebuggerDisplay("LibraryId: {LibraryId}")]
public record GetBooksLiteRequest(
Guid LibraryId,
int? CurrentPage,
int? PerPage,
string? SearchTerm,
string? SortBy,
SortOrder? SortOrder
);
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System;
using System.Diagnostics;
#endregion
@@ -9,7 +10,17 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra
/// Represents a request to get the books of a media library.
/// </summary>
/// <param name="LibraryId">The Id of the media library whose books are retrieved. Required.</param>
/// <param name="CurrentPage">The page of results to retrieve. Optional.</param>
/// <param name="PerPage">The maximum number of books to retrieve per page. Optional.</param>
/// <param name="SearchTerm">The search term used to filter results. Optional.</param>
/// <param name="SortBy">The name of the field by which to sort the results. Optional.</param>
/// <param name="SortOrder">The direction in which to sort the results. Optional.</param>
[DebuggerDisplay("LibraryId: {LibraryId}")]
public record GetBooksRequest(
Guid LibraryId
Guid LibraryId,
int? CurrentPage,
int? PerPage,
string? SearchTerm,
string? SortBy,
SortOrder? SortOrder
);
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
#endregion
namespace Lumina.Contracts.Responses.Common;
/// <summary>
/// Represents a paginated response containing a subset of data and pagination metadata for the current page.
/// </summary>
/// <typeparam name="TData">The type of the data items contained in the paginated response.</typeparam>
public sealed record PaginatedResponse<TData>
{
/// <summary>
/// Gets the collection of data items associated with this instance.
/// </summary>
public required IReadOnlyList<TData> Data { get; init; }
/// <summary>
/// Gets the current page number in a paginated collection.
/// </summary>
public required int CurrentPage { get; init; }
/// <summary>
/// Gets or sets the number of items to include per page in paginated results.
/// </summary>
public required int PerPage { get; init; }
/// <summary>
/// Gets the total number of elements available in the paginated result set.
/// </summary>
public required int Count { get; init; }
/// <summary>
/// Gets the total number of pages based on elements available in the result set and per page.
/// </summary>
public required int NumberOfPages { get; init; }
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Represents a lightweight book response, containing only the properties needed by the client for card-style navigation.
/// </summary>
/// <param name="Id">The Id of the book.</param>
/// <param name="Title">The title of the book.</param>
/// <param name="ReleaseYear">The release year of the book (re-release year, if available, or original release year), if known.</param>
/// <param name="CoverPath">The path of the image representing the cover of the book, if available.</param>
[DebuggerDisplay("Title: {Title}")]
public record BookLiteResponse(
Guid Id,
string Title,
int? ReleaseYear,
string? CoverPath
);
@@ -1,11 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Specifications;
using Lumina.DataAccess.Core.Repositories.Books.Specifications;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
@@ -54,8 +59,8 @@ internal sealed class BookRepository : IBookRepository
.ToListAsync(cancellationToken).ConfigureAwait(false);
// replace tags and genres in the book with existing ones
book.Tags = new HashSet<TagEntity>(book.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag));
book.Genres = new HashSet<GenreEntity>(book.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre));
book.Tags = [.. book.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)];
book.Genres = [.. book.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)];
_luminaDbContext.Books.Add(book);
return Result.Created;
@@ -90,6 +95,73 @@ internal sealed class BookRepository : IBookRepository
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets paginated books.
/// </summary>
/// <typeparam name="TFilter">The type of the filter used for filtering the data.</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 books are returned.</param>
/// <param name="sortBy">The name of the fields 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="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PaginatedResultDto{BookEntity}"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<BookEntity>>> GetPaginatedAsync<TFilter>(PaginationDataDto? paginationData, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
{
IQueryable<BookEntity> booksQuery = _luminaDbContext.Books
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.AsNoTracking();
// books should always be retrieved only per owning libraries
if (filterModel is not LibraryFilterDto libraryFilter || libraryFilter.LibraryId == Guid.Empty)
return Errors.Library.FilterMustIncludeLibraryId;
booksQuery = booksQuery.Where(book => book.LibraryId == libraryFilter.LibraryId);
FilterSpecification<BookEntity>? filterSpecification = BuildFilterSpecification(libraryFilter.SearchTerm);
// apply filtering
if (filterSpecification is not null)
booksQuery = booksQuery.Where(filterSpecification.ToExpression());
// apply sorting based on the specified sortBy and sortOrder parameters
booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending);
// if no pagination was requested, return all the books of the library
if (paginationData is null)
{
IReadOnlyList<BookEntity> allBooks = await booksQuery.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<BookEntity>
{
Data = allBooks,
CurrentPage = 1,
PerPage = allBooks.Count,
Count = allBooks.Count,
NumberOfPages = 1
};
}
int count = await booksQuery.Select(book => book.Id).CountAsync(cancellationToken).ConfigureAwait(false);
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // make sure current page doesn't exceed maximum number of pages
// apply pagination
IReadOnlyList<BookEntity> paginatedResult = await booksQuery
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<BookEntity>
{
Data = paginatedResult,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
/// <summary>
/// Gets all the books of the media library identified by <paramref name="libraryId"/>.
/// </summary>
@@ -176,4 +248,45 @@ internal sealed class BookRepository : IBookRepository
_luminaDbContext.Entry(foundBook).CurrentValues.SetValues(data);
return Result.Updated;
}
/// <summary>
/// Sorts a books query by the given field name, defaulting to <see cref="BookEntity.Title"/>.
/// </summary>
/// <param name="booksQuery">The query to sort.</param>
/// <param name="sortBy">The field to sort by (case-insensitive).</param>
/// <param name="sortOrder">The direction of the sorting.</param>
private static IOrderedQueryable<BookEntity> ApplySorting(IQueryable<BookEntity> booksQuery, string? sortBy, SortOrder sortOrder)
{
return sortBy?.ToLower() switch
{
"languagecode" => sortOrder == SortOrder.Descending
? booksQuery.OrderByDescending(book => book.LanguageCode)
: booksQuery.OrderBy(book => book.LanguageCode),
"format" => sortOrder == SortOrder.Descending
? booksQuery.OrderBy(book => book.Format == null).ThenByDescending(book => book.Format)
: booksQuery.OrderBy(book => book.Format == null).ThenBy(book => book.Format),
"metadataprovider" => sortOrder == SortOrder.Descending
? booksQuery.OrderByDescending(book => book.MetadataProvider)
: booksQuery.OrderBy(book => book.MetadataProvider),
_ => sortOrder == SortOrder.Descending
? booksQuery.OrderByDescending(book => book.Title)
: booksQuery.OrderBy(book => book.Title),
};
}
/// <summary>
/// Builds a filter specification for querying books.
/// </summary>
/// <param name="searchTerm">The search term used to filter results.</param>
/// <returns>A filter specification that can be used to query books matching the provided criteria.</returns>
private static FilterSpecification<BookEntity>? BuildFilterSpecification(string? searchTerm)
{
FilterSpecification<BookEntity>? filterSpecification = null;
// include the search term filter here, if provided
if (!string.IsNullOrWhiteSpace(searchTerm))
filterSpecification = new BookSearchSpecification(searchTerm);
return filterSpecification;
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.Specifications;
using System;
using System.Linq.Expressions;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Books.Specifications;
/// <summary>
/// Represents a filter specification for filtering or searching book entities based on a search term.
/// </summary>
internal sealed class BookSearchSpecification : FilterSpecification<BookEntity>
{
private readonly string _searchTerm;
/// <summary>
/// Initializes a new instance of the <see cref="BookSearchSpecification"/> class.
/// </summary>
/// <param name="searchTerm">The term to use when filtering or searching for books.</param>
public BookSearchSpecification(string searchTerm)
{
_searchTerm = searchTerm;
}
/// <summary>
/// Creates a LINQ expression that represents the predicate defined by the current specification.
/// </summary>
/// <returns>An expression tree that can be used to evaluate whether a <see cref="BookEntity"/> satisfies the specification criteria.</returns>
public override Expression<Func<BookEntity, bool>> ToExpression()
{
return book => book.Title.Contains(_searchTerm) || (book.OriginalTitle != null && book.OriginalTitle.Contains(_searchTerm));
}
}
@@ -0,0 +1,17 @@
namespace Lumina.Domain.SharedKernel.Common.Enums.Common;
/// <summary>
/// Enumeration for the sort order
/// </summary>
public enum SortOrder
{
/// <summary>
/// Ascending order.
/// </summary>
Ascending,
/// <summary>
/// Descending order.
/// </summary>
Descending
}
@@ -14,6 +14,7 @@ public static partial class Errors
public static Error CannotScanLockedLibrary => Error.Forbidden(description: nameof(CannotScanLockedLibrary));
public static Error CannotScanDisabledLibrary => Error.Forbidden(description: nameof(CannotScanDisabledLibrary));
public static Error LibraryIdCannotBeEmpty => Error.Validation(description: nameof(LibraryIdCannotBeEmpty));
public static Error FilterMustIncludeLibraryId => Error.Validation(description: nameof(FilterMustIncludeLibraryId));
public static Error LibraryAlreadyExists => Error.Conflict(description: nameof(LibraryAlreadyExists));
public static Error LibraryNotFound => Error.NotFound(description: nameof(LibraryNotFound));
public static Error LibraryTypeCannotBeNull => Error.Validation(description: nameof(LibraryTypeCannotBeNull));
@@ -12,6 +12,7 @@ public static partial class ApiRoutes
{
public const string GET_BOOK_BY_ID = "/books/{id}";
public const string GET_BOOKS = "/books";
public const string GET_BOOKS_LITE = "/books/lite";
public const string ADD_BOOK = "/books";
}
}
@@ -4,6 +4,7 @@ using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary;
@@ -21,13 +22,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B
/// </summary>
public class GetBooksEndpoint : BaseEndpoint<GetBooksRequest, IResult>
{
private readonly IQueryHandler<GetBooksQuery, Result<IEnumerable<BookResponse>>> _getBooksQueryHandler;
private readonly IQueryHandler<GetBooksQuery, Result<PaginatedResponse<BookResponse>>> _getBooksQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksEndpoint"/> class.
/// </summary>
/// <param name="getBooksQueryHandler">Injected service for handling get books queries.</param>
public GetBooksEndpoint(IQueryHandler<GetBooksQuery, Result<IEnumerable<BookResponse>>> getBooksQueryHandler)
public GetBooksEndpoint(IQueryHandler<GetBooksQuery, Result<PaginatedResponse<BookResponse>>> getBooksQueryHandler)
{
_getBooksQueryHandler = getBooksQueryHandler;
}
@@ -50,7 +51,7 @@ public class GetBooksEndpoint : BaseEndpoint<GetBooksRequest, IResult>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetBooksRequest request, CancellationToken cancellationToken)
{
Result<IEnumerable<BookResponse>> result = await _getBooksQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
Result<PaginatedResponse<BookResponse>> result = await _getBooksQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -3,6 +3,7 @@ using FastEndpoints;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
@@ -27,221 +28,228 @@ public class GetBooksEndpointSummary : Summary<GetBooksEndpoint>
Description = "Returns the entire list of books.";
Response(200, "The list of books is returned.",
example: new BookResponse[] {
new(
Id: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/books/the-fellowship-of-the-ring.epub",
Metadata: new(
Title: "The Fellowship of the Ring",
OriginalTitle: "The Fellowship of the Ring",
Description: "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.",
ReleaseInfo: new(
OriginalReleaseDate: DateOnly.ParseExact("1954-07-29", "yyyy-MM-dd", null),
OriginalReleaseYear: 1954,
ReReleaseDate: DateOnly.ParseExact("2001-09-06", "yyyy-MM-dd", null),
ReReleaseYear: 2001,
ReleaseCountry: "uk",
ReleaseVersion: "50th Anniversary Edition"
),
Genres: new List<GenreDto>() {
{ new(Name: "fantasy") },
{ new(Name: "adventure") },
{ new(Name: "classic") }
},
Tags: new List<TagDto>() {
{ new(Name: "epic fantasy") },
{ new(Name: "quest") },
{ new(Name: "middle-earth") }
},
Language: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
OriginalLanguage: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
Publisher: "Houghton Mifflin",
PageCount: 398
Response(200, "The paginated list of books is returned.",
example: new PaginatedResponse<BookResponse>
{
Data = [
new(
Id: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/books/the-fellowship-of-the-ring.epub",
Metadata: new(
Title: "The Fellowship of the Ring",
OriginalTitle: "The Fellowship of the Ring",
Description: "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.",
ReleaseInfo: new(
OriginalReleaseDate: DateOnly.ParseExact("1954-07-29", "yyyy-MM-dd", null),
OriginalReleaseYear: 1954,
ReReleaseDate: DateOnly.ParseExact("2001-09-06", "yyyy-MM-dd", null),
ReReleaseYear: 2001,
ReleaseCountry: "uk",
ReleaseVersion: "50th Anniversary Edition"
),
Genres: new List<GenreDto>() {
{ new(Name: "fantasy") },
{ new(Name: "adventure") },
{ new(Name: "classic") }
},
Tags: new List<TagDto>() {
{ new(Name: "epic fantasy") },
{ new(Name: "quest") },
{ new(Name: "middle-earth") }
},
Language: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
OriginalLanguage: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
Publisher: "Houghton Mifflin",
PageCount: 398
),
Format: BookFormat.Paperback,
Edition: "50th Anniversary Edition",
VolumeNumber: 1,
Series: new BookSeriesDto(
Title: "The Lord of the Rings"
),
ASIN: "B007978NPG",
GoodreadsId: "3",
LCCN: "54009621",
OCLCNumber: "ocm00012345",
OpenLibraryId: "OL7603910M",
LibraryThingId: "3203347",
GoogleBooksId: "aWZzLPhY4o0C",
BarnesAndNobleId: "1100307790",
AppleBooksId: "id395211",
ISBNs: [
new(
Value: "0395272238",
Format: IsbnFormat.Isbn10
),
new(
Value: "9780395272237",
Format: IsbnFormat.Isbn13
)
],
Contributors: [
new(
Name: new MediaContributorNameDto(
DisplayName: "J.R.R. Tolkien",
LegalName: "John Ronald Reuel Tolkien"
Format: BookFormat.Paperback,
Edition: "50th Anniversary Edition",
VolumeNumber: 1,
Series: new BookSeriesDto(
Title: "The Lord of the Rings"
),
ASIN: "B007978NPG",
GoodreadsId: "3",
LCCN: "54009621",
OCLCNumber: "ocm00012345",
OpenLibraryId: "OL7603910M",
LibraryThingId: "3203347",
GoogleBooksId: "aWZzLPhY4o0C",
BarnesAndNobleId: "1100307790",
AppleBooksId: "id395211",
ISBNs: [
new(
Value: "0395272238",
Format: IsbnFormat.Isbn10
),
Role: new MediaContributorRoleDto(
Name: "author",
Category: "book"
new(
Value: "9780395272237",
Format: IsbnFormat.Isbn13
)
),
new(
Name: new MediaContributorNameDto(
DisplayName: "Alan Lee",
LegalName: "Alan Lee"
],
Contributors: [
new(
Name: new MediaContributorNameDto(
DisplayName: "J.R.R. Tolkien",
LegalName: "John Ronald Reuel Tolkien"
),
Role: new MediaContributorRoleDto(
Name: "author",
Category: "book"
)
),
Role: new MediaContributorRoleDto(
Name: "illustrator",
Category: "book"
new(
Name: new MediaContributorNameDto(
DisplayName: "Alan Lee",
LegalName: "Alan Lee"
),
Role: new MediaContributorRoleDto(
Name: "illustrator",
Category: "book"
)
)
)
],
Ratings: [
new(
Source: BookRatingSource.GoogleBooks,
Value: 4.36M,
MaxValue: 5,
VoteCount: 2345678
),
new(
Source: BookRatingSource.Amazon,
Value: 4.7M,
MaxValue: 5,
VoteCount: 87654
)
],
MetadataStatus: MetadataStatus.Pending,
LastMetadataUpdateUtc: default,
MetadataProvider: default,
CreatedOnUtc: DateTime.UtcNow,
UpdatedOnUtc: default
),
new(
Id: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/books/the-two-towers.epub",
Metadata: new(
Title: "The Two Towers",
OriginalTitle: "The Two Towers",
Description: "The second part of J.R.R. Tolkien's epic adventure The Lord of the Rings. The Fellowship is scattered, and the quest to destroy the One Ring continues. Aragorn, Legolas, and Gimli search for Merry and Pippin, while Frodo and Sam take the Ring closer to Mordor under the guidance of the mysterious Gollum.",
ReleaseInfo: new(
OriginalReleaseDate: DateOnly.ParseExact("1954-11-11", "yyyy-MM-dd", null),
OriginalReleaseYear: 1954,
ReReleaseDate: DateOnly.ParseExact("2001-11-08", "yyyy-MM-dd", null),
ReReleaseYear: 2001,
ReleaseCountry: "uk",
ReleaseVersion: "50th Anniversary Edition"
),
Genres: new List<GenreDto>() {
{ new(Name: "fantasy") },
{ new(Name: "adventure") },
{ new(Name: "classic") }
},
Tags: new List<TagDto>() {
{ new(Name: "epic fantasy") },
{ new(Name: "quest") },
{ new(Name: "middle-earth") }
},
Language: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
OriginalLanguage: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
Publisher: "Houghton Mifflin",
PageCount: 352
],
Ratings: [
new(
Source: BookRatingSource.GoogleBooks,
Value: 4.36M,
MaxValue: 5,
VoteCount: 2345678
),
new(
Source: BookRatingSource.Amazon,
Value: 4.7M,
MaxValue: 5,
VoteCount: 87654
)
],
MetadataStatus: MetadataStatus.Pending,
LastMetadataUpdateUtc: default,
MetadataProvider: default,
CreatedOnUtc: DateTime.UtcNow,
UpdatedOnUtc: default
),
Format: BookFormat.Hardcover,
Edition: "50th Anniversary Edition",
VolumeNumber: 2,
Series: new BookSeriesDto(
Title: "The Lord of the Rings"
),
ASIN: "B007978NPZ",
GoodreadsId: "33",
LCCN: "54009622",
OCLCNumber: "ocm00067890",
OpenLibraryId: "OL7603911M",
LibraryThingId: "3203348",
GoogleBooksId: "aWZzLPhY4o1D",
BarnesAndNobleId: "1100307791",
AppleBooksId: "id395212",
ISBNs: [
new(
Value: "0395272246",
Format: IsbnFormat.Isbn10
),
new(
Value: "9780395272244",
Format: IsbnFormat.Isbn13
)
],
Contributors: [
new(
Name: new MediaContributorNameDto(
DisplayName: "J.R.R. Tolkien",
LegalName: "John Ronald Reuel Tolkien"
new(
Id: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/books/the-two-towers.epub",
Metadata: new(
Title: "The Two Towers",
OriginalTitle: "The Two Towers",
Description: "The second part of J.R.R. Tolkien's epic adventure The Lord of the Rings. The Fellowship is scattered, and the quest to destroy the One Ring continues. Aragorn, Legolas, and Gimli search for Merry and Pippin, while Frodo and Sam take the Ring closer to Mordor under the guidance of the mysterious Gollum.",
ReleaseInfo: new(
OriginalReleaseDate: DateOnly.ParseExact("1954-11-11", "yyyy-MM-dd", null),
OriginalReleaseYear: 1954,
ReReleaseDate: DateOnly.ParseExact("2001-11-08", "yyyy-MM-dd", null),
ReReleaseYear: 2001,
ReleaseCountry: "uk",
ReleaseVersion: "50th Anniversary Edition"
),
Role: new MediaContributorRoleDto(
Name: "author",
Category: "book"
)
),
new(
Name: new MediaContributorNameDto(
DisplayName: "Alan Lee",
LegalName: "Alan Lee"
Genres: new List<GenreDto>() {
{ new(Name: "fantasy") },
{ new(Name: "adventure") },
{ new(Name: "classic") }
},
Tags: new List<TagDto>() {
{ new(Name: "epic fantasy") },
{ new(Name: "quest") },
{ new(Name: "middle-earth") }
},
Language: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
Role: new MediaContributorRoleDto(
Name: "illustrator",
Category: "book"
)
)
],
Ratings: [
new(
Source: BookRatingSource.GoogleBooks,
Value: 4.4M,
MaxValue: 5,
VoteCount: 2340000
OriginalLanguage: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
Publisher: "Houghton Mifflin",
PageCount: 352
),
new(
Source: BookRatingSource.Amazon,
Value: 4.8M,
MaxValue: 5,
VoteCount: 90000
)
],
MetadataStatus: MetadataStatus.Pending,
LastMetadataUpdateUtc: default,
MetadataProvider: default,
CreatedOnUtc: DateTime.UtcNow,
UpdatedOnUtc: default
)
Format: BookFormat.Hardcover,
Edition: "50th Anniversary Edition",
VolumeNumber: 2,
Series: new BookSeriesDto(
Title: "The Lord of the Rings"
),
ASIN: "B007978NPZ",
GoodreadsId: "33",
LCCN: "54009622",
OCLCNumber: "ocm00067890",
OpenLibraryId: "OL7603911M",
LibraryThingId: "3203348",
GoogleBooksId: "aWZzLPhY4o1D",
BarnesAndNobleId: "1100307791",
AppleBooksId: "id395212",
ISBNs: [
new(
Value: "0395272246",
Format: IsbnFormat.Isbn10
),
new(
Value: "9780395272244",
Format: IsbnFormat.Isbn13
)
],
Contributors: [
new(
Name: new MediaContributorNameDto(
DisplayName: "J.R.R. Tolkien",
LegalName: "John Ronald Reuel Tolkien"
),
Role: new MediaContributorRoleDto(
Name: "author",
Category: "book"
)
),
new(
Name: new MediaContributorNameDto(
DisplayName: "Alan Lee",
LegalName: "Alan Lee"
),
Role: new MediaContributorRoleDto(
Name: "illustrator",
Category: "book"
)
)
],
Ratings: [
new(
Source: BookRatingSource.GoogleBooks,
Value: 4.4M,
MaxValue: 5,
VoteCount: 2340000
),
new(
Source: BookRatingSource.Amazon,
Value: 4.8M,
MaxValue: 5,
VoteCount: 90000
)
],
MetadataStatus: MetadataStatus.Pending,
LastMetadataUpdateUtc: default,
MetadataProvider: default,
CreatedOnUtc: DateTime.UtcNow,
UpdatedOnUtc: default
)
],
CurrentPage = 1,
PerPage = 10,
Count = 2,
NumberOfPages = 1
}
);
@@ -275,5 +283,26 @@ public class GetBooksEndpointSummary : Summary<GetBooksEndpoint>
}
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/books",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite;
/// <summary>
/// API endpoint for the <c>/books/lite</c> route.
/// </summary>
public class GetBooksLiteEndpoint : BaseEndpoint<GetBooksLiteRequest, IResult>
{
private readonly IQueryHandler<GetBooksLiteQuery, Result<PaginatedResponse<BookLiteResponse>>> _getBooksLiteQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksLiteEndpoint"/> class.
/// </summary>
/// <param name="getBooksLiteQueryHandler">Injected service for handling get books lite queries.</param>
public GetBooksLiteEndpoint(IQueryHandler<GetBooksLiteQuery, Result<PaginatedResponse<BookLiteResponse>>> getBooksLiteQueryHandler)
{
_getBooksLiteQueryHandler = getBooksLiteQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Books.GET_BOOKS_LITE);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the lightweight details of all the books of the media library identified by <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the Id of the media library whose books are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetBooksLiteRequest request, CancellationToken cancellationToken)
{
Result<PaginatedResponse<BookLiteResponse>> result = await _getBooksLiteQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,101 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetBooksLiteEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksLiteEndpointSummary : Summary<GetBooksLiteEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksLiteEndpointSummary"/> class.
/// </summary>
public GetBooksLiteEndpointSummary()
{
Summary = "Retrieves the lightweight details of the list of books.";
Description = "Returns a paginated list of the lightweight details of the books of the media library, suitable for card-style navigation.";
Response(200, "The paginated list of lightweight book details is returned.",
example: new PaginatedResponse<BookLiteResponse>
{
Data = [
new(
Id: Guid.NewGuid(),
Title: "The Fellowship of the Ring",
ReleaseYear: 1954,
CoverPath: null
),
new(
Id: Guid.NewGuid(),
Title: "The Two Towers",
ReleaseYear: 1954,
CoverPath: null
)
],
CurrentPage = 1,
PerPage = 10,
Count = 2,
NumberOfPages = 1
}
);
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/books/lite"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Invalid token: The token expired at '01/01/2024 01:00:00'",
instance = "/api/v1/books/lite"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = "/api/v1/books/lite"
}
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/books/lite",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}