Adds the capability of adding a Book via API

This commit is contained in:
BinaryAlley committed 2024-08-24 22:11:55 +03:00
1 parent 6459b6f2c2
commit 0eb7b453f6
61 files changed
+1276 -255

No files matched your search

@@ -47,7 +47,7 @@ public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TReques
if (validationResult.IsValid)
return await next(request, cancellationToken);
// after the command handler is executed
var errors = validationResult.Errors.ConvertAll(validationFailure => Error.Validation(validationFailure.ErrorMessage));
var errors = validationResult.Errors.ConvertAll(validationFailure => Error.Validation(description: validationFailure.ErrorMessage));
// the compiler doesn't know there is an implicit converter from a list of errors to the ErrorOr object, and unfortunately, there is no way around this but to use some magic
// this is acceptable because we DO know that we will always have a list of errors of type ErrorOr (check the generic constraint at the top of the class!)
return (dynamic)errors;
@@ -0,0 +1,45 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json;
using System.Text.Json.Serialization;
using Lumina.Domain.Common.Primitives;
#endregion
namespace Lumina.Application.Common.Converters;
/// <summary>
/// Converts an <see cref="Optional{T}"/> to and from JSON.
/// </summary>
/// <typeparam name="T">The type of the value represented by the <see cref="Optional{T}"/> structure.</typeparam>
public class OptionalJsonConverter<T> : JsonConverter<Optional<T>>
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Reads and converts the JSON to an instance of <see cref="Optional{T}"/>.
/// </summary>
/// <param name="reader">The <see cref="Utf8JsonReader"/> to read from.</param>
/// <param name="typeToConvert">The type to convert.</param>
/// <param name="options">An object that specifies serialization options to use.</param>
/// <returns>The converted <see cref="Optional{T}"/> value.</returns>
public override Optional<T> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
return Optional<T>.None();
var value = JsonSerializer.Deserialize<T>(ref reader, options);
return Optional<T>.Some(value!);
}
/// <summary>
/// Writes an <see cref="Optional{T}"/> value as JSON.
/// </summary>
/// <param name="writer">The <see cref="Utf8JsonWriter"/> to write to.</param>
/// <param name="value">The value to convert to JSON.</param>
/// <param name="options">An object that specifies serialization options to use.</param>
public override void Write(Utf8JsonWriter writer, Optional<T> value, JsonSerializerOptions options)
{
if (value.HasValue)
JsonSerializer.Serialize(writer, value.Value, options);
else
writer.WriteNullValue();
}
#endregion
}
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json;
using System.Text.Json.Serialization;
using Lumina.Domain.Common.Primitives;
#endregion
namespace Lumina.Application.Common.Converters;
/// <summary>
/// A factory for creating <see cref="OptionalJsonConverter{T}"/> instances.
/// </summary>
public class OptionalJsonConverterFactory : JsonConverterFactory
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Determines whether the converter can convert the specified type.
/// </summary>
/// <param name="typeToConvert">The type to check for convertibility.</param>
/// <returns><see langword="true"/> if the type is <see cref="Optional{T}"/>, <see langword="false"/> otherwise.</returns>
public override bool CanConvert(Type typeToConvert)
{
if (!typeToConvert.IsGenericType)
return false;
return typeToConvert.GetGenericTypeDefinition() == typeof(Optional<>);
}
/// <summary>
/// Creates a converter for the specified type.
/// </summary>
/// <param name="typeToConvert">The type for which to create a converter.</param>
/// <param name="options">The serializer options to use.</param>
/// <returns>A converter for <see cref="Optional{T}"/>.</returns>
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
Type valueType = typeToConvert.GetGenericArguments()[0];
JsonConverter converter = (JsonConverter)Activator.CreateInstance(
typeof(OptionalJsonConverter<>).MakeGenericType(valueType))!;
return converter;
}
#endregion
}
@@ -3,6 +3,8 @@ using Lumina.Application.Common.Behaviors;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using FluentValidation;
using MapsterMapper;
using Mapster;
#endregion
namespace Lumina.Application.Common.DependencyInjection;
@@ -32,6 +34,12 @@ public static class ApplicationLayerServices
// register fluent validators
services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly);
// register mapster configs in this assembly
var mapsterConfig = TypeAdapterConfig.GlobalSettings;
mapsterConfig.Scan(typeof(ApplicationLayerServices).Assembly);
services.AddSingleton(mapsterConfig);
services.AddScoped<IMapper, ServiceMapper>();
return services;
}
#endregion
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Application.Common.Enums;
/// <summary>
/// Represents the format of a book.
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum BookFormat
{
Hardcover,
Paperback,
MassMarketPaperback,
TradePaperback,
eBook,
Audiobook,
LargePrint,
BoardBook,
SpiralBound,
LibraryBinding,
LeatherBound,
PopupBook
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Application.Common.Enums;
/// <summary>
/// Enumeration for the various sources of book ratings.
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum BookRatingSource
{
User,
Goodreads,
Amazon,
GoogleBooks,
}
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Application.Common.Enums;
/// <summary>
/// Enumeration for the different ISBN (International Standard Book Number) formats.
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum IsbnFormat
{
Isbn10,
Isbn13
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Application.Common.Enums;
/// <summary>
/// Enumeration for the various roles of media contributors across different types of media.
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum MediaContributorRole
{
Actor,
Director,
Singer,
Author,
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Enums;
#endregion
namespace Lumina.Application.Common.Models.Books;
/// <summary>
/// Represents a book.
/// </summary>
public record BookDto(
WrittenContentMetadataDto Metadata,
BookFormat Format,
string? Edition,
int? VolumeNumber,
BookSeriesDto? Series,
string? ASIN,
string? GoodreadsId,
string? LCCN,
string? OCLCNumber,
string? OpenLibraryId,
string? LibraryThingId,
string? GoogleBooksId,
string? BarnesAndNobleId,
string? KoboId,
string? AppleBooksId,
List<IsbnDto> ISBNs,
List<Guid> Contributors,
List<BookRatingDto> Ratings
);
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Enums;
using Lumina.Application.Common.Models.Common;
#endregion
namespace Lumina.Application.Common.Models.Books;
/// <summary>
/// Represents a book rating.
/// </summary>
public record BookRatingDto(
decimal Value,
decimal MaxValue,
BookRatingSource? Source,
int? VoteCount
) : RatingDto(Value, MaxValue, VoteCount);
@@ -0,0 +1,8 @@
namespace Lumina.Application.Common.Models.Books;
/// <summary>
/// Represents a request to get book series information.
/// </summary>
public record BookSeriesDto(
string Title
);
@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Enums;
#endregion
namespace Lumina.Application.Common.Models.Books;
/// <summary>
/// Represents a request to get ISBN information.
/// </summary>
public record IsbnDto(
string Value,
IsbnFormat Format
);
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Models.Common;
#endregion
namespace Lumina.Application.Common.Models.Books;
/// <summary>
/// Represents written content metadata.
/// </summary>
public record WrittenContentMetadataDto(
string Title,
string? OriginalTitle,
string? Description,
ReleaseInfoDto ReleaseInfo,
List<GenreDto> Genres,
List<TagDto> Tags,
LanguageInfoDto? Language,
LanguageInfoDto? OriginalLanguage,
string? Publisher,
int? PageCount
);
@@ -0,0 +1,8 @@
namespace Lumina.Application.Common.Models.Common;
/// <summary>
/// Represents a request to get genre information.
/// </summary>
public record GenreDto(
string Name
);
@@ -0,0 +1,10 @@
namespace Lumina.Application.Common.Models.Common;
/// <summary>
/// Represents a request to get language information.
/// </summary>
public record LanguageInfoDto(
string LanguageCode,
string LanguageName,
string? NativeName
);
@@ -0,0 +1,10 @@
namespace Lumina.Application.Common.Models.Common;
/// <summary>
/// Represents a rating.
/// </summary>
public abstract record RatingDto(
decimal Value,
decimal MaxValue,
int? VoteCount
);
@@ -0,0 +1,13 @@
namespace Lumina.Application.Common.Models.Common;
/// <summary>
/// Represents a request to get release information.
/// </summary>
public record ReleaseInfoDto(
DateOnly? OriginalReleaseDate,
int? OriginalReleaseYear,
DateOnly? ReReleaseDate,
int? ReReleaseYear,
string? ReleaseCountry,
string? ReleaseVersion
);
@@ -0,0 +1,8 @@
namespace Lumina.Application.Common.Models.Common;
/// <summary>
/// Represents a request to get tag information.
/// </summary>
public record TagDto(
string Name
);
@@ -0,0 +1,9 @@
namespace Lumina.Application.Common.Models.Contributors;
/// <summary>
/// Represents a media contributor.
/// </summary>
public record MediaContributorDto(
string Name,
MediaContributorRoleDto Role
);
@@ -0,0 +1,9 @@
namespace Lumina.Application.Common.Models.Contributors;
/// <summary>
/// Represents a media contributor name.
/// </summary>
public record MediaContributorNameDto(
string DisplayName,
string? LegalName
);
@@ -0,0 +1,9 @@
namespace Lumina.Application.Common.Models.Contributors;
/// <summary>
/// Represents a media contributor role.
/// </summary>
public record MediaContributorRoleDto(
string Name,
string Category
);
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.Models.Books;
using Lumina.Application.Common.Models.Contributors;
using Lumina.Domain.Common.Enums;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate;
using Mediator;
#endregion
namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands;
/// <summary>
/// Command for adding a book.
/// </summary>
public record AddBookCommand(
WrittenContentMetadataDto Metadata,
BookFormat Format,
string? Edition,
int? VolumeNumber,
BookSeriesDto? Series,
string? ASIN,
string? GoodreadsId,
string? LCCN,
string? OCLCNumber,
string? OpenLibraryId,
string? LibraryThingId,
string? GoogleBooksId,
string? BarnesAndNobleId,
string? KoboId,
string? AppleBooksId,
List<IsbnDto> ISBNs,
List<MediaContributorDto> Contributors,
List<BookRatingDto> Ratings
) : IRequest<ErrorOr<Book>>;
@@ -0,0 +1,143 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Enums;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects;
using Mediator;
#endregion
namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands;
/// <summary>
/// Handler for the command to add a book.
/// </summary>
public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Book>>
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Handles the command to add a book.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="Book"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<Book>> Handle(AddBookCommand request, CancellationToken cancellationToken)
{
List<MediaContributorId> contributorIds = new();
foreach(var mediaContributor in request.Contributors)
{
// TODO: add logic to search the media contributors repository for existing contributors, based on the provided names
}
BookSeries? bookSeries = null;
if (request.Series != null)
{
// TODO: add logic to search the book series repository for existing book series, based on the provided title
}
var domainRatingsResult = request.Ratings.ConvertAll(rating => BookRating.Create(
rating.Value,
rating.MaxValue,
Optional<BookRatingSource>.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : default),
Optional<int>.FromNullable(rating.VoteCount)));
// check if any of the results contain errors
var errors = domainRatingsResult.Where(ratingResult => ratingResult.IsError).SelectMany(ratingResult => ratingResult.Errors).ToList();
if (errors.Count != 0) // if there are errors, return them
return errors;
List<Rating> domainRatings = domainRatingsResult.Select(rating => rating.Value as Rating).ToList();
var domainGenresResult = request.Metadata.Genres.ConvertAll(genre => Genre.Create(genre.Name));
errors = domainGenresResult.Where(genreResult => genreResult.IsError).SelectMany(genreResult => genreResult.Errors).ToList();
if (errors.Count != 0)
return errors;
List<Genre> domainGenres = domainGenresResult.Select(genre => genre.Value).ToList();
var domainTagsResult = request.Metadata.Tags.ConvertAll(tag => Tag.Create(tag.Name));
errors = domainTagsResult.Where(tagResult => tagResult.IsError).SelectMany(tagResult => tagResult.Errors).ToList();
if (errors.Count != 0)
return errors;
List<Tag> domainTags = domainTagsResult.Select(tag => tag.Value).ToList();
var domainIsbnsResult = request.ISBNs.ConvertAll(isbn => Isbn.Create(isbn.Value, (IsbnFormat)(int)isbn.Format));
errors = domainIsbnsResult.Where(isbnResult => isbnResult.IsError).SelectMany(isbnResult => isbnResult.Errors).ToList();
if (errors.Count != 0)
return errors;
List<Isbn> domainIsbns = domainIsbnsResult.Select(isbn => isbn.Value).ToList();
var releaseInfoResult = ReleaseInfo.Create(
Optional<DateOnly>.FromNullable(request.Metadata.ReleaseInfo.OriginalReleaseDate),
Optional<int>.FromNullable(request.Metadata.ReleaseInfo.OriginalReleaseYear),
Optional<DateOnly>.FromNullable(request.Metadata.ReleaseInfo.ReReleaseDate),
Optional<int>.FromNullable(request.Metadata.ReleaseInfo.ReReleaseYear),
Optional<string>.FromNullable(request.Metadata.ReleaseInfo.ReleaseCountry),
Optional<string>.FromNullable(request.Metadata.ReleaseInfo.ReleaseVersion)
);
if (releaseInfoResult.IsError)
return releaseInfoResult.Errors;
ReleaseInfo releaseInfo = releaseInfoResult.Value;
LanguageInfo? languageInfo = null;
if (request.Metadata.Language is not null)
{
var languageInfoResult = LanguageInfo.Create(
request.Metadata.Language.LanguageCode,
request.Metadata.Language.LanguageName,
Optional<string>.FromNullable(request.Metadata.Language.NativeName));
if (languageInfoResult.IsError)
return languageInfoResult.Errors;
languageInfo = languageInfoResult.Value;
}
LanguageInfo? originalLanguageInfo = null;
if (request.Metadata.OriginalLanguage is not null)
{
var originalLanguageInfoResult = LanguageInfo.Create(
request.Metadata.OriginalLanguage.LanguageCode,
request.Metadata.OriginalLanguage.LanguageName,
Optional<string>.FromNullable(request.Metadata.OriginalLanguage.NativeName));
if (originalLanguageInfoResult.IsError)
return originalLanguageInfoResult.Errors;
originalLanguageInfo = originalLanguageInfoResult.Value;
}
WrittenContentMetadata metadata = WrittenContentMetadata.Create(
request.Metadata.Title,
Optional<string>.FromNullable(request.Metadata.OriginalTitle),
Optional<string>.FromNullable(request.Metadata.Description),
releaseInfo,
domainGenres,
domainTags,
Optional<LanguageInfo>.FromNullable(languageInfo),
Optional<LanguageInfo>.FromNullable(originalLanguageInfo),
Optional<string>.FromNullable(request.Metadata.Publisher),
Optional<int>.FromNullable(request.Metadata.PageCount)
);
var createBookResult = Book.Create(
metadata,
request.Format,
Optional<string>.FromNullable(request.Edition),
request.VolumeNumber ?? default,
Optional<BookSeries>.FromNullable(bookSeries),
Optional<string>.FromNullable(request.ASIN),
Optional<string>.FromNullable(request.GoodreadsId),
Optional<string>.FromNullable(request.LCCN),
Optional<string>.FromNullable(request.OCLCNumber),
Optional<string>.FromNullable(request.OpenLibraryId),
Optional<string>.FromNullable(request.LibraryThingId),
Optional<string>.FromNullable(request.GoogleBooksId),
Optional<string>.FromNullable(request.BarnesAndNobleId),
Optional<string>.FromNullable(request.KoboId),
Optional<string>.FromNullable(request.AppleBooksId),
domainIsbns,
contributorIds,
ratings: domainRatings
);
if (createBookResult.IsError)
return createBookResult.Errors;
return createBookResult.Value;
}
#endregion
}
@@ -0,0 +1,95 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
#endregion
namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands;
/// <summary>
/// Validates the needed validation rules for <see cref="AddBookCommand"/>.
/// </summary>
public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
{
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="AddBookCommandValidator"/> class.
/// </summary>
public AddBookCommandValidator()
{
RuleFor(x => x.Metadata).NotNull()
.ChildRules(metadata =>
{
metadata.RuleFor(m => m.Title).NotEmpty().MaximumLength(255);
metadata.RuleFor(m => m.OriginalTitle).MaximumLength(255);
metadata.RuleFor(m => m.Description).MaximumLength(2000);
metadata.RuleFor(m => m.ReleaseInfo).NotNull()
.ChildRules(ri =>
{
ri.RuleFor(r => r.OriginalReleaseYear).InclusiveBetween(1, 9999).When(r => r.OriginalReleaseYear.HasValue);
ri.RuleFor(r => r.ReReleaseYear).InclusiveBetween(1, 9999).When(r => r.ReReleaseYear.HasValue);
ri.RuleFor(r => r.ReleaseCountry).MaximumLength(50);
ri.RuleFor(r => r.ReleaseVersion).MaximumLength(50);
});
metadata.RuleFor(m => m.Genres).NotEmpty();
metadata.RuleForEach(m => m.Genres).ChildRules(g => g.RuleFor(genre => genre.Name).NotEmpty().MaximumLength(50));
metadata.RuleForEach(m => m.Tags).ChildRules(t => t.RuleFor(tag => tag.Name).NotEmpty().MaximumLength(50));
metadata.RuleFor(m => m.Language).ChildRules(l =>
{
l.RuleFor(x => x.LanguageCode).NotEmpty().MaximumLength(10);
l.RuleFor(x => x.LanguageName).NotEmpty().MaximumLength(50);
l.RuleFor(x => x.NativeName).MaximumLength(50);
}).When(m => m.Language != null);
metadata.RuleFor(m => m.OriginalLanguage).ChildRules(l =>
{
l.RuleFor(x => x.LanguageCode).NotEmpty().MaximumLength(10);
l.RuleFor(x => x.LanguageName).NotEmpty().MaximumLength(50);
l.RuleFor(x => x.NativeName).MaximumLength(50);
}).When(m => m.OriginalLanguage != null);
metadata.RuleFor(m => m.Publisher).MaximumLength(100);
metadata.RuleFor(m => m.PageCount).GreaterThan(0).When(m => m.PageCount.HasValue);
});
RuleFor(x => x.Format).IsInEnum();
RuleFor(x => x.Edition).MaximumLength(50);
RuleFor(x => x.VolumeNumber).GreaterThan(0).When(x => x.VolumeNumber.HasValue);
RuleFor(x => x.Series).ChildRules(s => s.RuleFor(series => series.Title).NotEmpty().MaximumLength(255)).When(x => x.Series != null);
RuleFor(x => x.ASIN).MaximumLength(10);
RuleFor(x => x.GoodreadsId).MaximumLength(20);
RuleFor(x => x.LCCN).MaximumLength(20);
RuleFor(x => x.OCLCNumber).MaximumLength(20);
RuleFor(x => x.OpenLibraryId).MaximumLength(20);
RuleFor(x => x.LibraryThingId).MaximumLength(20);
RuleFor(x => x.GoogleBooksId).MaximumLength(20);
RuleFor(x => x.BarnesAndNobleId).MaximumLength(20);
RuleFor(x => x.KoboId).MaximumLength(20);
RuleFor(x => x.AppleBooksId).MaximumLength(20);
RuleFor(x => x.ISBNs).NotEmpty();
RuleForEach(x => x.ISBNs).ChildRules(isbn =>
{
isbn.RuleFor(i => i.Value).NotEmpty().MaximumLength(13);
isbn.RuleFor(i => i.Format).IsInEnum();
});
RuleFor(x => x.Contributors).NotEmpty();
RuleForEach(x => x.Contributors).ChildRules(contributor =>
{
contributor.RuleFor(c => c.Name).NotEmpty().MaximumLength(100);
contributor.RuleFor(c => c.Role).ChildRules(role =>
{
role.RuleFor(r => r.Name).NotEmpty().MaximumLength(50);
role.RuleFor(r => r.Category).NotEmpty().MaximumLength(50);
});
});
RuleForEach(x => x.Ratings).ChildRules(rating =>
{
rating.RuleFor(r => r.Value).Must((r, value) => value >= 0 && value <= r.MaxValue)
.WithMessage("Value must be between 0 and MaxValue");
rating.RuleFor(r => r.MaxValue).GreaterThan(0);
rating.RuleFor(r => r.VoteCount).GreaterThanOrEqualTo(0).When(r => r.VoteCount.HasValue);
});
}
#endregion
}
@@ -1,21 +1,5 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Lumina.Domain\Lumina.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentValidation" Version="11.9.2" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.9.2" />
<PackageReference Include="Mediator.Abstractions" Version="2.1.7" />
<PackageReference Include="Mediator.SourceGenerator" Version="2.1.7">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
@@ -23,4 +7,21 @@
<BaseOutputPath>..\..\bin\</BaseOutputPath>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Lumina.Domain\Lumina.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Mapster" Version="7.4.0" />
<PackageReference Include="FluentValidation" Version="11.9.2" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.9.2" />
<PackageReference Include="Mapster.DependencyInjection" Version="1.0.1" />
<PackageReference Include="Mediator.Abstractions" Version="2.1.7" />
<PackageReference Include="Mediator.SourceGenerator" Version="2.1.7">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
</ItemGroup>
</Project>
@@ -7,4 +7,8 @@
<BaseOutputPath>..\..\bin\</BaseOutputPath>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Lumina.Application\Lumina.Application.csproj" />
</ItemGroup>
</Project>
@@ -1,27 +0,0 @@
namespace Lumina.Domain.Common.Enums;
/// <summary>
/// Enumeration for the various roles of media contributors across different types of media.
/// </summary>
public enum MediaContributorRole
{
/// <summary>
/// A person who portrays a character in a performance, typically in films, television shows, or theater productions.
/// </summary>
Actor,
/// <summary>
/// The person responsible for overseeing and directing the production of a film, play, television show, or other performing art.
/// </summary>
Director,
/// <summary>
/// A person who uses their voice to produce musical sounds, typically with a melody and often with lyrics in songs.
/// </summary>
Singer,
/// <summary>
/// The creator or originator of a written work, such as a book, article, or other literary piece.
/// </summary>
Author
}
@@ -24,7 +24,7 @@ public readonly struct Optional<T>
{
get
{
return HasValue ? _value! : throw new InvalidOperationException("Optional has no value.");
return HasValue ? _value! : default!;
}
}
#endregion
@@ -34,10 +34,11 @@ public readonly struct Optional<T>
/// Initializes a new instance of the <see cref="Optional{T}"/> structure.
/// </summary>
/// <param name="value">The value represented by this structure.</param>
public Optional(T value)
/// <param name="hasValue"><see langword="true"/> if <paramref name="value"/> is not <see langword="null"/>, <see langword="false"/>otherwise.</param>
private Optional(T? value, bool hasValue)
{
_value = value;
HasValue = true;
HasValue = hasValue;
}
#endregion
@@ -48,7 +49,47 @@ public readonly struct Optional<T>
/// <param name="value">The value to be converted.</param>
public static implicit operator Optional<T>(T value)
{
return new Optional<T>(value);
return Some(value);
}
/// <summary>
/// Creates an <see cref="Optional{T}"/> with a value.
/// </summary>
/// <param name="value">The value to wrap in the <see cref="Optional{T}"/>.</param>
/// <returns>An <see cref="Optional{T}"/> containing the specified value.</returns>
public static Optional<T> Some(T value)
{
return new Optional<T>(value, true);
}
/// <summary>
/// Creates an <see cref="Optional{T}"/> with no value.
/// </summary>
/// <returns>An empty <see cref="Optional{T}"/>.</returns>
public static Optional<T> None()
{
return new(default, false);
}
/// <summary>
/// Creates an <see cref="Optional{T}"/> from a nullable reference type.
/// </summary>
/// <param name="value">The nullable value to convert.</param>
/// <returns>An <see cref="Optional{T}"/> representing the nullable value.</returns>
public static Optional<T> FromNullable(T? value)
{
return value is null ? None() : Some(value);
}
/// <summary>
/// Creates an <see cref="Optional{T}"/> from a nullable value type.
/// </summary>
/// <typeparam name="TValue">The underlying value type.</typeparam>
/// <param name="value">The nullable value to convert.</param>
/// <returns>An <see cref="Optional{T}"/> representing the nullable value.</returns>
public static Optional<T> FromNullable<TValue>(TValue? value) where TValue : struct, T
{
return value.HasValue ? Some(value.Value) : None();
}
#endregion
}
@@ -71,8 +71,8 @@ public abstract class BaseMetadata : ValueObject
/// </summary>
/// <param name="title">The title of the element to which this metadata object belongs to.</param>
/// <param name="originalTitle">The optional original title of the element to which this metadata object belongs to.</param>
/// <param name="releaseInfo">The optional release information of the media item.</param>
/// <param name="description">The optional description of the element to which this metadata object belongs to.</param>
/// <param name="releaseInfo">The optional release information of the media item.</param>
/// <param name="genres">The list of genres of the element to which this metadata object belongs to.</param>
/// <param name="tags">The list of tags of the element to which this metadata object belongs to.</param>
/// <param name="language">The optional language of the element to which this metadata object belongs to.</param>
@@ -81,8 +81,8 @@ public abstract class BaseMetadata : ValueObject
protected BaseMetadata(
string title,
Optional<string> originalTitle,
ReleaseInfo releaseInfo,
Optional<string> description,
ReleaseInfo releaseInfo,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
@@ -90,8 +90,8 @@ public abstract class BaseMetadata : ValueObject
{
Title = title ?? throw new ArgumentNullException(nameof(title));
OriginalTitle = originalTitle;
ReleaseInfo = releaseInfo;
Description = description;
ReleaseInfo = releaseInfo;
_genres = genres;
_tags = tags;
Language = language;
@@ -105,8 +105,8 @@ public abstract class BaseMetadata : ValueObject
{
yield return Title;
yield return OriginalTitle;
yield return ReleaseInfo;
yield return Description;
yield return ReleaseInfo;
foreach (var genre in _genres)
yield return genre;
foreach (var tag in _tags)
@@ -36,7 +36,7 @@ public class Genre : ValueObject
/// </summary>
/// <param name="name">The value of the genre.</param>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="Genre"/> or an error message.
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="Genre"/>, or an error message.
/// </returns>
public static ErrorOr<Genre> Create(string name)
{
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Enums;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using System.Diagnostics;
@@ -38,8 +37,6 @@ public class LanguageInfo : ValueObject
/// <param name="languageCode">The ISO 639-1 two-letter language code.</param>
/// <param name="languageName">The full name of the language in English.</param>
/// <param name="nativeName">The optional native name of the language.</param>
/// <exception cref="ArgumentNullException">Thrown if languageCode or languageName is null.</exception>
/// <exception cref="ArgumentException">Thrown if languageCode is not a valid ISO 639-1 code.</exception>
private LanguageInfo(string languageCode, string languageName, Optional<string> nativeName)
{
LanguageCode = languageCode.ToLowerInvariant();
@@ -56,7 +53,7 @@ public class LanguageInfo : ValueObject
/// <param name="languageName">The full name of the language in English.</param>
/// <param name="nativeName">The optional native name of the language.</param>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="LanguageInfo"/> or an error message.
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="LanguageInfo"/>, or an error message.
/// </returns>
public static ErrorOr<LanguageInfo> Create(string languageCode, string languageName, Optional<string> nativeName)
{
@@ -1,6 +1,4 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Enums;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using System.Diagnostics;
@@ -12,28 +10,23 @@ namespace Lumina.Domain.Common.ValueObjects.Metadata;
/// Value Object for the rating of a media element.
/// </summary>
[DebuggerDisplay("{Value}/{MaxValue}")]
public class Rating : ValueObject
public abstract class Rating : ValueObject
{
#region ==================================================================== PROPERTIES =================================================================================
/// <summary>
/// Gets the numeric value of the rating.
/// </summary>
public decimal Value { get; }
public decimal Value { get; private set; }
/// <summary>
/// Gets the maximum possible rating value.
/// </summary>
public decimal MaxValue { get; }
/// <summary>
/// Gets the optional source of the rating (e.g., "IMDB", "Rotten Tomatoes").
/// </summary>
public Optional<VideoRatingSource> Source { get; }
public decimal MaxValue { get; private set; }
/// <summary>
/// Gets the optional number of votes or reviews this rating is based on.
/// </summary>
public Optional<int> VoteCount { get; }
public Optional<int> VoteCount { get; private set; }
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -42,37 +35,16 @@ public class Rating : ValueObject
/// </summary>
/// <param name="value">The numeric value of the rating.</param>
/// <param name="maxValue">The maximum possible rating value.</param>
/// <param name="source">The optional source of the rating.</param>
/// <param name="voteCount">The optional number of votes or reviews.</param>
private Rating(decimal value, decimal maxValue, Optional<VideoRatingSource> source, Optional<int> voteCount)
protected Rating(decimal value, decimal maxValue, Optional<int> voteCount)
{
Value = value;
MaxValue = maxValue;
Source = source;
VoteCount = voteCount;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a new instance of the <see cref="Rating"/> class.
/// </summary>
/// <param name="value">The numeric value of the rating.</param>
/// <param name="maxValue">The maximum possible rating value.</param>
/// <param name="source">The optional source of the rating.</param>
/// <param name="voteCount">The optional number of votes or reviews.</param>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="Rating"/> or an error message.
/// </returns>
public static ErrorOr<Rating> Create(decimal value, decimal maxValue, Optional<VideoRatingSource> source, Optional<int> voteCount)
{
if (maxValue < 0 || value < 0)
return Errors.Errors.Metadata.RatingMustBePositive;
if (value > maxValue)
return Errors.Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue;
return new Rating(value, maxValue, source, voteCount);
}
/// <summary>
/// Returns the rating as a percentage.
/// </summary>
@@ -81,28 +53,5 @@ public class Rating : ValueObject
{
return (Value / MaxValue) * 100;
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
yield return MaxValue;
yield return Source;
yield return VoteCount;
}
/// <summary>
/// Customized ToString() method.
/// </summary>
/// <returns>Custom string value showing relevant data for current class.</returns>
public override string ToString()
{
string baseString = $"{Value}/{MaxValue}";
if (Source.HasValue)
baseString += $" ({Source.Value})";
if (VoteCount.HasValue)
baseString += $" [{VoteCount.Value} votes]";
return baseString;
}
#endregion
}
@@ -84,7 +84,7 @@ public class ReleaseInfo : ValueObject
/// <param name="releaseCountry">The optional country or region of release.</param>
/// <param name="releaseVersion">The optional release version or edition.</param>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="ReleaseInfo"/> or an error message.
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="ReleaseInfo"/>, or an error message.
/// </returns>
public static ErrorOr<ReleaseInfo> Create(
Optional<DateOnly> originalReleaseDate,
@@ -36,7 +36,7 @@ public class Tag : ValueObject
/// </summary>
/// <param name="name">The value of the tag.</param>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="Tag"/> or an error message.
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="Tag"/>, or an error message.
/// </returns>
public static ErrorOr<Tag> Create(string name)
{
@@ -54,7 +54,7 @@ public class AudioMetadata : BaseMetadata
/// <param name="durationInSeconds">The duration of the audio, in seconds.</param>
/// <param name="sampleRate">The sample rate of the audio, in Hz.</param>
/// <param name="channels">The number of audio channels.</param>
/// <param name="release">The release information of the audio.</param>
/// <param name="releaseInfo">The release information of the audio.</param>
/// <param name="description">The description of the audio.</param>
/// <param name="language">The language of the audio.</param>
/// <param name="originalLanguage">The optional original language of the video.</param>
@@ -68,7 +68,7 @@ public class AudioMetadata : BaseMetadata
int durationInSeconds,
int sampleRate,
int channels,
ReleaseInfo release,
ReleaseInfo releaseInfo,
Optional<string> description,
List<Genre> genres,
List<Tag> tags,
@@ -77,7 +77,7 @@ public class AudioMetadata : BaseMetadata
Optional<int> bitDepth,
Optional<string> audioCodec,
Optional<int> bitrate)
: base(title, originalTitle, release, description, genres, tags, language, originalLanguage)
: base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage)
{
DurationInSeconds = durationInSeconds;
SampleRate = sampleRate;
@@ -106,7 +106,7 @@ public class AudioMetadata : BaseMetadata
/// <param name="genres">The genres of the audio.</param>
/// <param name="tags">The tags associated with the audio.</param>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="AudioMetadata"/> or an error message.
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="AudioMetadata"/>, or an error message.
/// </returns>
public static ErrorOr<AudioMetadata> Create(
string title,
@@ -68,7 +68,7 @@ public class FileInfo : ValueObject
/// <param name="lastModified">The date and time when the file was last modified.</param>
/// <param name="mimeType">The MIME type of the file, if available.</param>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="FileInfo"/> or an error message.
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="FileInfo"/>, or an error message.
/// </returns>
public static ErrorOr<FileInfo> Create(string path, string fileExtension, long sizeInBytes, DateTime lastModified, Optional<string> mimeType)
{
@@ -100,7 +100,7 @@ public class StreamInfo : ValueObject
/// <param name="sampleRate">The sample rate of the stream (for audio).</param>
/// <param name="channels">The number of channels (for audio).</param>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="StreamInfo"/> or an error message.
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="StreamInfo"/>, or an error message.
/// </returns>
public static ErrorOr<StreamInfo> Create(
string streamId,
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using Lumina.Domain.Common.Models.Core;
#endregion
namespace Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects;
/// <summary>
/// Value Object for the role of a media contributor.
/// </summary>
[DebuggerDisplay("{DisplayName}")]
public sealed class MediaContributorRole : ValueObject
{
#region ==================================================================== PROPERTIES =================================================================================
/// <summary>
/// Gets the value representing this object.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the category of this object.
/// </summary>
public string Category { get; }
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="MediaContributorRole"/> class.
/// </summary>
/// <param name="name">The value representing this object.</param>
/// <param name="category">The category of this object.</param>
private MediaContributorRole(string name, string category)
{
Name = name;
Category = category;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a new instance of the <see cref="MediaContributorRole"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="name">The value representing this object.</param>
/// <param name="category">The category of this object.</param>
/// <returns>The created <see cref="MediaContributorRole"/> instance.</returns>
public static MediaContributorRole Create(string name, string category)
{
// TODO: enforce invariants
return new MediaContributorRole(name, category);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Name;
yield return Category;
}
#endregion
}
@@ -48,7 +48,7 @@ public class VideoMetadata : BaseMetadata
/// <param name="originalTitle">The optional original title of the video.</param>
/// <param name="durationInSeconds">The duration of the video, in seconds.</param>
/// <param name="resolution">The resolution of the video.</param>
/// <param name="release">The release information of the video.</param>
/// <param name="releaseInfo">The release information of the video.</param>
/// <param name="description">The optional description of the video.</param>
/// <param name="language">The language of the video.</param>
/// <param name="originalLanguage">The optional original language of the video.</param>
@@ -62,8 +62,8 @@ public class VideoMetadata : BaseMetadata
Optional<string> originalTitle,
int durationInSeconds,
string resolution,
ReleaseInfo release,
Optional<string> description,
ReleaseInfo releaseInfo,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<float> frameRate,
@@ -71,7 +71,7 @@ public class VideoMetadata : BaseMetadata
Optional<string> audioCodec,
List<Genre> genres,
List<Tag> tags)
: base(title, originalTitle, release, description, genres, tags, language, originalLanguage)
: base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage)
{
DurationInSeconds = durationInSeconds;
Resolution = resolution ?? throw new ArgumentNullException(nameof(resolution));
@@ -89,8 +89,8 @@ public class VideoMetadata : BaseMetadata
/// <param name="originalTitle">The optional original title of the video.</param>
/// <param name="durationInSeconds">The duration of the video in seconds.</param>
/// <param name="resolution">The resolution of the video.</param>
/// <param name="release">The release information of the video.</param>
/// <param name="description">The optional description of the video.</param>
/// <param name="releaseInfo">The release information of the video.</param>
/// <param name="language">The language of the video.</param>
/// <param name="originalLanguage">The optional original language of the video.</param>
/// <param name="frameRate">The optional frame rate of the video.</param>
@@ -100,15 +100,15 @@ public class VideoMetadata : BaseMetadata
/// <param name="tags">The tags associated with the video.</param>
/// <param name="contributors">The list of contributors for this video.</param>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="VideoMetadata"/> or an error message.
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="VideoMetadata"/>, or an error message.
/// </returns>
public static ErrorOr<VideoMetadata> Create(
string title,
Optional<string> originalTitle,
int durationInSeconds,
string resolution,
ReleaseInfo release,
Optional<string> description,
ReleaseInfo releaseInfo,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<float> frameRate,
@@ -117,7 +117,7 @@ public class VideoMetadata : BaseMetadata
List<Genre> genres,
List<Tag> tags)
{
return new VideoMetadata(title, originalTitle, durationInSeconds, resolution, release, description,
return new VideoMetadata(title, originalTitle, durationInSeconds, resolution, description, releaseInfo,
language, originalLanguage, frameRate, videoCodec, audioCodec, genres, tags);
}
@@ -223,7 +223,9 @@ public sealed class Book : AggregateRoot<BookId, Guid>
/// <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>
/// <returns>The created <see cref="Book"/>.</returns>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="Book"/>, or an error message.
/// </returns>
public static ErrorOr<Book> Create(
WrittenContentMetadata metadata,
BookFormat format,
@@ -289,7 +291,9 @@ public sealed class Book : AggregateRoot<BookId, Guid>
/// <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>
/// <returns>The created <see cref="Book"/>.</returns>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="Book"/>, or an error message.
/// </returns>
public static ErrorOr<Book> Create(
BookId id,
WrittenContentMetadata metadata,
@@ -43,8 +43,10 @@ public sealed class BookSeries : Entity<BookSeriesId>
/// Initializes a new instance of the <see cref="BookSeries"/> class.
/// </summary>
/// <param name="id">The identifier of the book series.</param>
/// <param name="title">The title of the book series.</param>
public BookSeries(BookSeriesId id, WrittenContentMetadata metadata, bool isComplete, List<Book> books)
/// <param name="metadata">The metadata of the book series.</param>
/// <param name="isComplete">The current status of the book series.</param>
/// <param name="books">The books of the book series.</param>
private BookSeries(BookSeriesId id, WrittenContentMetadata metadata, bool isComplete, List<Book> books)
: base(id)
{
Id = id;
@@ -56,6 +58,53 @@ public sealed class BookSeries : Entity<BookSeriesId>
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a new instance of the <see cref="BookSeries"/> class.
/// </summary>
/// <param name="id">The identifier of the book series.</param>
/// <param name="metadata">The metadata of the book series.</param>
/// <param name="isComplete">The current status of the book series.</param>
/// <param name="books">The books of the book series.</param>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="BookSeries"/>, or an error message.
/// </returns>
public static ErrorOr<BookSeries> Create(
BookSeriesId id,
WrittenContentMetadata metadata,
bool isComplete,
List<Book> books)
{
// TODO: enforce invariants
return new BookSeries(
id,
metadata,
isComplete,
books
);
}
/// <summary>
/// Creates a new instance of the <see cref="BookSeries"/> class.
/// </summary>
/// <param name="metadata">The metadata of the book series.</param>
/// <param name="isComplete">The current status of the book series.</param>
/// <param name="books">The books of the book series.</param>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="BookSeries"/>, or an error message.
/// </returns>
public static ErrorOr<BookSeries> Create(
WrittenContentMetadata metadata,
bool isComplete,
List<Book> books)
{
// TODO: enforce invariants
return new BookSeries(
BookSeriesId.CreateUnique(),
metadata,
isComplete,
books
);
}
/// <summary>
/// Adds a book to the series.
/// </summary>
/// <param name="book">The book to be added.</param>
@@ -34,7 +34,6 @@ public sealed class BookId : AggregateRootId<Guid>
/// <returns>The created <see cref="BookId"/> instance.</returns>
public static BookId CreateUnique()
{
// TODO: enforce invariants
return new BookId(Guid.NewGuid());
}
@@ -45,7 +44,6 @@ public sealed class BookId : AggregateRootId<Guid>
/// <returns>The created <see cref="BookId"/> instance.</returns>
public static BookId Create(Guid value)
{
// TODO: enforce invariants
return new BookId(value);
}
@@ -0,0 +1,83 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using ErrorOr;
using Lumina.Domain.Common.Enums;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Common.Errors;
#endregion
namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the rating of a media element.
/// </summary>
[DebuggerDisplay("{Value}/{MaxValue}")]
public class BookRating : Rating
{
#region ==================================================================== PROPERTIES =================================================================================
/// <summary>
/// Gets the optional source of the rating (e.g., "Goodreads", "Amazon").
/// </summary>
public Optional<BookRatingSource> Source { get; }
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="Rating"/> class.
/// </summary>
/// <param name="value">The numeric value of the rating.</param>
/// <param name="maxValue">The maximum possible rating value.</param>
/// <param name="source">The optional source of the rating.</param>
/// <param name="voteCount">The optional number of votes or reviews.</param>
private BookRating(decimal value, decimal maxValue, Optional<BookRatingSource> source, Optional<int> voteCount)
: base(value, maxValue, voteCount)
{
Source = source;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a new instance of the <see cref="Rating"/> class.
/// </summary>
/// <param name="value">The numeric value of the rating.</param>
/// <param name="maxValue">The maximum possible rating value.</param>
/// <param name="source">The optional source of the rating.</param>
/// <param name="voteCount">The optional number of votes or reviews.</param>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="Rating"/>, or an error message.
/// </returns>
public static ErrorOr<BookRating> Create(decimal value, decimal maxValue, Optional<BookRatingSource> source, Optional<int> voteCount)
{
if (maxValue < 0 || value < 0)
return Errors.Metadata.RatingMustBePositive;
if (value > maxValue)
return Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue;
return new BookRating(value, maxValue, source, voteCount);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
yield return MaxValue;
yield return Source;
yield return VoteCount;
}
/// <summary>
/// Customized ToString() method.
/// </summary>
/// <returns>Custom string value showing relevant data for current class.</returns>
public override string ToString()
{
string baseString = $"{Value}/{MaxValue}";
if (Source.HasValue)
baseString += $" ({Source.Value})";
if (VoteCount.HasValue)
baseString += $" [{VoteCount.Value} votes]";
return baseString;
}
#endregion
}
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Models.Core;
#endregion
@@ -30,9 +29,8 @@ public sealed class BookSeriesId : ValueObject
/// Creates a new instance of the <see cref="BookSeriesId"/> class.
/// </summary>
/// <returns>The created <see cref="BookSeriesId"/> instance.</returns>
public static ErrorOr<BookSeriesId> CreateUnique()
public static BookSeriesId CreateUnique()
{
// TODO: enforce invariants
return new BookSeriesId(Guid.NewGuid());
}
@@ -41,9 +39,8 @@ public sealed class BookSeriesId : ValueObject
/// </summary>
/// <param name="value">The value used to create the <see cref="BookSeriesId"/> instance.</param>
/// <returns>The created <see cref="BookSeriesId"/> instance.</returns>
public static ErrorOr<BookSeriesId> Create(Guid value)
public static BookSeriesId Create(Guid value)
{
// TODO: enforce invariants
return new BookSeriesId(value);
}
@@ -30,26 +30,26 @@ public class WrittenContentMetadata : BaseMetadata
/// </summary>
/// <param name="title">The title of the written content.</param>
/// <param name="originalTitle">The optional original title of the video.</param>
/// <param name="release">The release information of the written content.</param>
/// <param name="description">The description of the written content.</param>
/// <param name="releaseInfo">The release information of the written content.</param>
/// <param name="genres">The genres of the written content.</param>
/// <param name="tags">The tags associated with the written content.</param>
/// <param name="language">The language of the written content.</param>
/// <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 WrittenContentMetadata(
private WrittenContentMetadata(
string title,
Optional<string> originalTitle,
ReleaseInfo release,
Optional<string> description,
ReleaseInfo releaseInfo,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<string> publisher,
Optional<int> pageCount)
: base(title, originalTitle, release, description, genres, tags, language, originalLanguage)
: base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage)
{
Publisher = publisher;
PageCount = pageCount;
@@ -57,6 +57,44 @@ public class WrittenContentMetadata : BaseMetadata
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a new instance of the <see cref="WrittenContentMetadata"/> class.
/// </summary>
/// <param name="title">The title of the written content.</param>
/// <param name="originalTitle">The optional original title of the video.</param>
/// <param name="description">The description of the written content.</param>
/// <param name="releaseInfo">The release information of the written content.</param>
/// <param name="genres">The genres of the written content.</param>
/// <param name="tags">The tags associated with the written content.</param>
/// <param name="language">The language of the written content.</param>
/// <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(
string title,
Optional<string> originalTitle,
Optional<string> description,
ReleaseInfo releaseInfo,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<string> publisher,
Optional<int> pageCount)
{
return new WrittenContentMetadata(
title,
originalTitle,
description,
releaseInfo,
genres, tags,
language,
originalLanguage,
publisher,
pageCount
);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
@@ -1,9 +1,5 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Lumina.Application\Lumina.Application.csproj" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
@@ -11,4 +7,8 @@
<BaseOutputPath>..\..\bin\</BaseOutputPath>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Lumina.Application\Lumina.Application.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Enums;
using Lumina.Application.Common.Models.Books;
using Lumina.Application.Common.Models.Contributors;
#endregion
namespace Lumina.Presentation.Api.Common.Contracts.Books;
/// <summary>
/// Represents a request to add a book.
/// </summary>
public record AddBookRequest(
WrittenContentMetadataDto Metadata,
BookFormat Format,
string? Edition,
int? VolumeNumber,
BookSeriesDto? Series,
string? ASIN,
string? GoodreadsId,
string? LCCN,
string? OCLCNumber,
string? OpenLibraryId,
string? LibraryThingId,
string? GoogleBooksId,
string? BarnesAndNobleId,
string? KoboId,
string? AppleBooksId,
List<IsbnDto> ISBNs,
List<MediaContributorDto> Contributors,
List<BookRatingDto> Ratings
);
@@ -1,6 +1,10 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
using Lumina.Application.Common.Converters;
using Lumina.Presentation.Api.Common.Configuration;
using Lumina.Presentation.Api.Common.Errors;
using Mapster;
using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
#endregion
@@ -21,7 +25,11 @@ public static class PresentationApiLayerServices
public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services)
{
// add services to the container
services.AddControllers();
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
options.JsonSerializerOptions.Converters.Add(new OptionalJsonConverterFactory());
});
// add services to the container.
services.AddEndpointsApiExplorer();
@@ -43,6 +51,12 @@ public static class PresentationApiLayerServices
services.AddSingleton<ProblemDetailsFactory, CustomProblemDetailsFactory>();
// register mapster configs
var mapsterConfig = TypeAdapterConfig.GlobalSettings;
mapsterConfig.Scan(typeof(PresentationApiLayerServices).Assembly);
services.AddSingleton(mapsterConfig);
services.AddScoped<IMapper, ServiceMapper>();
return services;
}
#endregion
@@ -1,11 +1,7 @@
#region ========================================================================= USING =====================================================================================
using System;
using ErrorOr;
using System.Linq;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.Extensions.Options;
using Lumina.Presentation.Api.Common.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands;
using Lumina.Presentation.Api.Common.Contracts.Books;
using Mapster;
#endregion
namespace Lumina.Presentation.Api.Common.Mapping;
/// <summary>
/// Mapping configuration for books.
/// </summary>
public class BookMappingConfig : IRegister
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Registers the mapping configuration.
/// </summary>
/// <param name="config">The type adapter configuration.</param>
public void Register(TypeAdapterConfig config)
{
config.NewConfig<AddBookRequest, AddBookCommand>()
.Map(dest => dest.ASIN, src => src.ASIN)
.Map(dest => dest.ISBNs, src => src.ISBNs)
.Map(dest => dest.LCCN, src => src.LCCN)
.Map(dest => dest.OCLCNumber, src => src.OCLCNumber)
.MapToConstructor(true);
}
#endregion
}
@@ -1,6 +1,8 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands;
using Lumina.Presentation.Api.Common.Contracts.Books;
using Lumina.Presentation.Api.Controllers.Common;
using MapsterMapper;
using Mediator;
using Microsoft.AspNetCore.Mvc;
#endregion
@@ -15,7 +17,8 @@ namespace Lumina.Presentation.Api.Controllers.Books;
public class BooksController : ApiController
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly ISender mediator;
private readonly ISender _mediator;
private readonly IMapper _mapper;
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -23,17 +26,18 @@ public class BooksController : ApiController
/// Initializes a new instance of the <see cref="BooksController"/> class.
/// </summary>
/// <param name="mediator">Injecting service for mediating commands and queries.</param>
public BooksController(ISender mediator)
/// <param name="mapper">Injected service for mapping objects.</param>
public BooksController(ISender mediator, IMapper mapper)
{
this.mediator = mediator;
_mediator = mediator;
_mapper = mapper;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Gets all books.
/// Controller action for getting the list of all books.
/// </summary>
/// <returns>An <see cref="ErrorOr{T}"/> containing either a collection of books, or an error.</returns>
[HttpGet()]
public async Task<IActionResult> GetBooks()
{
@@ -42,15 +46,15 @@ public class BooksController : ApiController
return Ok(new List<string> { "Book 1", "Book 2", "Book 3" });
}
// /// <summary>
// /// Adds a book.
// /// </summary>
// /// <param name="command"></param>
// /// <returns>The result of the HTTP request.</returns>
// public async Task<IActionResult> AddBook(AddBookCommand command)
// {
// ErrorOr<Unit> result = await mediator.Send(command);
// return result.Match(result => Ok(result), errors => Problem(errors));
// }
/// <summary>
/// Controller action for adding a book.
/// </summary>
/// <param name="command">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));
}
#endregion
}
@@ -8,10 +8,12 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Mapster" Version="7.4.0" />
<PackageReference Include="Mapster.DependencyInjection" Version="1.0.1" />
<PackageReference Include="Mediator.Abstractions" Version="2.1.7" />
<PackageReference Include="Mediator.SourceGenerator" Version="2.1.7">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
<PackageReference Include="Mediator.SourceGenerator" Version="2.1.7">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="5.1.0" />