mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 17:11:10 +00:00
Adds alpha picker filtering to the books lite query
This commit is contained in:
1 parent
e72625de7c
commit
6fa154a2e7
12 files changed
+375
-9
No files matched your search
@@ -13,4 +13,17 @@ public record LibraryFilterDto : BaseFilterDto
|
|||||||
/// The Id of the media library used to filter data.
|
/// The Id of the media library used to filter data.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public required Guid LibraryId { get; init; }
|
public required Guid LibraryId { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The alpha key used to filter the data by the first character of the item title, for the alpha picker.
|
||||||
|
/// Can be <see langword="null"/> to disable alpha filtering, a single ASCII letter (case-insensitive) to filter by that letter,
|
||||||
|
/// <see cref="LibraryItemAlphaKeys.NUMBER"/> to filter by titles whose first character is a digit,
|
||||||
|
/// or <see cref="LibraryItemAlphaKeys.SYMBOL"/> to filter by titles whose first character is neither a letter nor a digit.
|
||||||
|
/// </summary>
|
||||||
|
public string? FilterAlphaKey { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.
|
||||||
|
/// </summary>
|
||||||
|
public bool IgnoreThePrefixForAlphaPicker { get; init; }
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Common.DTO.Filtering;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Collection of the special alpha keys that can be used for alpha filtering, in addition to the single letters.
|
||||||
|
/// </summary>
|
||||||
|
public static class LibraryItemAlphaKeys
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The alpha key that filters the items by titles whose first character is a digit.
|
||||||
|
/// </summary>
|
||||||
|
public const string NUMBER = "#";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The alpha key that filters the items by titles whose first character is neither a letter nor a digit.
|
||||||
|
/// </summary>
|
||||||
|
public const string SYMBOL = "*";
|
||||||
|
}
|
||||||
+3
-1
@@ -30,7 +30,9 @@ public static class GetBooksLiteRequestMapping
|
|||||||
LibraryFilterDto libraryFilter = new()
|
LibraryFilterDto libraryFilter = new()
|
||||||
{
|
{
|
||||||
LibraryId = request.LibraryId,
|
LibraryId = request.LibraryId,
|
||||||
SearchTerm = request.SearchTerm
|
SearchTerm = request.SearchTerm,
|
||||||
|
FilterAlphaKey = request.FilterAlphaKey,
|
||||||
|
IgnoreThePrefixForAlphaPicker = request.IgnoreThePrefixForAlphaPicker
|
||||||
};
|
};
|
||||||
|
|
||||||
return new GetBooksLiteQuery(paginationData, libraryFilter, request.SortBy, request.SortOrder);
|
return new GetBooksLiteQuery(paginationData, libraryFilter, request.SortBy, request.SortOrder);
|
||||||
|
|||||||
+10
@@ -1,4 +1,5 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Common.DTO.Filtering;
|
||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Common.Utilities;
|
using Lumina.Application.Common.Utilities;
|
||||||
using Lumina.Domain.Common.Errors;
|
using Lumina.Domain.Common.Errors;
|
||||||
@@ -22,5 +23,14 @@ public class GetBooksLiteQueryValidator : AbstractValidator<GetBooksLiteQuery>
|
|||||||
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
|
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
|
||||||
.Must(id => id != Guid.Empty)
|
.Must(id => id != Guid.Empty)
|
||||||
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
|
.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)
|
||||||
|
.Must(alphaKey => alphaKey is null
|
||||||
|
|| alphaKey == LibraryItemAlphaKeys.NUMBER
|
||||||
|
|| alphaKey == LibraryItemAlphaKeys.SYMBOL
|
||||||
|
|| (alphaKey.Length == 1 && char.IsAsciiLetter(alphaKey[0])))
|
||||||
|
.WithError(Errors.Library.InvalidFilterAlphaKey);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+8
@@ -13,6 +13,12 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra
|
|||||||
/// <param name="CurrentPage">The page of results to retrieve. Optional.</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="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="SearchTerm">The search term used to filter results. Optional.</param>
|
||||||
|
/// <param name="FilterAlphaKey">
|
||||||
|
/// The alpha key used to filter the results by the first character of their title, for the alpha picker. Optional.
|
||||||
|
/// Can be <see langword="null"/> to disable alpha filtering, a single ASCII letter (case-insensitive) to filter by that letter,
|
||||||
|
/// "#" to filter by titles whose first character is a digit, or "*" to filter by titles whose first character is neither a letter nor a digit.
|
||||||
|
/// </param>
|
||||||
|
/// <param name="IgnoreThePrefixForAlphaPicker">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. 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>
|
/// <param name="SortOrder">The direction in which to sort the results. Optional.</param>
|
||||||
[DebuggerDisplay("LibraryId: {LibraryId}")]
|
[DebuggerDisplay("LibraryId: {LibraryId}")]
|
||||||
@@ -21,6 +27,8 @@ public record GetBooksLiteRequest(
|
|||||||
int? CurrentPage,
|
int? CurrentPage,
|
||||||
int? PerPage,
|
int? PerPage,
|
||||||
string? SearchTerm,
|
string? SearchTerm,
|
||||||
|
string? FilterAlphaKey,
|
||||||
|
bool IgnoreThePrefixForAlphaPicker,
|
||||||
string? SortBy,
|
string? SortBy,
|
||||||
SortOrder? SortOrder
|
SortOrder? SortOrder
|
||||||
);
|
);
|
||||||
@@ -120,7 +120,7 @@ internal sealed class BookRepository : IBookRepository
|
|||||||
|
|
||||||
booksQuery = booksQuery.Where(book => book.LibraryId == libraryFilter.LibraryId);
|
booksQuery = booksQuery.Where(book => book.LibraryId == libraryFilter.LibraryId);
|
||||||
|
|
||||||
FilterSpecification<BookEntity>? filterSpecification = BuildFilterSpecification(libraryFilter.SearchTerm);
|
FilterSpecification<BookEntity>? filterSpecification = BuildFilterSpecification(libraryFilter);
|
||||||
// apply filtering
|
// apply filtering
|
||||||
if (filterSpecification is not null)
|
if (filterSpecification is not null)
|
||||||
booksQuery = booksQuery.Where(filterSpecification.ToExpression());
|
booksQuery = booksQuery.Where(filterSpecification.ToExpression());
|
||||||
@@ -277,15 +277,24 @@ internal sealed class BookRepository : IBookRepository
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Builds a filter specification for querying books.
|
/// Builds a filter specification for querying books.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="searchTerm">The search term used to filter results.</param>
|
/// <param name="libraryFilter">The model containing the parameters used to filter the results.</param>
|
||||||
/// <returns>A filter specification that can be used to query books matching the provided criteria.</returns>
|
/// <returns>A filter specification that can be used to query books matching the provided criteria.</returns>
|
||||||
private static FilterSpecification<BookEntity>? BuildFilterSpecification(string? searchTerm)
|
private static FilterSpecification<BookEntity>? BuildFilterSpecification(LibraryFilterDto libraryFilter)
|
||||||
{
|
{
|
||||||
FilterSpecification<BookEntity>? filterSpecification = null;
|
FilterSpecification<BookEntity>? filterSpecification = null;
|
||||||
|
|
||||||
// include the search term filter here, if provided
|
// include the search term filter, if provided
|
||||||
if (!string.IsNullOrWhiteSpace(searchTerm))
|
if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm))
|
||||||
filterSpecification = new BookSearchSpecification(searchTerm);
|
filterSpecification = new BookSearchSpecification(libraryFilter.SearchTerm);
|
||||||
|
|
||||||
|
// include the alpha key filter, if provided
|
||||||
|
if (libraryFilter.FilterAlphaKey is not null)
|
||||||
|
{
|
||||||
|
BookAlphaFilterSpecification alphaFilterSpecification = new(libraryFilter.FilterAlphaKey, libraryFilter.IgnoreThePrefixForAlphaPicker);
|
||||||
|
filterSpecification = filterSpecification is null
|
||||||
|
? alphaFilterSpecification
|
||||||
|
: filterSpecification.And(alphaFilterSpecification);
|
||||||
|
}
|
||||||
|
|
||||||
return filterSpecification;
|
return filterSpecification;
|
||||||
}
|
}
|
||||||
|
|||||||
+132
@@ -0,0 +1,132 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||||
|
using Lumina.Application.Common.DTO.Filtering;
|
||||||
|
using Lumina.Application.Common.Specifications;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using System;
|
||||||
|
using System.Linq.Expressions;
|
||||||
|
using System.Reflection;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.DataAccess.Core.Repositories.Books.Specifications;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Represents a filter specification for filtering books by the alpha key of their title, for the alpha picker.
|
||||||
|
/// The alpha key is the first character of the title, lowercased, and optionally computed after ignoring a leading "The " prefix.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class BookAlphaFilterSpecification : FilterSpecification<BookEntity>
|
||||||
|
{
|
||||||
|
private static readonly MethodInfo s_toLowerMethod = typeof(string).GetMethod(nameof(string.ToLower), Type.EmptyTypes)!;
|
||||||
|
private static readonly MethodInfo s_startsWithMethod = typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string)])!;
|
||||||
|
private static readonly MethodInfo s_substringMethod = typeof(string).GetMethod(nameof(string.Substring), [typeof(int)])!;
|
||||||
|
private static readonly MethodInfo s_globMethod = typeof(SqliteDbFunctionsExtensions)
|
||||||
|
.GetMethod(nameof(SqliteDbFunctionsExtensions.Glob), [typeof(DbFunctions), typeof(string), typeof(string)])!;
|
||||||
|
|
||||||
|
private readonly string? _filterAlphaKey;
|
||||||
|
private readonly bool _ignoreThePrefixForAlphaPicker;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="BookAlphaFilterSpecification"/> class.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="filterAlphaKey">The alpha key to filter by. A single ASCII letter, <see cref="LibraryItemAlphaKeys.NUMBER"/>, or <see cref="LibraryItemAlphaKeys.SYMBOL"/>.</param>
|
||||||
|
/// <param name="ignoreThePrefixForAlphaPicker">Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.</param>
|
||||||
|
public BookAlphaFilterSpecification(string? filterAlphaKey, bool ignoreThePrefixForAlphaPicker)
|
||||||
|
{
|
||||||
|
_filterAlphaKey = filterAlphaKey;
|
||||||
|
_ignoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <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()
|
||||||
|
{
|
||||||
|
// when no alpha key was requested, every book matches
|
||||||
|
if (_filterAlphaKey is null)
|
||||||
|
return book => true;
|
||||||
|
|
||||||
|
ParameterExpression book = Expression.Parameter(typeof(BookEntity), "book");
|
||||||
|
Expression effectiveTitle = BuildEffectiveTitle(book);
|
||||||
|
|
||||||
|
if (_filterAlphaKey == LibraryItemAlphaKeys.NUMBER)
|
||||||
|
return BuildGlobPredicate(book, effectiveTitle, "[0-9]*");
|
||||||
|
|
||||||
|
if (_filterAlphaKey == LibraryItemAlphaKeys.SYMBOL)
|
||||||
|
return BuildSymbolPredicate(book, effectiveTitle);
|
||||||
|
|
||||||
|
// the alpha key is a single ASCII letter
|
||||||
|
string globPattern = char.ToLowerInvariant(_filterAlphaKey[0]) + "*";
|
||||||
|
return BuildGlobPredicate(book, effectiveTitle, globPattern);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds the expression representing the lowercased title used to derive the alpha key, falling back to the original title
|
||||||
|
/// when the title is <see langword="null"/> or empty, and optionally stripped of a leading "the " prefix.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="book">The parameter representing the book entity.</param>
|
||||||
|
/// <returns>The expression of the effective title.</returns>
|
||||||
|
private Expression BuildEffectiveTitle(ParameterExpression book)
|
||||||
|
{
|
||||||
|
Expression titleProperty = Expression.Property(book, nameof(BookEntity.Title));
|
||||||
|
|
||||||
|
// the raw title: the title, unless it is null or empty, in which case the original title (or an empty string) is used
|
||||||
|
BinaryExpression isTitleMissing = Expression.OrElse(
|
||||||
|
Expression.Equal(titleProperty, Expression.Constant(null, typeof(string))),
|
||||||
|
Expression.Equal(titleProperty, Expression.Constant(string.Empty)));
|
||||||
|
Expression rawTitle = Expression.Condition(isTitleMissing,
|
||||||
|
Expression.Coalesce(Expression.Property(book, nameof(BookEntity.OriginalTitle)), Expression.Constant(string.Empty)),
|
||||||
|
titleProperty);
|
||||||
|
|
||||||
|
MethodCallExpression lowerTitle = Expression.Call(rawTitle, s_toLowerMethod);
|
||||||
|
|
||||||
|
// when ignoring the "The " prefix, strip a leading "the " from the lowercased title
|
||||||
|
Expression effectiveTitle = lowerTitle;
|
||||||
|
if (_ignoreThePrefixForAlphaPicker)
|
||||||
|
{
|
||||||
|
MethodCallExpression startsWithThe = Expression.Call(lowerTitle, s_startsWithMethod, Expression.Constant("the "));
|
||||||
|
MethodCallExpression strippedTitle = Expression.Call(lowerTitle, s_substringMethod, Expression.Constant(4));
|
||||||
|
effectiveTitle = Expression.Condition(startsWithThe, strippedTitle, lowerTitle);
|
||||||
|
}
|
||||||
|
|
||||||
|
return effectiveTitle;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds a predicate that is satisfied when the effective title starts with a glob pattern.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="book">The parameter representing the book entity.</param>
|
||||||
|
/// <param name="effectiveTitle">The expression of the effective title.</param>
|
||||||
|
/// <param name="globPattern">The glob pattern the effective title must match.</param>
|
||||||
|
/// <returns>The built predicate.</returns>
|
||||||
|
private static Expression<Func<BookEntity, bool>> BuildGlobPredicate(ParameterExpression book, Expression effectiveTitle, string globPattern)
|
||||||
|
{
|
||||||
|
MethodCallExpression glob = BuildGlobCall(effectiveTitle, globPattern);
|
||||||
|
return Expression.Lambda<Func<BookEntity, bool>>(glob, book);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds a predicate that is satisfied when the first character of the effective title is neither a letter nor a digit.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="book">The parameter representing the book entity.</param>
|
||||||
|
/// <param name="effectiveTitle">The expression of the effective title.</param>
|
||||||
|
/// <returns>The built predicate.</returns>
|
||||||
|
private static Expression<Func<BookEntity, bool>> BuildSymbolPredicate(ParameterExpression book, Expression effectiveTitle)
|
||||||
|
{
|
||||||
|
Expression notLetter = Expression.Not(BuildGlobCall(effectiveTitle, "[a-z]*"));
|
||||||
|
Expression notDigit = Expression.Not(BuildGlobCall(effectiveTitle, "[0-9]*"));
|
||||||
|
return Expression.Lambda<Func<BookEntity, bool>>(Expression.AndAlso(notLetter, notDigit), book);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds the call to <see cref="SqliteDbFunctionsExtensions.Glob"/> for the effective title and the provided glob pattern.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="effectiveTitle">The expression of the effective title.</param>
|
||||||
|
/// <param name="globPattern">The glob pattern the effective title must match.</param>
|
||||||
|
/// <returns>The built method call.</returns>
|
||||||
|
private static MethodCallExpression BuildGlobCall(Expression effectiveTitle, string globPattern)
|
||||||
|
{
|
||||||
|
Expression functions = Expression.Property(null, typeof(EF), nameof(EF.Functions));
|
||||||
|
return Expression.Call(s_globMethod, functions, effectiveTitle, Expression.Constant(globPattern));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ public static partial class Errors
|
|||||||
public static Error CannotScanDisabledLibrary => Error.Forbidden(description: nameof(CannotScanDisabledLibrary));
|
public static Error CannotScanDisabledLibrary => Error.Forbidden(description: nameof(CannotScanDisabledLibrary));
|
||||||
public static Error LibraryIdCannotBeEmpty => Error.Validation(description: nameof(LibraryIdCannotBeEmpty));
|
public static Error LibraryIdCannotBeEmpty => Error.Validation(description: nameof(LibraryIdCannotBeEmpty));
|
||||||
public static Error FilterMustIncludeLibraryId => Error.Validation(description: nameof(FilterMustIncludeLibraryId));
|
public static Error FilterMustIncludeLibraryId => Error.Validation(description: nameof(FilterMustIncludeLibraryId));
|
||||||
|
public static Error InvalidFilterAlphaKey => Error.Validation(description: nameof(InvalidFilterAlphaKey));
|
||||||
public static Error LibraryAlreadyExists => Error.Conflict(description: nameof(LibraryAlreadyExists));
|
public static Error LibraryAlreadyExists => Error.Conflict(description: nameof(LibraryAlreadyExists));
|
||||||
public static Error LibraryNotFound => Error.NotFound(description: nameof(LibraryNotFound));
|
public static Error LibraryNotFound => Error.NotFound(description: nameof(LibraryNotFound));
|
||||||
public static Error LibraryTypeCannotBeNull => Error.Validation(description: nameof(LibraryTypeCannotBeNull));
|
public static Error LibraryTypeCannotBeNull => Error.Validation(description: nameof(LibraryTypeCannotBeNull));
|
||||||
|
|||||||
+7
-1
@@ -26,6 +26,8 @@ public class GetBooksLiteQueryFixture
|
|||||||
/// <param name="libraryId">Optional. The Id of the media library whose books are retrieved.</param>
|
/// <param name="libraryId">Optional. The Id of the media library whose books are retrieved.</param>
|
||||||
/// <param name="paginationData">Optional. The pagination data of the query.</param>
|
/// <param name="paginationData">Optional. The pagination data of the query.</param>
|
||||||
/// <param name="searchTerm">Optional. The search term used to filter results.</param>
|
/// <param name="searchTerm">Optional. The search term used to filter results.</param>
|
||||||
|
/// <param name="filterAlphaKey">Optional. The alpha key used to filter the results by the first character of their title, for the alpha picker.</param>
|
||||||
|
/// <param name="ignoreThePrefixForAlphaPicker">Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.</param>
|
||||||
/// <param name="sortBy">Optional. The name of the field by which to sort the results.</param>
|
/// <param name="sortBy">Optional. The name of the field by which to sort the results.</param>
|
||||||
/// <param name="sortOrder">Optional. The direction in which to sort the results.</param>
|
/// <param name="sortOrder">Optional. The direction in which to sort the results.</param>
|
||||||
/// <returns>The created query to get the lightweight details of books.</returns>
|
/// <returns>The created query to get the lightweight details of books.</returns>
|
||||||
@@ -33,6 +35,8 @@ public class GetBooksLiteQueryFixture
|
|||||||
Guid? libraryId = null,
|
Guid? libraryId = null,
|
||||||
PaginationDataDto? paginationData = null,
|
PaginationDataDto? paginationData = null,
|
||||||
string? searchTerm = null,
|
string? searchTerm = null,
|
||||||
|
string? filterAlphaKey = null,
|
||||||
|
bool ignoreThePrefixForAlphaPicker = false,
|
||||||
string? sortBy = null,
|
string? sortBy = null,
|
||||||
SortOrder? sortOrder = null)
|
SortOrder? sortOrder = null)
|
||||||
{
|
{
|
||||||
@@ -45,7 +49,9 @@ public class GetBooksLiteQueryFixture
|
|||||||
new LibraryFilterDto
|
new LibraryFilterDto
|
||||||
{
|
{
|
||||||
LibraryId = libraryId ?? _faker.Random.Guid(),
|
LibraryId = libraryId ?? _faker.Random.Guid(),
|
||||||
SearchTerm = searchTerm
|
SearchTerm = searchTerm,
|
||||||
|
FilterAlphaKey = filterAlphaKey,
|
||||||
|
IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker
|
||||||
},
|
},
|
||||||
sortBy,
|
sortBy,
|
||||||
sortOrder ?? _faker.PickRandom<SortOrder>()
|
sortOrder ?? _faker.PickRandom<SortOrder>()
|
||||||
|
|||||||
+6
@@ -25,6 +25,8 @@ public class GetBooksLiteRequestFixture
|
|||||||
/// <param name="currentPage">Optional. The page of results to retrieve.</param>
|
/// <param name="currentPage">Optional. The page of results to retrieve.</param>
|
||||||
/// <param name="perPage">Optional. The maximum number of books to retrieve per page.</param>
|
/// <param name="perPage">Optional. The maximum number of books to retrieve per page.</param>
|
||||||
/// <param name="searchTerm">Optional. The search term used to filter results.</param>
|
/// <param name="searchTerm">Optional. The search term used to filter results.</param>
|
||||||
|
/// <param name="filterAlphaKey">Optional. The alpha key used to filter the results by the first character of their title, for the alpha picker.</param>
|
||||||
|
/// <param name="ignoreThePrefixForAlphaPicker">Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.</param>
|
||||||
/// <param name="sortBy">Optional. The name of the field by which to sort the results.</param>
|
/// <param name="sortBy">Optional. The name of the field by which to sort the results.</param>
|
||||||
/// <param name="sortOrder">Optional. The direction in which to sort the results.</param>
|
/// <param name="sortOrder">Optional. The direction in which to sort the results.</param>
|
||||||
/// <returns>The created <see cref="GetBooksLiteRequest"/>.</returns>
|
/// <returns>The created <see cref="GetBooksLiteRequest"/>.</returns>
|
||||||
@@ -33,6 +35,8 @@ public class GetBooksLiteRequestFixture
|
|||||||
int? currentPage = null,
|
int? currentPage = null,
|
||||||
int? perPage = null,
|
int? perPage = null,
|
||||||
string? searchTerm = null,
|
string? searchTerm = null,
|
||||||
|
string? filterAlphaKey = null,
|
||||||
|
bool ignoreThePrefixForAlphaPicker = false,
|
||||||
string? sortBy = null,
|
string? sortBy = null,
|
||||||
SortOrder? sortOrder = null)
|
SortOrder? sortOrder = null)
|
||||||
{
|
{
|
||||||
@@ -41,6 +45,8 @@ public class GetBooksLiteRequestFixture
|
|||||||
CurrentPage: currentPage ?? _faker.Random.Number(1, 100),
|
CurrentPage: currentPage ?? _faker.Random.Number(1, 100),
|
||||||
PerPage: perPage ?? _faker.Random.Number(1, 200),
|
PerPage: perPage ?? _faker.Random.Number(1, 200),
|
||||||
SearchTerm: searchTerm ?? _faker.Lorem.Word(),
|
SearchTerm: searchTerm ?? _faker.Lorem.Word(),
|
||||||
|
FilterAlphaKey: filterAlphaKey,
|
||||||
|
IgnoreThePrefixForAlphaPicker: ignoreThePrefixForAlphaPicker,
|
||||||
SortBy: sortBy ?? _faker.Lorem.Word(),
|
SortBy: sortBy ?? _faker.Lorem.Word(),
|
||||||
SortOrder: sortOrder ?? _faker.PickRandom<SortOrder>()
|
SortOrder: sortOrder ?? _faker.PickRandom<SortOrder>()
|
||||||
);
|
);
|
||||||
|
|||||||
+118
-1
@@ -82,6 +82,121 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
|||||||
Assert.Contains(paginatedBooks.Data, book => book.Title == "Book B");
|
Assert.Contains(paginatedBooks.Data, book => book.Title == "Book B");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetBooksLite_WhenCalledWithFilterAlphaKeyLetter_ShouldReturnOnlyBooksStartingWithThatLetter()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Guid userId = GetCurrentUserId();
|
||||||
|
Guid libraryId = Guid.NewGuid();
|
||||||
|
await SeedLibraryAsync(libraryId, userId);
|
||||||
|
await SeedBookAsync(libraryId, "Quiet Place");
|
||||||
|
await SeedBookAsync(libraryId, "The Quiet");
|
||||||
|
await SeedBookAsync(libraryId, "Racing");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=q");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
|
||||||
|
Assert.NotNull(paginatedBooks);
|
||||||
|
BookLiteResponse book = Assert.Single(paginatedBooks!.Data);
|
||||||
|
Assert.Equal("Quiet Place", book.Title);
|
||||||
|
Assert.Equal(1, paginatedBooks.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetBooksLite_WhenCalledWithFilterAlphaKeyLetterAndIgnoreThePrefix_ShouldIncludeThePrefixedTitles()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Guid userId = GetCurrentUserId();
|
||||||
|
Guid libraryId = Guid.NewGuid();
|
||||||
|
await SeedLibraryAsync(libraryId, userId);
|
||||||
|
await SeedBookAsync(libraryId, "Quiet Place");
|
||||||
|
await SeedBookAsync(libraryId, "The Quiet");
|
||||||
|
await SeedBookAsync(libraryId, "Racing");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=q&ignoreThePrefixForAlphaPicker=true");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
|
||||||
|
Assert.NotNull(paginatedBooks);
|
||||||
|
Assert.Equal(2, paginatedBooks!.Count);
|
||||||
|
Assert.Contains(paginatedBooks.Data, book => book.Title == "Quiet Place");
|
||||||
|
Assert.Contains(paginatedBooks.Data, book => book.Title == "The Quiet");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetBooksLite_WhenCalledWithFilterAlphaKeyNumber_ShouldReturnOnlyBooksStartingWithADigit()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Guid userId = GetCurrentUserId();
|
||||||
|
Guid libraryId = Guid.NewGuid();
|
||||||
|
await SeedLibraryAsync(libraryId, userId);
|
||||||
|
await SeedBookAsync(libraryId, "1984");
|
||||||
|
await SeedBookAsync(libraryId, "7 Habits of Highly Effective People");
|
||||||
|
await SeedBookAsync(libraryId, "Brave New World");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=%23");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
|
||||||
|
Assert.NotNull(paginatedBooks);
|
||||||
|
Assert.Equal(2, paginatedBooks!.Count);
|
||||||
|
Assert.Contains(paginatedBooks.Data, book => book.Title == "1984");
|
||||||
|
Assert.Contains(paginatedBooks.Data, book => book.Title == "7 Habits of Highly Effective People");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetBooksLite_WhenCalledWithFilterAlphaKeySymbol_ShouldReturnOnlyBooksStartingWithASymbol()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Guid userId = GetCurrentUserId();
|
||||||
|
Guid libraryId = Guid.NewGuid();
|
||||||
|
await SeedLibraryAsync(libraryId, userId);
|
||||||
|
await SeedBookAsync(libraryId, "!Important");
|
||||||
|
await SeedBookAsync(libraryId, "1984");
|
||||||
|
await SeedBookAsync(libraryId, "Alpha");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=%2A");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
|
||||||
|
Assert.NotNull(paginatedBooks);
|
||||||
|
BookLiteResponse book = Assert.Single(paginatedBooks!.Data);
|
||||||
|
Assert.Equal("!Important", book.Title);
|
||||||
|
Assert.Equal(1, paginatedBooks.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetBooksLite_WhenTitleIsEmptyAndFilterAlphaKeyIsProvided_ShouldUseOriginalTitle()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Guid userId = GetCurrentUserId();
|
||||||
|
Guid libraryId = Guid.NewGuid();
|
||||||
|
await SeedLibraryAsync(libraryId, userId);
|
||||||
|
await SeedBookAsync(libraryId, "", "Rendezvous");
|
||||||
|
await SeedBookAsync(libraryId, "Racing");
|
||||||
|
await SeedBookAsync(libraryId, "Quiet Place");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=r");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
|
||||||
|
Assert.NotNull(paginatedBooks);
|
||||||
|
Assert.Equal(2, paginatedBooks!.Count);
|
||||||
|
Assert.Contains(paginatedBooks.Data, book => book.Title == ""); // the empty title book matches the filter through its original title
|
||||||
|
Assert.Contains(paginatedBooks.Data, book => book.Title == "Racing");
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task GetBooksLite_WhenCalledWithSearchTerm_ShouldReturnOnlyMatchingBooks()
|
public async Task GetBooksLite_WhenCalledWithSearchTerm_ShouldReturnOnlyMatchingBooks()
|
||||||
{
|
{
|
||||||
@@ -204,8 +319,9 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||||
/// <param name="title">The title of the book.</param>
|
/// <param name="title">The title of the book.</param>
|
||||||
|
/// <param name="originalTitle">Optional. The original title of the book.</param>
|
||||||
/// <returns>A task representing the asynchronous operation.</returns>
|
/// <returns>A task representing the asynchronous operation.</returns>
|
||||||
private async Task SeedBookAsync(Guid libraryId, string title)
|
private async Task SeedBookAsync(Guid libraryId, string title, string? originalTitle = null)
|
||||||
{
|
{
|
||||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||||
@@ -215,6 +331,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
|||||||
LibraryId = libraryId,
|
LibraryId = libraryId,
|
||||||
Path = $"/books/{Guid.NewGuid()}.epub",
|
Path = $"/books/{Guid.NewGuid()}.epub",
|
||||||
Title = title,
|
Title = title,
|
||||||
|
OriginalTitle = originalTitle,
|
||||||
CreatedBy = Guid.NewGuid(),
|
CreatedBy = Guid.NewGuid(),
|
||||||
CreatedOnUtc = DateTime.UtcNow,
|
CreatedOnUtc = DateTime.UtcNow,
|
||||||
UpdatedBy = null
|
UpdatedBy = null
|
||||||
|
|||||||
+42
@@ -46,4 +46,46 @@ public class GetBooksLiteQueryValidatorTests
|
|||||||
// Assert
|
// Assert
|
||||||
result.ShouldNotHaveAnyValidationErrors();
|
result.ShouldNotHaveAnyValidationErrors();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WhenFilterAlphaKeyIsNotASingleLetterOrSpecialKey_ShouldHaveValidationError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
||||||
|
query = query with { Filter = query.Filter with { FilterAlphaKey = "AB" } };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
List<Error> result = _validator.TestValidate(query);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldHaveValidationError(Errors.Library.InvalidFilterAlphaKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WhenFilterAlphaKeyIsASingleLetter_ShouldNotHaveValidationError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
||||||
|
query = query with { Filter = query.Filter with { FilterAlphaKey = "Q" } };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
List<Error> result = _validator.TestValidate(query);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldNotHaveAnyValidationErrors();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WhenFilterAlphaKeyIsNumberOrSymbol_ShouldNotHaveValidationError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
||||||
|
query = query with { Filter = query.Filter with { FilterAlphaKey = "#" } };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
List<Error> result = _validator.TestValidate(query);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldNotHaveAnyValidationErrors();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user