Refactors the update book slice across the stack

This commit is contained in:
BinaryAlley committed 2026-09-12 12:13:18 -07:00
1 parent 9a71a6d32b
commit 001146eefc
27 files changed
+4065 -632

No files matched your search

@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
@@ -14,7 +14,8 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <summary>
/// Command for updating an existing book.
/// </summary>
/// <param name="Id">The Id of the book to update.</param>
/// <param name="LibraryId">The unique identifier of the media library this book belongs to, taken from the route.</param>
/// <param name="BookId">The unique identifier of the book to update, taken from the route.</param>
/// <param name="Metadata">Written content metadata of the book.</param>
/// <param name="Format">The format of the book (e.g., Hardcover, Paperback), if applicable.</param>
/// <param name="Edition">The edition of the book, if applicable.</param>
@@ -34,7 +35,8 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <param name="Ratings">The list of ratings for this book.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record UpdateBookCommand(
Guid Id,
string? LibraryId,
string? BookId,
WrittenContentMetadataDto? Metadata,
BookFormat? Format,
string? Edition,
@@ -50,6 +52,6 @@ public record UpdateBookCommand(
string? BarnesAndNobleId,
string? AppleBooksId,
List<IsbnDto>? ISBNs,
List<MediaContributorDto>? Contributors,
List<MediaContributorReferenceDto>? Contributors,
List<BookRatingDto>? Ratings
) : ICommand;
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
@@ -8,12 +8,9 @@ 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 Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -70,74 +67,44 @@ public class UpdateBookCommandHandler : ICommandHandler<UpdateBookCommand, Resul
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(command.LibraryId!);
Guid bookId = Guid.Parse(command.BookId!);
// Get the existing book with all its related data.
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, 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 edited 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 update 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(existingBook.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// Convert the book to a domain object and apply the edited metadata to it.
Result<Book> getDomainBookResult = existingBook.ToDomainEntity();
if (getDomainBookResult.IsFailure)
return getDomainBookResult.Errors;
Book book = getDomainBookResult.Value;
// Media contributors are referenced by Id and are never created implicitly by editing a book, so each one must already exist.
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
Result<Success> applyMetadataResult = book.ApplyMetadata(command.ToBookMetadataDto());
if (applyMetadataResult.IsFailure)
return applyMetadataResult.Errors;
// Link the media contributors typed by the user to the book, finding or creating a single contributor per person.
List<BookContributorEntity> linkedContributors = [];
// A person can be credited under several roles in the same book; each distinct display name must resolve to the same media
// contributor row, otherwise the duplicate inserts would violate the unique display name constraint when the changes are saved.
Dictionary<string, MediaContributorEntity> contributorsByDisplayName = [];
foreach (MediaContributorDto contributor in command.Contributors!)
{
if (contributor.Name?.DisplayName is null)
continue;
if (!contributorsByDisplayName.TryGetValue(contributor.Name.DisplayName, out MediaContributorEntity? contributorEntity))
{
Result<MediaContributorEntity> findOrCreateResult = await _unitOfWork.MediaContributorRepository.FindOrCreateByDisplayNameAsync(contributor.Name.DisplayName, contributor.Name.LegalName, cancellationToken).ConfigureAwait(false);
if (findOrCreateResult.IsFailure)
return findOrCreateResult.Errors;
contributorEntity = findOrCreateResult.Value;
contributorsByDisplayName.Add(contributor.Name.DisplayName, contributorEntity);
}
string roleName = contributor.Role?.Name ?? "Contributor";
MediaContributorRoleCategory roleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other;
linkedContributors.Add(new BookContributorEntity
{
Id = Guid.NewGuid(),
BookId = existingBook.Id,
MediaContributorId = contributorEntity.Id,
RoleName = roleName,
RoleCategory = roleCategory,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = userId,
UpdatedBy = null
});
}
book.UpdateContributors([.. linkedContributors.Select(linkedContributor => MediaContributorId.Create(linkedContributor.MediaContributorId))]);
// Convert the command to a domain aggregate to enforce invariants, preserving the identity and creation metadata of the stored book.
Result<Book> updateBookResult = command.ToDomainEntity(existingBook);
if (updateBookResult.IsFailure)
return updateBookResult.Errors;
// Map the updated domain book onto a fresh repository entity, ready for the repository to replace the stored data.
BookEntity updatedBook = book.ToRepositoryEntity();
updatedBook.BookContributors = linkedContributors;
updatedBook.UpdatedOnUtc = DateTime.UtcNow;
updatedBook.UpdatedBy = userId;
BookEntity updatedBook = updateBookResult.Value.ToRepositoryEntity();
// The identity, enrichment and artwork columns are never overwritten by an edit, so they are copied onto the fresh entity that
// backs the response; without this, the response would report the fresh entity defaults (Pending metadata status, no cover path).
updatedBook.CreatedOnUtc = existingBook.CreatedOnUtc;
// The enrichment and artwork columns are never overwritten by an edit, so they are copied onto the fresh entity that the repository
// replaces the stored data with; without this, the stored artwork would be cleared.
updatedBook.MetadataStatus = existingBook.MetadataStatus;
updatedBook.LastMetadataUpdateUtc = existingBook.LastMetadataUpdateUtc;
updatedBook.MetadataProvider = existingBook.MetadataProvider;
@@ -147,8 +114,40 @@ public class UpdateBookCommandHandler : ICommandHandler<UpdateBookCommand, Resul
if (updateResult.IsFailure)
return updateResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return updatedBook.ToResponse() with { Contributors = command.Contributors };
// Returns the book as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the persistence medium applied on save.
Result<BookEntity?> getPersistedBookResult = await _unitOfWork.BookRepository.GetByIdAsync(existingBook.Id, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPersistedBookResult.IsFailure)
return getPersistedBookResult.Errors;
if (getPersistedBookResult.Value is null)
return DomainErrors.WrittenContent.BookNotFound;
return getPersistedBookResult.Value.ToResponse();
}
/// <summary>
/// Gets the media contributors referenced by <paramref name="command"/>, requiring each referenced Id to already exist.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the existing media contributors, or an error when at least one referenced contributor does not exist.
/// </returns>
private async Task<Result<IReadOnlyList<MediaContributorEntity>>> GetExistingContributorsAsync(UpdateBookCommand command, CancellationToken cancellationToken)
{
List<Guid> contributorIds = [.. command.Contributors!.Select(contributor => contributor.ContributorId).Distinct()];
if (contributorIds.Count == 0)
return Result.From<IReadOnlyList<MediaContributorEntity>>([]);
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await _unitOfWork.MediaContributorRepository
.GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
if (getContributorsResult.Value.Count != contributorIds.Count)
return DomainErrors.MediaContributor.MediaContributorNotFound;
return Result.From(getContributorsResult.Value);
}
}
@@ -18,18 +18,34 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
/// </summary>
public UpdateBookCommandValidator()
{
RuleFor(command => command.Id)
// Validates the identifier of the media library the book belongs to, taken from the route.
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(command => command.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// Validates the identifier of the book to update, taken from the route.
RuleFor(command => command.BookId)
.NotEmpty()
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
RuleFor(command => command.BookId)
.Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty)
.When(command => command.BookId is not null && command.BookId.Length > 0)
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
// Validates the metadata of the book: title, lengths, release information, languages, genres and tags.
RuleFor(command => command.Metadata)
.NotNull()
.WithError(Errors.Metadata.MetadataCannotBeNull)
.ChildRules(metadata =>
{
metadata.RuleFor(m => m!.Title)
.NotNull()
.NotEmpty()
.WithError(Errors.Metadata.TitleCannotBeEmpty)
.MaximumLength(255)
@@ -125,7 +141,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
metadata.RuleFor(m => m!.Language!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.MaximumLength(2)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.Language is not null);
@@ -144,7 +160,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.MaximumLength(2)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
@@ -171,6 +187,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
.WithError(Errors.WrittenContent.PageCountMustBeGreaterThanZero);
});
// Validates the physical characteristics of the book: format, edition and volume number.
RuleFor(command => command.Format)
.IsInEnum()
.When(command => command.Format is not null)
@@ -186,6 +203,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
.When(command => command.VolumeNumber.HasValue)
.WithError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero);
// Validates the series the book is part of, when the request carries one.
RuleFor(command => command.Series)
.ChildRules(series =>
series.RuleFor(s => s!.Title)
@@ -195,6 +213,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
.WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong))
.When(command => command.Series is not null);
// Validates the external identifiers of the book.
RuleFor(command => command.ASIN)
.Length(10)
.When(command => command.ASIN is not null)
@@ -246,6 +265,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
.When(command => command.AppleBooksId is not null)
.WithError(Errors.WrittenContent.InvalidAppleBooksIdFormat);
// Validates the ISBN list of the book.
RuleFor(command => command.ISBNs)
.NotNull()
.WithError(Errors.WrittenContent.IsbnListCannotBeNull);
@@ -272,48 +292,26 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
.WithError(Errors.WrittenContent.UnknownIsbnFormat);
});
// Validates the media contributors that contributed to the book.
RuleFor(command => command.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
.WithError(Errors.WrittenContent.ContributorsListCannotBeNull);
RuleForEach(command => command.Contributors)
.ChildRules(contributor =>
{
contributor.RuleFor(c => c.Name)
.NotNull()
.WithError(Errors.MediaContributor.ContributorNameCannotBeEmpty)
.ChildRules(name =>
{
name.RuleFor(n => n!.DisplayName)
.NotNull()
.WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty)
.NotEmpty()
.WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty)
.MaximumLength(100)
.WithError(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong);
name.RuleFor(n => n!.LegalName)
.MaximumLength(100)
.When(n => n!.LegalName is not null)
.WithError(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong);
});
contributor.RuleFor(c => c.ContributorId)
.NotEmpty()
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty)
.Must(contributorId => contributorId != Guid.Empty)
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
contributor.RuleFor(c => c.Role)
.NotNull()
.WithError(Errors.MediaContributor.ContributorRoleCannotBeNull)
.ChildRules(role =>
{
role.RuleFor(r => r!.Name)
.NotEmpty()
.WithError(Errors.MediaContributor.RoleNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong);
role.RuleFor(r => r!.Category)
.NotEmpty()
.WithError(Errors.MediaContributor.RoleCategoryCannotBeEmpty);
});
.IsInEnum()
.WithError(Errors.MediaContributor.UnknownMediaContributorRole);
});
// Validates the ratings of the book.
RuleFor(command => command.Ratings)
.NotNull()
.WithError(Errors.Metadata.RatingsListCannotBeNull);