Adds refactoring

This commit is contained in:
BinaryAlley committed 2024-08-28 21:52:41 +03:00
1 parent 9d840db864
commit f37d06f8df
9 files changed
+109 -49

No files matched your search

@@ -60,7 +60,7 @@ public class BookMappingConfig : IRegister
.Map(dest => dest.ISBNs, src => src.ISBNs)
.Map(dest => dest.Ratings, src => src.Ratings)
.Map(dest => dest.Created, src => src.Created)
.Map(dest => dest.Updated, src => src.Updated);
.Map(dest => dest.Updated, src => src.Updated.HasValue ? src.Updated : null);
config.NewConfig<BookRating, BookRatingDto>()
.Map(dest => dest.Value, src => src.Value)
@@ -71,7 +71,7 @@ public class BookMappingConfig : IRegister
config.NewConfig<Optional<BookRatingSource>, BookRatingSource?>()
.MapWith(src => src.HasValue ? src.Value : default);
// from BookDto to Book
config.NewConfig<BookDto, Book>()
.MapWith(src => Book.Create(
BookId.Create(src.Id),
@@ -101,11 +101,11 @@ public class BookMappingConfig : IRegister
).Value : Optional<LanguageInfo>.None(),
Optional<string>.FromNullable(src.Publisher),
Optional<int>.FromNullable(src.PageCount)
),
).Value,
Enum.Parse<BookFormat>(src.Format),
Optional<string>.FromNullable(src.Edition),
Optional<int>.FromNullable(src.VolumeNumber),
Optional<BookSeries>.None(), // Assuming BookSeries is not part of BookDto
Optional<BookSeries>.None(),
Optional<string>.FromNullable(src.ASIN),
Optional<string>.FromNullable(src.GoodreadsId),
Optional<string>.FromNullable(src.LCCN),
@@ -115,17 +115,17 @@ public class BookMappingConfig : IRegister
Optional<string>.FromNullable(src.GoogleBooksId),
Optional<string>.FromNullable(src.BarnesAndNobleId),
Optional<string>.FromNullable(src.AppleBooksId),
src.Created,
Optional<DateTime>.FromNullable(src.Updated),
src.ISBNs.Select(i => Isbn.Create(i.Value, i.Format).Value).ToList(),
new List<MediaContributorId>(), // Assuming MediaContributorId is not part of BookDto
new List<MediaContributorId>(),
src.Ratings.Select(r => BookRating.Create(
r.Value,
r.MaxValue,
Optional<BookRatingSource>.FromNullable(r.Source),
Optional<int>.FromNullable(r.VoteCount)
).Value).ToList()
).Value) // Assuming Create returns ErrorOr<Book>, we take the Value
.Ignore(dest => dest.Created)
.Ignore(dest => dest.Updated);
).Value);
}
#endregion
}
@@ -125,7 +125,7 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
return originalLanguageInfoResult.Errors;
originalLanguageInfo = originalLanguageInfoResult.Value;
}
WrittenContentMetadata metadata = WrittenContentMetadata.Create(
var metadataResult = WrittenContentMetadata.Create(
request.Metadata.Title,
Optional<string>.FromNullable(request.Metadata.OriginalTitle),
Optional<string>.FromNullable(request.Metadata.Description),
@@ -137,9 +137,10 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
Optional<string>.FromNullable(request.Metadata.Publisher),
Optional<int>.FromNullable(request.Metadata.PageCount)
);
if (metadataResult.IsError)
return metadataResult.Errors;
var createBookResult = Book.Create(
metadata,
metadataResult.Value,
request.Format,
Optional<string>.FromNullable(request.Edition),
request.VolumeNumber ?? default,
@@ -1,6 +1,8 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Enums;
using Lumina.Domain.Common.Errors;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands;
@@ -157,7 +159,12 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
{
isbn.RuleFor(i => i.Value)
.NotEmpty().WithMessage(Errors.WrittenContent.IsbnValueCannotBeEmpty.Code)
.MaximumLength(13).WithMessage(Errors.WrittenContent.InvalidIsbn13Format.Code);
.Matches(i => i.Format == IsbnFormat.Isbn13
? @"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$"
: @"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$")
.WithMessage(i => i.Format == IsbnFormat.Isbn13
? Errors.WrittenContent.InvalidIsbn13Format.Code
: Errors.WrittenContent.InvalidIsbn10Format.Code);
isbn.RuleFor(i => i.Format)
.IsInEnum().WithMessage(Errors.WrittenContent.UnknownIsbnFormat.Code);
});
@@ -196,5 +203,35 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
.WithMessage(Errors.Metadata.RatingVoteCountMustBePositive.Code);
});
}
public static bool ValidateIsbn10(string isbn)
{
isbn = isbn.Replace("-", "").Replace(" ", "").ToUpper();
if (!Regex.IsMatch(isbn, @"^(?:\d{9}[\dX])$"))
return false;
int sum = 0;
for (int i = 0; i < 9; i++)
sum += (10 - i) * (isbn[i] - '0');
char lastChar = isbn[9];
sum += lastChar == 'X' ? 10 : (lastChar - '0');
return sum % 11 == 0;
}
public static bool ValidateIsbn13(string isbn)
{
if (!Regex.IsMatch(isbn, @"^(978|979)-[0-9]{1,5}-[0-9]+-[0-9]+-[0-9]$"))
return false;
isbn = isbn.Replace("-", "");
int sum = 0;
for (int i = 0; i < 12; i++)
sum += (i % 2 == 0) ? isbn[i] - '0' : (isbn[i] - '0') * 3;
int checkDigit = (10 - (sum % 10)) % 10;
return checkDigit == (isbn[12] - '0');
}
#endregion
}
@@ -139,10 +139,12 @@ public sealed class Book : AggregateRoot<BookId>
/// <param name="googleBooksId">The optional Google Books ID of the book.</param>
/// <param name="barnesAndNobleId">The optional Barnes & Noble ID of the book.</param>
/// <param name="appleBooksId">The optional Apple Books ID of the book.</param>
/// <param name="created">The date and time when the entity was created.</param>
/// <param name="updated">The date and time when the entity was last updated.</param>
/// <param name="isbns">The list of ISBNs of the book.</param>
/// <param name="contributors">The list of media contributors of the book.</param>
/// <param name="ratings">The list of ratings for the book.</param>
public Book(
private Book(
BookId id,
WrittenContentMetadata metadata,
BookFormat format,
@@ -158,6 +160,8 @@ public sealed class Book : AggregateRoot<BookId>
Optional<string> googleBooksId,
Optional<string> barnesAndNobleId,
Optional<string> appleBooksId,
DateTime created,
Optional<DateTime> updated,
List<Isbn> isbns,
List<MediaContributorId> contributors,
List<BookRating> ratings) : base(id)
@@ -177,6 +181,8 @@ public sealed class Book : AggregateRoot<BookId>
GoogleBooksId = googleBooksId;
BarnesAndNobleId = barnesAndNobleId;
AppleBooksId = appleBooksId;
Created = created;
Updated = updated.HasValue ? updated.Value : null;
_isbns = isbns;
_contributors = contributors;
_ratings = ratings;
@@ -253,6 +259,8 @@ public sealed class Book : AggregateRoot<BookId>
googleBooksId,
barnesAndNobleId,
appleBooksId,
DateTime.UtcNow,
default,
isbns,
contributors,
ratings);
@@ -276,6 +284,8 @@ public sealed class Book : AggregateRoot<BookId>
/// <param name="googleBooksId">The optional Google Books ID of the book.</param>
/// <param name="barnesAndNobleId">The optional Barnes & Noble ID of the book.</param>
/// <param name="appleBooksId">The optional Apple Books ID of the book.</param>
/// <param name="created">The date and time when the entity was created.</param>
/// <param name="updated">The date and time when the entity was last updated.</param>
/// <param name="isbns">The list of ISBNs of the book.</param>
/// <param name="contributors">The list of media contributors of the book.</param>
/// <param name="ratings">The list of ratings for the book.</param>
@@ -298,6 +308,8 @@ public sealed class Book : AggregateRoot<BookId>
Optional<string> googleBooksId,
Optional<string> barnesAndNobleId,
Optional<string> appleBooksId,
DateTime created,
Optional<DateTime> updated,
List<Isbn> isbns,
List<MediaContributorId> contributors,
List<BookRating> ratings)
@@ -319,6 +331,8 @@ public sealed class Book : AggregateRoot<BookId>
googleBooksId,
barnesAndNobleId,
appleBooksId,
created,
updated,
isbns,
contributors,
ratings);
@@ -13,6 +13,11 @@ namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggrega
/// </summary>
public sealed class Isbn : ValueObject
{
#region ================================================================== FIELD MEMBERS ================================================================================
private static readonly Regex Isbn10Regex = new(@"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$", RegexOptions.Compiled);
private static readonly Regex Isbn13Regex = new(@"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$", RegexOptions.Compiled);
#endregion
#region ==================================================================== PROPERTIES =================================================================================
/// <summary>
/// Gets the value of the ISBN.
@@ -71,58 +76,40 @@ public sealed class Isbn : ValueObject
/// <summary>
/// Validates an ISBN-10 string.
/// </summary>
/// <param name="isbn">The ISBN-10 string to validate, without hyphens or spaces.</param>
/// <param name="isbn">The ISBN-10 string to validate, with or without hyphens or spaces.</param>
/// <returns><see langword="true"/> if the ISBN-10 is valid, <see langword="false"/> otherwise.</returns>
public static bool IsValidIsbn10(string isbn)
{
// ISBN-10 must be exactly 10 characters long
if (isbn.Length != 10)
if (!Isbn10Regex.IsMatch(isbn))
return false;
// remove any hyphens or spaces
isbn = isbn.Replace("-", "").Replace(" ", "").ToUpper();
int sum = 0;
for (int i = 0; i < 9; i++)
{
// each of the first 9 characters must be a digit
if (!char.IsDigit(isbn[i]))
return false;
// calculate the sum: each digit is multiplied by its position (10 to 2) and added
sum += (10 - i) * (isbn[i] - '0');
}
// check the last character, which can be a digit or 'X'
char lastChar = isbn[9];
if (lastChar == 'X' || lastChar == 'x')
if (lastChar == 'X')
sum += 10;
else if (char.IsDigit(lastChar))
sum += lastChar - '0';
else
return false;
// the ISBN-10 is valid if the sum is divisible by 11
sum += lastChar - '0';
return sum % 11 == 0;
}
/// <summary>
/// Validates an ISBN-13 string.
/// </summary>
/// <param name="isbn">The ISBN-13 string to validate, without hyphens or spaces.</param>
/// <param name="isbn">The ISBN-13 string to validate, with or without hyphens or spaces.</param>
/// <returns><see langword="true"/> if the ISBN-13 is valid, <see langword="false"/> otherwise.</returns>
public static bool IsValidIsbn13(string isbn)
{
// ISBN-13 must be exactly 13 characters long
if (isbn.Length != 13)
if (!Isbn13Regex.IsMatch(isbn))
return false;
// remove any hyphens or spaces
isbn = isbn.Replace("-", "").Replace(" ", "");
int sum = 0;
for (int i = 0; i < 12; i++)
{
// each of the first 12 characters must be a digit
if (!char.IsDigit(isbn[i]))
return false;
// calculate the sum: alternate digits are multiplied by 3
sum += (i % 2 == 0) ? isbn[i] - '0' : 3 * (isbn[i] - '0');
}
// calculate the check digit
int checkDigit = 10 - (sum % 10);
if (checkDigit == 10)
checkDigit = 0;
// the ISBN-13 is valid if the calculated check digit matches the last digit
int checkDigit = (10 - (sum % 10)) % 10;
return checkDigit == (isbn[12] - '0');
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using System.Diagnostics;
@@ -70,7 +71,10 @@ public class WrittenContentMetadata : BaseMetadata
/// <param name="originalLanguage">The optional original language of the video.</param>
/// <param name="publisher">The publisher of the written content.</param>
/// <param name="pageCount">The number of pages in the written content.</param>
public static WrittenContentMetadata Create(
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="WrittenContentMetadata"/>, or an error message.
/// </returns>
public static ErrorOr<WrittenContentMetadata> Create(
string title,
Optional<string> originalTitle,
Optional<string> description,
@@ -2,20 +2,20 @@
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands;
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Queries;
using Lumina.Presentation.Api.Common.Contracts.Books;
using Lumina.Presentation.Api.Controllers.Common;
using Lumina.Presentation.Api.Core.Controllers.Common;
using MapsterMapper;
using Mediator;
using Microsoft.AspNetCore.Mvc;
#endregion
namespace Lumina.Presentation.Api.Controllers.Books;
namespace Lumina.Presentation.Api.Core.Controllers.Books;
/// <summary>
/// Controller for managing books.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class BooksController : ApiController
public class BooksController : ApiController
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly ISender _mediator;
@@ -49,12 +49,12 @@ public class BooksController : ApiController
/// <summary>
/// Controller action for adding a book.
/// </summary>
/// <param name="command">The command to add a book.</param>
/// <param name="request">The command to add a book.</param>
[HttpPost()]
public async Task<IActionResult> AddBook(AddBookRequest request)
{
var result = await _mediator.Send(_mapper.Map<AddBookCommand>(request));
return result.Match(result => Ok(result), errors => Problem(errors));
return result.Match(result => Created($"/api/v1/books/{result.Id}", result), errors => Problem(errors));
}
#endregion
}
@@ -5,7 +5,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
#endregion
namespace Lumina.Presentation.Api.Controllers.Common;
namespace Lumina.Presentation.Api.Core.Controllers.Common;
/// <summary>
/// Base class for API controllers.
+17
View File
@@ -63,6 +63,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "books", "books", "{FAFD9E43
..\docs\technical\requests\books\GetAll.http = ..\docs\technical\requests\books\GetAll.http
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "IntegrationTests", "IntegrationTests", "{3F057926-562F-4EF4-BFC0-EE62372D4551}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.DataAccess.IntegrationTests", "..\tests\IntegrationTests\Lumina.DataAccess.IntegrationTests\Lumina.DataAccess.IntegrationTests.csproj", "{6B3FC07B-6208-4544-ACFB-79243A59EA1A}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Presentation.Api.IntegrationTests", "..\tests\IntegrationTests\Lumina.Presentation.Api.IntegrationTests\Lumina.Presentation.Api.IntegrationTests.csproj", "{3680DAFB-10BA-4A0F-AE40-620D06DAF617}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -113,6 +119,14 @@ Global
{4D5E4789-8437-4F3B-883E-28BBF8A4848F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4D5E4789-8437-4F3B-883E-28BBF8A4848F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4D5E4789-8437-4F3B-883E-28BBF8A4848F}.Release|Any CPU.Build.0 = Release|Any CPU
{6B3FC07B-6208-4544-ACFB-79243A59EA1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6B3FC07B-6208-4544-ACFB-79243A59EA1A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6B3FC07B-6208-4544-ACFB-79243A59EA1A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6B3FC07B-6208-4544-ACFB-79243A59EA1A}.Release|Any CPU.Build.0 = Release|Any CPU
{3680DAFB-10BA-4A0F-AE40-620D06DAF617}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3680DAFB-10BA-4A0F-AE40-620D06DAF617}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3680DAFB-10BA-4A0F-AE40-620D06DAF617}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3680DAFB-10BA-4A0F-AE40-620D06DAF617}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -135,6 +149,9 @@ Global
{4F8D14A3-A465-4EC2-B175-A188B113AB99} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2}
{C17A1188-FA69-42BC-92E6-4F91D31B3A58} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2}
{FAFD9E43-508B-4F20-8AA2-8CADA697ED2D} = {C17A1188-FA69-42BC-92E6-4F91D31B3A58}
{3F057926-562F-4EF4-BFC0-EE62372D4551} = {16E590D3-DD9F-4B45-BF19-C6E317A57D11}
{6B3FC07B-6208-4544-ACFB-79243A59EA1A} = {3F057926-562F-4EF4-BFC0-EE62372D4551}
{3680DAFB-10BA-4A0F-AE40-620D06DAF617} = {3F057926-562F-4EF4-BFC0-EE62372D4551}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4A55A28E-C657-4A0B-95EA-2931AE66004E}