Refactors the get book slice

This commit is contained in:
BinaryAlley committed 2026-09-13 06:58:32 -07:00
1 parent 1d35cd01db
commit 8aaf9fe64e
17 files changed
+395 -347

No files matched your search

@@ -1,25 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using System;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Extension methods for converting <see cref="GetBookRequest"/>.
/// </summary>
public static class GetBookRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetBookQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetBookQuery ToQuery(this GetBookRequest request)
{
return new GetBookQuery(
Guid.TryParse(request.Id, out Guid bookId) ? bookId : Guid.Empty
);
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
@@ -8,7 +7,9 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <summary>
/// Query for getting a book by its Id.
/// </summary>
/// <param name="Id">The Id of the book to get.</param>
/// <param name="LibraryId">The unique identifier of the media library the book belongs to, taken from the route.</param>
/// <param name="BookId">The unique identifier of the book to get, taken from the route.</param>
public record GetBookQuery(
Guid Id
string? LibraryId,
string? BookId
) : IQuery;
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
@@ -8,12 +7,10 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -67,56 +64,29 @@ public class GetBookQueryHandler : IQueryHandler<GetBookQuery, Result<BookRespon
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the route identifiers are non-empty Guids before this point.
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
// Get the book with the specified id from the repository.
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false);
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getBookResult.IsFailure)
return getBookResult.Errors;
if (getBookResult.Value is null)
return DomainErrors.WrittenContent.BookNotFound;
BookEntity existingBook = getBookResult.Value;
// Resource scoping: the book must belong to the library named by the route, so that a book can never be read through another
// library's route; the mismatch is reported as not found, without disclosing that the book exists in another library.
if (existingBook.LibraryId != libraryId)
return DomainErrors.WrittenContent.BookNotFound;
// Admins can see the books of all libraries; for everyone else, only the books of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(getBookResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
BookResponse response = getBookResult.Value.ToResponse();
// The response carries the resolved contributor names, so that the clients can display them without querying the contributors themselves.
List<MediaContributorEntity> contributors = await GetContributorsAsync(getBookResult.Value, cancellationToken).ConfigureAwait(false);
if (contributors.Count == 0)
return response;
Dictionary<Guid, MediaContributorEntity> contributorsById = contributors.ToDictionary(contributor => contributor.Id);
List<MediaContributorDto> contributorResponses = [];
foreach (BookContributorEntity participation in getBookResult.Value.BookContributors)
{
if (!contributorsById.TryGetValue(participation.MediaContributorId, out MediaContributorEntity? contributor))
continue;
contributorResponses.Add(new MediaContributorDto(
new MediaContributorNameDto(contributor.DisplayName, contributor.LegalName),
new MediaContributorRoleDto(participation.RoleName, participation.RoleCategory)
));
}
return response with { Contributors = contributorResponses };
}
/// <summary>
/// Gets the media contributors linked to the book of <paramref name="book"/>, by their unique identifiers.
/// </summary>
/// <param name="book">The book whose media contributors are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the media contributors of the book, or an error.</returns>
private async Task<List<MediaContributorEntity>> GetContributorsAsync(BookEntity book, CancellationToken cancellationToken)
{
IReadOnlyCollection<Guid> contributorIds = [.. book.BookContributors.Select(participation => participation.MediaContributorId).Distinct()];
if (contributorIds.Count == 0)
return [];
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await _unitOfWork.MediaContributorRepository.GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return [];
return [.. getContributorsResult.Value];
return existingBook.ToResponse();
}
}
@@ -17,10 +17,24 @@ public class GetBookQueryValidator : AbstractValidator<GetBookQuery>
/// </summary>
public GetBookQueryValidator()
{
RuleFor(query => query.Id)
// Validates the identifier of the media library the book belongs to, taken from the route.
RuleFor(query => query.LibraryId)
.NotEmpty()
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(query => query.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(query => query.LibraryId is not null && query.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// Validates the identifier of the book to get, taken from the route.
RuleFor(query => query.BookId)
.NotEmpty()
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
RuleFor(query => query.BookId)
.Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty)
.When(query => query.BookId is not null && query.BookId.Length > 0)
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
}
@@ -1,15 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Represents a request to get a book by the specified Id.
/// </summary>
/// <param name="Id">The unique identifier of the book to retrieve.</param>
[DebuggerDisplay("Id: {Id}")]
public record GetBookRequest(
string? Id
);
@@ -1,8 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary;
@@ -15,9 +14,9 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook;
/// <summary>
/// API endpoint for the <c>/books/{id}</c> route.
/// API endpoint for the <c>/{libraryId}/books/{bookId}</c> route.
/// </summary>
public class GetBookEndpoint : BaseEndpoint<GetBookRequest, IResult>
public class GetBookEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IQueryHandler<GetBookQuery, Result<BookResponse>> _getBookQueryHandler;
@@ -35,20 +34,23 @@ public class GetBookEndpoint : BaseEndpoint<GetBookRequest, IResult>
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.GET);
Verbs(Http.GET);
Routes(ApiRoutes.Books.GET_BOOK_BY_ID);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the book identified by <paramref name="request"/>.
/// Gets the book identified by the route.
/// </summary>
/// <param name="request">The request containing the Id of the book to get.</param>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetBookRequest request, CancellationToken cancellationToken)
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
Result<BookResponse> result = await _getBookQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
// Take unique identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
string? bookId = HttpContext.Request.RouteValues["bookId"]?.ToString();
Result<BookResponse> result = await _getBookQueryHandler.HandleAsync(new GetBookQuery(libraryId, bookId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -4,7 +4,6 @@ using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
@@ -20,7 +19,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B
/// Class used for providing a textual description for the <see cref="GetBookEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBookEndpointSummary : Summary<GetBookEndpoint, GetBookRequest>
public class GetBookEndpointSummary : Summary<GetBookEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetBookEndpointSummary"/> class.
@@ -28,13 +27,7 @@ public class GetBookEndpointSummary : Summary<GetBookEndpoint, GetBookRequest>
public GetBookEndpointSummary()
{
Summary = "Gets a book by its Id.";
Description = "Gets the full details of the book identified by the request, including the resolved names of its media contributors.";
ExampleRequest = new GetBookRequest(
Id: Guid.NewGuid().ToString()
);
RequestParam(r => r.Id, "The Id of the book to get. Required.");
Description = "Gets the full details of the book identified by the route, including the references to its media contributors.";
ResponseParam<BookResponse>(r => r.Id, "The Id of the book.");
ResponseParam<BookResponse>(r => r.LibraryId, "The Id of the media library the book belongs to.");
@@ -65,8 +58,8 @@ public class GetBookEndpointSummary : Summary<GetBookEndpoint, GetBookRequest>
ResponseParam<BookResponse>(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable.");
ResponseParam<BookResponse>(r => r.Edition, "The edition of the book, if applicable.");
ResponseParam<BookResponse>(r => r.VolumeNumber, "The volume or book number in the series, if applicable.");
ResponseParam<BookResponse>(r => r.Series, "The series the book is part of, if applicable.");
ResponseParam<BookResponse>(r => r.Series!.Title, "The title of the series the book is part of.");
ResponseParam<BookResponse>(r => r.Series, "The series the book is part of. Book series are not yet supported and this is always null.");
ResponseParam<BookResponse>(r => r.Series!.Title, "The title of the series the book is part of. Book series are not yet supported and this is always null.");
ResponseParam<BookResponse>(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable.");
ResponseParam<BookResponse>(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable.");
ResponseParam<BookResponse>(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable.");
@@ -77,7 +70,7 @@ public class GetBookEndpointSummary : Summary<GetBookEndpoint, GetBookRequest>
ResponseParam<BookResponse>(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable.");
ResponseParam<BookResponse>(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable.");
ResponseParam<BookResponse>(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book.");
ResponseParam<BookResponse>(r => r.Contributors, "The list of media contributors starring in this book.");
ResponseParam<BookResponse>(r => r.Contributors, "The list of references to the media contributors that contributed to this book, each with the role they played.");
ResponseParam<BookResponse>(r => r.Ratings, "The list of ratings for the book.");
ResponseParam<BookResponse>(r => r.MetadataStatus, "The status of the metadata enrichment of the book.");
ResponseParam<BookResponse>(r => r.LastMetadataUpdateUtc, "The date and time when the metadata of the book was last enriched, if applicable.");
@@ -131,9 +124,7 @@ public class GetBookEndpointSummary : Summary<GetBookEndpoint, GetBookRequest>
Format: BookFormat.Paperback,
Edition: "50th Anniversary Edition",
VolumeNumber: 1,
Series: new BookSeriesDto(
Title: "The Lord of the Rings"
),
Series: null,
ASIN: "B007978NPG",
GoodreadsId: "3",
LCCN: "54009621",
@@ -156,25 +147,13 @@ public class GetBookEndpointSummary : Summary<GetBookEndpoint, GetBookRequest>
],
Contributors:
[
new MediaContributorDto(
Name: new MediaContributorNameDto(
DisplayName: "J.R.R. Tolkien",
LegalName: "John Ronald Reuel Tolkien"
),
Role: new MediaContributorRoleDto(
Name: "author",
Category: MediaContributorRoleCategory.Author
)
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Author
),
new MediaContributorDto(
Name: new MediaContributorNameDto(
DisplayName: "Alan Lee",
LegalName: "Alan Lee"
),
Role: new MediaContributorRoleDto(
Name: "illustrator",
Category: MediaContributorRoleCategory.Illustrator
)
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Illustrator
)
],
Ratings:
@@ -202,13 +181,32 @@ public class GetBookEndpointSummary : Summary<GetBookEndpoint, GetBookRequest>
);
Response(401, "Authentication required.", "application/problem+json",
example: new
example: new[]
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/books/{id}"
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Authentication failed",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token has expired",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}"
}
}
);
@@ -219,7 +217,7 @@ public class GetBookEndpointSummary : Summary<GetBookEndpoint, GetBookRequest>
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/books/{id}",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
@@ -231,7 +229,7 @@ public class GetBookEndpointSummary : Summary<GetBookEndpoint, GetBookRequest>
title = "General.NotFound",
status = 404,
detail = "BookNotFound",
instance = "/api/v1/books/{id}",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
@@ -243,12 +241,13 @@ public class GetBookEndpointSummary : Summary<GetBookEndpoint, GetBookRequest>
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/books/{id}",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty",
"BookIdCannotBeEmpty"
}
}