mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 13:11:10 +00:00
Refactors the add book slice and shared media contributor model across the stack
This commit is contained in:
1 parent
3a2c80b615
commit
9a71a6d32b
61 files changed
+5223
-1384
No files matched your search
+10
-16
@@ -5,12 +5,11 @@ using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for the participation of a media contributor in a book, carrying the role the contributor
|
||||
/// played in that book. The role is tracked per participation, so that a single contributor can play multiple
|
||||
/// roles in the same book, or different roles in different books.
|
||||
/// Repository entity for the participation of a media contributor in a book, carrying the role the contributor played in that book.
|
||||
/// The role is tracked per participation, so that a single contributor can play multiple roles in the same book, or different roles in different books.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("BookId: {BookId} MediaContributorId: {MediaContributorId}")]
|
||||
public class BookContributorEntity : IStorageEntity, IAuditableEntity
|
||||
@@ -21,24 +20,19 @@ public class BookContributorEntity : IStorageEntity, IAuditableEntity
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the book the contributor participated in.
|
||||
/// Gets the Id of the book the contributor participated in.
|
||||
/// </summary>
|
||||
public required Guid BookId { get; set; }
|
||||
public required Guid BookId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the media contributor.
|
||||
/// Gets the Id of the media contributor.
|
||||
/// </summary>
|
||||
public required Guid MediaContributorId { get; set; }
|
||||
public required Guid MediaContributorId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the display name of the role the contributor played in the book.
|
||||
/// Gets the role the contributor played in the book.
|
||||
/// </summary>
|
||||
public required string RoleName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the canonical category of the role the contributor played in the book.
|
||||
/// </summary>
|
||||
public required MediaContributorRoleCategory RoleCategory { get; set; }
|
||||
public required MediaContributorRole Role { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
@@ -58,5 +52,5 @@ public class BookContributorEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+1
-2
@@ -1,6 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using System;
|
||||
@@ -185,7 +184,7 @@ public class BookEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the Barnes & Noble ID of the book.
|
||||
/// </summary>
|
||||
public string? BarnesAndNobleId { get; set; } = null!;
|
||||
public string? BarnesAndNobleId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Apple Books ID of the book.
|
||||
|
||||
@@ -3,6 +3,7 @@ using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
@@ -19,7 +20,7 @@ public interface IBookRepository : IRepository<BookEntity>,
|
||||
IUpdateRepositoryAction<BookEntity>,
|
||||
IGetByIdRepositoryAction<BookEntity, Guid>,
|
||||
IGetAllRepositoryAction<BookEntity>,
|
||||
IGetPaginatedRepositoryAction<BookEntity>
|
||||
IGetAllLiteRepositoryAction<BookEntity, BookLiteRow>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets all the books of the media library identified by <paramref name="libraryId"/>.
|
||||
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using AudioMediaContributorId = Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate.MediaContributorId;
|
||||
using BookMediaContributorId = Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate.MediaContributorId;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaContributors;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="MediaContributorReferenceDto"/>.
|
||||
/// </summary>
|
||||
public static class MediaContributorReferenceDtoMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="dto"/> to a domain <see cref="BookMediaContributor"/>.
|
||||
/// </summary>
|
||||
/// <param name="dto">The data transfer object to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="BookMediaContributor"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<BookMediaContributor> ToBookDomainEntity(this MediaContributorReferenceDto dto)
|
||||
{
|
||||
return BookMediaContributor.Create(BookMediaContributorId.Create(dto.ContributorId), dto.Role);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="dtos"/> to a collection of <see cref="BookMediaContributor"/>.
|
||||
/// </summary>
|
||||
/// <param name="dtos">The DTOs to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a collection of converted <see cref="BookMediaContributor"/>, or an error message.
|
||||
/// </returns>
|
||||
public static IEnumerable<Result<BookMediaContributor>> ToBookDomainEntities(this IEnumerable<MediaContributorReferenceDto> dtos)
|
||||
{
|
||||
return dtos.Select(domainEntity => domainEntity.ToBookDomainEntity());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="dto"/> to a domain <see cref="MusicMediaContributor"/>.
|
||||
/// </summary>
|
||||
/// <param name="dto">The data transfer object to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="MusicMediaContributor"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<MusicMediaContributor> ToMusicDomainEntity(this MediaContributorReferenceDto dto)
|
||||
{
|
||||
return MusicMediaContributor.Create(AudioMediaContributorId.Create(dto.ContributorId), dto.Role);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="dtos"/> to a collection of <see cref="MusicMediaContributor"/>.
|
||||
/// </summary>
|
||||
/// <param name="dtos">The DTOs to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a collection of converted <see cref="MusicMediaContributor"/>, or an error message.
|
||||
/// </returns>
|
||||
public static IEnumerable<Result<MusicMediaContributor>> ToMusicDomainEntities(this IEnumerable<MediaContributorReferenceDto> dtos)
|
||||
{
|
||||
return dtos.Select(domainEntity => domainEntity.ToMusicDomainEntity());
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaContributors;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.Common;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
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;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="AddBookCommand"/>.
|
||||
/// </summary>
|
||||
public static class AddBookCommandMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="command"/> to <see cref="Book"/>.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="Book"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<Book> ToDomainEntity(this AddBookCommand command, Guid libraryId)
|
||||
{
|
||||
IEnumerable<Result<BookRating>> domainRatingsResult = command.Ratings!.ToDomainEntities();
|
||||
List<Error> errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors) ?? []];
|
||||
if (errors.Count > 0)
|
||||
return errors;
|
||||
|
||||
IEnumerable<Result<Isbn>> domainIsbnsResult = command.ISBNs!.ToDomainEntities();
|
||||
errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors) ?? []];
|
||||
if (errors.Count > 0)
|
||||
return errors;
|
||||
|
||||
Result<WrittenContentMetadata> metadataResult = command.Metadata!.ToDomainEntity();
|
||||
if (metadataResult.IsFailure)
|
||||
return metadataResult.Errors;
|
||||
|
||||
// TODO: update Api.Book.md documentation when the functionality is fully implemented.
|
||||
BookSeries? bookSeries = null;
|
||||
if (command.Series != null)
|
||||
{
|
||||
// TODO: add logic to search the book series repository for existing book series, based on the provided title.
|
||||
// TODO: uncomment integration and unit tests about series.
|
||||
}
|
||||
|
||||
// Map the media contributors referenced by the user to their domain counterparts; a contributor is identified by its id and carries the role it played.
|
||||
IEnumerable<Result<BookMediaContributor>> domainContributorsResult = command.Contributors!.ToBookDomainEntities();
|
||||
errors = [.. domainContributorsResult.Where(domainContributor => domainContributor.IsFailure).SelectMany(domainContributor => domainContributor.Errors) ?? []];
|
||||
if (errors.Count > 0)
|
||||
return errors;
|
||||
|
||||
return Book.Create(
|
||||
LibraryId.Create(libraryId),
|
||||
command.Path,
|
||||
metadataResult.Value,
|
||||
Optional<BookFormat>.FromNullable(command.Format),
|
||||
Optional<string>.FromNullable(command.Edition),
|
||||
Optional<float>.FromNullable(command.VolumeNumber),
|
||||
Optional<BookSeries>.FromNullable(bookSeries),
|
||||
Optional<string>.FromNullable(command.ASIN),
|
||||
Optional<string>.FromNullable(command.GoodreadsId),
|
||||
Optional<string>.FromNullable(command.LCCN),
|
||||
Optional<string>.FromNullable(command.OCLCNumber),
|
||||
Optional<string>.FromNullable(command.OpenLibraryId),
|
||||
Optional<string>.FromNullable(command.LibraryThingId),
|
||||
Optional<string>.FromNullable(command.GoogleBooksId),
|
||||
Optional<string>.FromNullable(command.BarnesAndNobleId),
|
||||
Optional<string>.FromNullable(command.AppleBooksId),
|
||||
[.. domainIsbnsResult.Select(isbn => isbn.Value)],
|
||||
[.. domainContributorsResult.Select(domainContributor => domainContributor.Value)],
|
||||
[.. domainRatingsResult.Select(domainRating => domainRating.Value)]
|
||||
);
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -15,11 +15,12 @@ public static class AddBookRequestMapping
|
||||
/// Converts <paramref name="request"/> to <see cref="AddBookCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="libraryId">The Id of the library the book is added to, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static AddBookCommand ToCommand(this AddBookRequest request)
|
||||
public static AddBookCommand ToCommand(this AddBookRequest request, string? libraryId)
|
||||
{
|
||||
return new AddBookCommand(
|
||||
request.LibraryId,
|
||||
libraryId,
|
||||
request.Path,
|
||||
request.Metadata,
|
||||
request.Format,
|
||||
|
||||
+20
-19
@@ -1,20 +1,21 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
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.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
@@ -59,6 +60,16 @@ public static class BookEntityMapping
|
||||
if (bookRatingResult.IsFailure)
|
||||
return bookRatingResult.Errors;
|
||||
|
||||
List<BookMediaContributor> domainContributors = [];
|
||||
foreach (BookContributorEntity bookContributor in repositoryEntity.BookContributors)
|
||||
{
|
||||
Result<BookMediaContributor> contributorResult = BookMediaContributor.Create(
|
||||
MediaContributorId.Create(bookContributor.MediaContributorId), bookContributor.Role);
|
||||
if (contributorResult.IsFailure)
|
||||
return contributorResult.Errors;
|
||||
domainContributors.Add(contributorResult.Value);
|
||||
}
|
||||
|
||||
Result<ReleaseInfo> releaseInfoResult = ReleaseInfo.Create(
|
||||
Optional<DateOnly>.FromNullable(repositoryEntity.OriginalReleaseDate),
|
||||
Optional<int>.FromNullable(repositoryEntity.OriginalReleaseYear),
|
||||
@@ -71,30 +82,20 @@ public static class BookEntityMapping
|
||||
return releaseInfoResult.Errors;
|
||||
|
||||
Optional<LanguageInfo> languageInfo = Optional<LanguageInfo>.None();
|
||||
if (repositoryEntity.LanguageCode is not null)
|
||||
{
|
||||
Result<LanguageInfo> languageInfoResult = LanguageInfo.Create(
|
||||
if (repositoryEntity.LanguageCode is not null && repositoryEntity.LanguageName is not null)
|
||||
languageInfo = LanguageInfo.Create(
|
||||
repositoryEntity.LanguageCode,
|
||||
repositoryEntity.LanguageName,
|
||||
Optional<string>.FromNullable(repositoryEntity.LanguageNativeName)
|
||||
);
|
||||
if (languageInfoResult.IsFailure)
|
||||
return languageInfoResult.Errors;
|
||||
languageInfo = languageInfoResult.Value;
|
||||
}
|
||||
|
||||
Optional<LanguageInfo> originalLanguageCode = Optional<LanguageInfo>.None();
|
||||
if (repositoryEntity.OriginalLanguageCode is not null)
|
||||
{
|
||||
Result<LanguageInfo> originalLanguageInfoResult = LanguageInfo.Create(
|
||||
if (repositoryEntity.OriginalLanguageCode is not null && repositoryEntity.OriginalLanguageName is not null)
|
||||
originalLanguageCode = LanguageInfo.Create(
|
||||
repositoryEntity.OriginalLanguageCode,
|
||||
repositoryEntity.OriginalLanguageName!,
|
||||
repositoryEntity.OriginalLanguageName,
|
||||
Optional<string>.FromNullable(repositoryEntity.OriginalLanguageNativeName)
|
||||
);
|
||||
if (originalLanguageInfoResult.IsFailure)
|
||||
return originalLanguageInfoResult.Errors;
|
||||
originalLanguageCode = originalLanguageInfoResult.Value;
|
||||
}
|
||||
|
||||
Result<WrittenContentMetadata> writtenContentMetadataResult = WrittenContentMetadata.Create(
|
||||
repositoryEntity.Title,
|
||||
@@ -134,7 +135,7 @@ public static class BookEntityMapping
|
||||
repositoryEntity.CreatedOnUtc,
|
||||
Optional<DateTime>.FromNullable(repositoryEntity.UpdatedOnUtc),
|
||||
[.. isbnsResult.Select(isbn => isbn.Value)],
|
||||
[.. repositoryEntity.BookContributors.Select(bookContributor => MediaContributorId.Create(bookContributor.MediaContributorId))],
|
||||
domainContributors,
|
||||
[.. bookRatingsResult.Select(bookRating => bookRating.Value)]);
|
||||
if (bookResult.IsFailure)
|
||||
return bookResult.Errors;
|
||||
@@ -218,7 +219,7 @@ public static class BookEntityMapping
|
||||
repositoryEntity.BarnesAndNobleId,
|
||||
repositoryEntity.AppleBooksId,
|
||||
[.. repositoryEntity.ISBNs.ToResponses()],
|
||||
null,
|
||||
[.. repositoryEntity.BookContributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))],
|
||||
[.. repositoryEntity.Ratings.ToResponses()],
|
||||
repositoryEntity.MetadataStatus,
|
||||
repositoryEntity.LastMetadataUpdateUtc,
|
||||
|
||||
+12
-1
@@ -4,6 +4,7 @@ using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
using System;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
@@ -57,9 +58,19 @@ public static class BookMapping
|
||||
BarnesAndNobleId = domainEntity.BarnesAndNobleId.HasValue ? domainEntity.BarnesAndNobleId.Value : null,
|
||||
AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null,
|
||||
ISBNs = [.. domainEntity.ISBNs.ToRepositoryEntities()],
|
||||
BookContributors = [.. domainEntity.Contributors.Select(contributor => new BookContributorEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
BookId = domainEntity.Id.Value,
|
||||
MediaContributorId = contributor.ContributorId.Value,
|
||||
Role = contributor.Role,
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
})],
|
||||
Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()],
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null,
|
||||
UpdatedBy = domainEntity.UpdatedOnUtc.HasValue ? Guid.NewGuid() : null,
|
||||
};
|
||||
|
||||
+10
-14
@@ -58,22 +58,18 @@ public static class BookMetadataDtoMapping
|
||||
return tagsErrors;
|
||||
|
||||
Optional<LanguageInfo> languageInfo = Optional<LanguageInfo>.None();
|
||||
if (metadata.Language is not null)
|
||||
{
|
||||
Result<LanguageInfo> languageInfoResult = LanguageInfo.Create(metadata.Language.LanguageCode, metadata.Language.LanguageName, Optional<string>.FromNullable(metadata.Language.NativeName));
|
||||
if (languageInfoResult.IsFailure)
|
||||
return languageInfoResult.Errors;
|
||||
languageInfo = languageInfoResult.Value;
|
||||
}
|
||||
if (metadata.Language is not null && metadata.Language.LanguageCode is not null && metadata.Language.LanguageName is not null)
|
||||
languageInfo = LanguageInfo.Create(
|
||||
metadata.Language.LanguageCode,
|
||||
metadata.Language.LanguageName,
|
||||
Optional<string>.FromNullable(metadata.Language.NativeName));
|
||||
|
||||
Optional<LanguageInfo> originalLanguageInfo = Optional<LanguageInfo>.None();
|
||||
if (metadata.OriginalLanguage is not null)
|
||||
{
|
||||
Result<LanguageInfo> originalLanguageInfoResult = LanguageInfo.Create(metadata.OriginalLanguage.LanguageCode, metadata.OriginalLanguage.LanguageName, Optional<string>.FromNullable(metadata.OriginalLanguage.NativeName));
|
||||
if (originalLanguageInfoResult.IsFailure)
|
||||
return originalLanguageInfoResult.Errors;
|
||||
originalLanguageInfo = originalLanguageInfoResult.Value;
|
||||
}
|
||||
if (metadata.OriginalLanguage is not null && metadata.OriginalLanguage.LanguageCode is not null && metadata.OriginalLanguage.LanguageName is not null)
|
||||
originalLanguageInfo = LanguageInfo.Create(
|
||||
metadata.OriginalLanguage.LanguageCode,
|
||||
metadata.OriginalLanguage.LanguageName,
|
||||
Optional<string>.FromNullable(metadata.OriginalLanguage.NativeName));
|
||||
|
||||
Result<WrittenContentMetadata> writtenContentMetadataResult = WrittenContentMetadata.Create(
|
||||
metadata.Title,
|
||||
|
||||
+4
-4
@@ -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,7 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
|
||||
/// <summary>
|
||||
/// Command for adding a book.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The Id of the media library this book belongs to.</param>
|
||||
/// <param name="LibraryId">The unique identifier of the media library this book belongs to, taken from the route.</param>
|
||||
/// <param name="Path">The file system path of the book.</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>
|
||||
@@ -35,7 +35,7 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
|
||||
/// <param name="Ratings">The list of ratings for this book.</param>
|
||||
[DebuggerDisplay("Title: {Metadata.Title}")]
|
||||
public record AddBookCommand(
|
||||
Guid LibraryId,
|
||||
string? LibraryId,
|
||||
string Path,
|
||||
WrittenContentMetadataDto? Metadata,
|
||||
BookFormat? Format,
|
||||
@@ -52,6 +52,6 @@ public record AddBookCommand(
|
||||
string? BarnesAndNobleId,
|
||||
string? AppleBooksId,
|
||||
List<IsbnDto>? ISBNs,
|
||||
List<MediaContributorDto>? Contributors,
|
||||
List<MediaContributorReferenceDto>? Contributors,
|
||||
List<BookRatingDto>? Ratings
|
||||
) : ICommand;
|
||||
+63
-154
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
@@ -8,24 +9,17 @@ 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.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
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 Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
@@ -39,6 +33,7 @@ public class AddBookCommandHandler : ICommandHandler<AddBookCommand, Result<Book
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<AddBookCommand> _validator;
|
||||
private readonly IPathService _pathService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddBookCommandHandler"/> class.
|
||||
@@ -47,12 +42,14 @@ public class AddBookCommandHandler : ICommandHandler<AddBookCommand, Result<Book
|
||||
/// <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 AddBookCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<AddBookCommand> validator)
|
||||
/// <param name="pathService">Injected service for file system path related functionality.</param>
|
||||
public AddBookCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<AddBookCommand> validator, IPathService pathService)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_validator = validator;
|
||||
_pathService = pathService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -75,163 +72,75 @@ public class AddBookCommandHandler : ICommandHandler<AddBookCommand, Result<Book
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The validator guarantees that the library id of the route is a non-empty Guid before this point.
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
|
||||
// Admins can add books to all libraries; for everyone else, only to the libraries they own.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// TODO: update Api.Book.md documentation when the functionality is fully implemented.
|
||||
BookSeries? bookSeries = null;
|
||||
if (command.Series != null)
|
||||
{
|
||||
// TODO: add logic to search the book series repository for existing book series, based on the provided title.
|
||||
// TODO: uncomment integration and unit tests about series.
|
||||
}
|
||||
List<Result<BookRating>> domainRatingsResult = command.Ratings!.ConvertAll(rating => BookRating.Create(
|
||||
rating.Value ?? default,
|
||||
rating.MaxValue ?? default,
|
||||
Optional<BookRatingSource>.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : (BookRatingSource?)null),
|
||||
Optional<int>.FromNullable(rating.VoteCount)));
|
||||
// Check if any of the results contain errors.
|
||||
List<Error> errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)];
|
||||
if (errors.Count != 0) // if there are errors, return them
|
||||
return errors;
|
||||
// A book is only readable if it is stored inside one of the content locations of its library, so a client can never register an entry that points the reading pipeline at an arbitrary file of the host.
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
|
||||
List<BookRating> domainRatings = [.. domainRatingsResult.Select(rating => rating.Value)];
|
||||
if (!getLibraryResult.Value.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(command.Path, contentLocation.Path)))
|
||||
return DomainErrors.WrittenContent.BookPathMustBeWithinLibraryContentLocations;
|
||||
|
||||
List<Result<Genre>> domainGenresResult = command.Metadata!.Genres!.ConvertAll(genre => Genre.Create(genre.Name!));
|
||||
errors = [.. domainGenresResult.Where(genreResult => genreResult.IsFailure).SelectMany(genreResult => genreResult.Errors)];
|
||||
if (errors.Count != 0)
|
||||
return errors;
|
||||
List<Genre> domainGenres = [.. domainGenresResult.Select(genre => genre.Value)];
|
||||
// Media contributors are referenced by Id and are never created implicitly by adding a book, so each one must already exist.
|
||||
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false);
|
||||
if (getContributorsResult.IsFailure)
|
||||
return getContributorsResult.Errors;
|
||||
|
||||
List<Result<Tag>> domainTagsResult = command.Metadata.Tags!.ConvertAll(tag => Tag.Create(tag.Name!));
|
||||
errors = [.. domainTagsResult.Where(tagResult => tagResult.IsFailure).SelectMany(tagResult => tagResult.Errors)];
|
||||
if (errors.Count != 0)
|
||||
return errors;
|
||||
List<Tag> domainTags = [.. domainTagsResult.Select(tag => tag.Value)];
|
||||
|
||||
List<Result<Isbn>> domainIsbnsResult = command.ISBNs!.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!));
|
||||
errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors)];
|
||||
if (errors.Count != 0)
|
||||
return errors;
|
||||
List<Isbn> domainIsbns = [.. domainIsbnsResult.Select(isbn => isbn.Value)];
|
||||
|
||||
Result<ReleaseInfo> releaseInfoResult = ReleaseInfo.Create(
|
||||
Optional<DateOnly>.FromNullable(command.Metadata.ReleaseInfo!.OriginalReleaseDate),
|
||||
Optional<int>.FromNullable(command.Metadata.ReleaseInfo.OriginalReleaseYear),
|
||||
Optional<DateOnly>.FromNullable(command.Metadata.ReleaseInfo.ReReleaseDate),
|
||||
Optional<int>.FromNullable(command.Metadata.ReleaseInfo.ReReleaseYear),
|
||||
Optional<ReleaseCountry>.FromNullable(command.Metadata.ReleaseInfo!.ReleaseCountry),
|
||||
Optional<string>.FromNullable(command.Metadata.ReleaseInfo.ReleaseVersion)
|
||||
);
|
||||
if (releaseInfoResult.IsFailure)
|
||||
return releaseInfoResult.Errors;
|
||||
ReleaseInfo releaseInfo = releaseInfoResult.Value;
|
||||
LanguageInfo? languageInfo = null;
|
||||
if (command.Metadata.Language is not null)
|
||||
{
|
||||
Result<LanguageInfo> languageInfoResult = LanguageInfo.Create(
|
||||
command.Metadata.Language.LanguageCode!,
|
||||
command.Metadata.Language.LanguageName!,
|
||||
Optional<string>.FromNullable(command.Metadata.Language.NativeName));
|
||||
if (languageInfoResult.IsFailure)
|
||||
return languageInfoResult.Errors;
|
||||
languageInfo = languageInfoResult.Value;
|
||||
}
|
||||
LanguageInfo? originalLanguageInfo = null;
|
||||
if (command.Metadata.OriginalLanguage is not null)
|
||||
{
|
||||
Result<LanguageInfo> originalLanguageInfoResult = LanguageInfo.Create(
|
||||
command.Metadata.OriginalLanguage.LanguageCode!,
|
||||
command.Metadata.OriginalLanguage.LanguageName!,
|
||||
Optional<string>.FromNullable(command.Metadata.OriginalLanguage.NativeName));
|
||||
if (originalLanguageInfoResult.IsFailure)
|
||||
return originalLanguageInfoResult.Errors;
|
||||
originalLanguageInfo = originalLanguageInfoResult.Value;
|
||||
}
|
||||
Result<WrittenContentMetadata> metadataResult = WrittenContentMetadata.Create(
|
||||
command.Metadata.Title!,
|
||||
Optional<string>.FromNullable(command.Metadata.OriginalTitle),
|
||||
Optional<string>.FromNullable(command.Metadata.Description),
|
||||
releaseInfo,
|
||||
domainGenres,
|
||||
domainTags,
|
||||
Optional<LanguageInfo>.FromNullable(languageInfo),
|
||||
Optional<LanguageInfo>.FromNullable(originalLanguageInfo),
|
||||
Optional<string>.FromNullable(command.Metadata.Publisher),
|
||||
Optional<int>.FromNullable(command.Metadata.PageCount)
|
||||
);
|
||||
if (metadataResult.IsFailure)
|
||||
return metadataResult.Errors;
|
||||
|
||||
// Link the media contributors typed by the user to the book, finding or creating a single contributor per person; the same person
|
||||
// can be credited under several roles, so every distinct display name must resolve to the same media contributor row.
|
||||
List<MediaContributorId> contributorIds = [];
|
||||
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);
|
||||
}
|
||||
|
||||
contributorIds.Add(MediaContributorId.Create(contributorEntity.Id));
|
||||
}
|
||||
|
||||
Result<Book> createBookResult = Book.Create(
|
||||
LibraryId.Create(command.LibraryId),
|
||||
command.Path,
|
||||
metadataResult.Value,
|
||||
Optional<BookFormat>.FromNullable(command.Format),
|
||||
Optional<string>.FromNullable(command.Edition),
|
||||
command.VolumeNumber ?? default,
|
||||
Optional<BookSeries>.FromNullable(bookSeries),
|
||||
Optional<string>.FromNullable(command.ASIN),
|
||||
Optional<string>.FromNullable(command.GoodreadsId),
|
||||
Optional<string>.FromNullable(command.LCCN),
|
||||
Optional<string>.FromNullable(command.OCLCNumber),
|
||||
Optional<string>.FromNullable(command.OpenLibraryId),
|
||||
Optional<string>.FromNullable(command.LibraryThingId),
|
||||
Optional<string>.FromNullable(command.GoogleBooksId),
|
||||
Optional<string>.FromNullable(command.BarnesAndNobleId),
|
||||
Optional<string>.FromNullable(command.AppleBooksId),
|
||||
domainIsbns,
|
||||
contributorIds,
|
||||
ratings: domainRatings
|
||||
);
|
||||
// Convert the command to a domain aggregate to enforce invariants, then persist it in the repository.
|
||||
Result<Book> createBookResult = command.ToDomainEntity(libraryId);
|
||||
if (createBookResult.IsFailure)
|
||||
return createBookResult.Errors;
|
||||
|
||||
// The participation rows need the generated id of the book, so they are built once the domain book exists.
|
||||
BookEntity persistenceBook = createBookResult.Value.ToRepositoryEntity();
|
||||
persistenceBook.CreatedBy = userId;
|
||||
persistenceBook.BookContributors = [.. command.Contributors!
|
||||
.Where(contributor => contributor.Name?.DisplayName is not null)
|
||||
.Select(contributor => new BookContributorEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
BookId = persistenceBook.Id,
|
||||
MediaContributorId = contributorsByDisplayName[contributor.Name!.DisplayName!].Id,
|
||||
RoleName = contributor.Role?.Name ?? "Contributor",
|
||||
RoleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = userId,
|
||||
UpdatedBy = null
|
||||
})];
|
||||
Result<Created> insertBookResult = await _unitOfWork.BookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false);
|
||||
Result<Created> insertBookResult = await _unitOfWork.BookRepository.InsertAsync(createBookResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (insertBookResult.IsFailure)
|
||||
return insertBookResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return persistenceBook.ToResponse() with { Contributors = command.Contributors };
|
||||
// The pre-insert checks handle the common cases; a concurrent request could still persist a book at the same path of the same
|
||||
// library between them and the save, in which case the persistence medium reports the unique constraint violation as a conflict.
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// 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(createBookResult.Value.Id.Value, 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(AddBookCommand 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);
|
||||
}
|
||||
}
|
||||
+32
-41
@@ -18,22 +18,31 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
|
||||
/// </summary>
|
||||
public AddBookCommandValidator()
|
||||
{
|
||||
// Validates the identifier of the media library that will own the book, taken from the route.
|
||||
RuleFor(command => command.LibraryId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.WrittenContent.BookLibraryCannotBeNull)
|
||||
.Must(id => id != Guid.Empty)
|
||||
.WithError(Errors.WrittenContent.BookLibraryCannotBeNull);
|
||||
.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 file system path of the book.
|
||||
RuleFor(command => command.Path)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.WrittenContent.BookPathCannotBeEmpty);
|
||||
.WithError(Errors.WrittenContent.BookPathCannotBeEmpty)
|
||||
.MaximumLength(2048)
|
||||
.WithError(Errors.WrittenContent.BookPathMustBeMaximum2048CharactersLong);
|
||||
|
||||
// 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)
|
||||
@@ -130,7 +139,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
|
||||
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);
|
||||
|
||||
@@ -148,7 +157,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
|
||||
|
||||
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);
|
||||
|
||||
@@ -175,6 +184,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
|
||||
.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)
|
||||
@@ -190,6 +200,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
|
||||
.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)
|
||||
@@ -199,6 +210,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
|
||||
.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)
|
||||
@@ -249,6 +261,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
|
||||
.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);
|
||||
@@ -274,49 +287,27 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
|
||||
.IsInEnum()
|
||||
.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);
|
||||
|
||||
Reference in new issue
Block a user