Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#21 Catalog - Attach Tags to Products #25

Merged
merged 1 commit into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions backend/src/Catalog.Application/Catalog.Application.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\Catalog.Domain\Catalog.Domain.csproj" />
<ProjectReference Include="..\Common.Application\Common.Application.csproj" />
<ProjectReference Include="..\Catalog.Domain\Catalog.Domain.csproj"/>
<ProjectReference Include="..\Common.Application\Common.Application.csproj"/>
</ItemGroup>

<ItemGroup>
<PackageReference Include="FluentValidation" Version="11.10.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.10.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.8" />
<PackageReference Include="FluentValidation" Version="11.10.0"/>
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.10.0"/>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.8"/>
</ItemGroup>

</Project>
14 changes: 11 additions & 3 deletions backend/src/Catalog.Application/Products/Commands/AddProduct.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Catalog.Domain.Products.Entities;
using Catalog.Domain.Products.Repositories;
using Catalog.Domain.Tags.Repositories;
using Common.Application.Commands;
using Common.Application.Models;
using FluentValidation;
Expand All @@ -8,13 +9,13 @@ namespace Catalog.Application.Products.Commands;

public static class AddProduct
{
public sealed record Command(Guid Id, string Name, string Description, decimal Price) : ICommand;
public sealed record Command(Guid Id, string Name, string Description, decimal Price, List<Guid> TagIds) : ICommand;

public sealed class Handler(IUnitOfWork unitOfWork, IProductRepository productRepository, IValidator<Command> validator) : ICommandHandler<Command>
public sealed class Handler(IUnitOfWork unitOfWork, IProductRepository productRepository, ITagRepository tagRepository, IValidator<Command> validator) : ICommandHandler<Command>
{
public async Task<Result> HandleAsync(Command command)
{
var (id, name, description, price) = command;
var (id, name, description, price, tagIds) = command;

var validationResult = await validator.ValidateAsync(command);
if (!validationResult.IsValid) return Result.Fail("add-product-validation");
Expand All @@ -27,6 +28,13 @@ public async Task<Result> HandleAsync(Command command)
Price = price
};

if (tagIds.Count > 0)
{
var tags = await tagRepository.GetTagsAsync(tagIds);
if (tagIds.Count != tags.Count) return Result.Fail("add-product-tags-count");
product.Tags.AddRange(tags);
}

await productRepository.AddAsync(product);
await unitOfWork.CommitAsync();

Expand Down
16 changes: 13 additions & 3 deletions backend/src/Catalog.Application/Products/Commands/EditProduct.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Catalog.Domain.Products.Repositories;
using Catalog.Domain.Tags.Repositories;
using Common.Application.Commands;
using Common.Application.Models;
using FluentValidation;
Expand All @@ -7,13 +8,13 @@ namespace Catalog.Application.Products.Commands;

public static class EditProduct
{
public sealed record Command(Guid Id, string Name, string Description, decimal Price) : ICommand;
public sealed record Command(Guid Id, string Name, string Description, decimal Price, List<Guid> TagIds) : ICommand;

public sealed class Handler(IUnitOfWork unitOfWork, IProductRepository productRepository, IValidator<Command> validator) : ICommandHandler<Command>
public sealed class Handler(IUnitOfWork unitOfWork, IProductRepository productRepository, ITagRepository tagRepository, IValidator<Command> validator) : ICommandHandler<Command>
{
public async Task<Result> HandleAsync(Command command)
{
var (id, name, description, price) = command;
var (id, name, description, price, tagIds) = command;

var validationResult = await validator.ValidateAsync(command);
if (!validationResult.IsValid) return Result.Fail("edit-product-validation");
Expand All @@ -24,6 +25,15 @@ public async Task<Result> HandleAsync(Command command)
product.Description = description;
product.Price = price;

product.Tags.Clear();

if (tagIds.Count > 0)
{
var tags = await tagRepository.GetTagsAsync(tagIds);
if (tagIds.Count != tags.Count) return Result.Fail("edit-product-tags-count");
product.Tags.AddRange(tags);
}

await unitOfWork.CommitAsync();

return Result.Ok();
Expand Down
26 changes: 26 additions & 0 deletions backend/src/Catalog.Application/Products/Queries/GetProduct.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using Catalog.Domain.Products.Entities;
using Common.Application.Queries;
using Microsoft.EntityFrameworkCore;

namespace Catalog.Application.Products.Queries;

public static class GetProduct
{
public sealed record Query(Guid Id) : IQuery<ProductDto?>;

public sealed record TagDto(Guid Id, string Name);

public sealed record ProductDto(Guid Id, string Name, string Description, decimal Price, IEnumerable<TagDto> Tags);

public sealed class Handler(IQueryProcessor queryProcessor) : IQueryHandler<Query, ProductDto?>
{
public Task<ProductDto?> HandleAsync(Query query)
{
return queryProcessor.Query<Product>()
.Include(p => p.Tags)
.Where(p => p.Id == query.Id)
.Select(p => new ProductDto(p.Id, p.Name, p.Description, p.Price, p.Tags.Select(t => new TagDto(t.Id, t.Name))))
.FirstOrDefaultAsync();
}
}
}
13 changes: 9 additions & 4 deletions backend/src/Catalog.Application/Tags/Queries/GetTags.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace Catalog.Application.Tags.Queries;

public static class GetTags
{
public sealed record Query(int PageIndex, int PageSize) : IQuery<Result>;
public sealed record Query(int? PageIndex, int? PageSize) : IQuery<Result>;

public sealed record Dto(Guid Id, string Name);

Expand All @@ -16,9 +16,14 @@ public sealed class Handler(IQueryProcessor queryProcessor) : IQueryHandler<Quer
{
public async Task<Result> HandleAsync(Query query)
{
var tags = await queryProcessor.Query<Tag>()
.Skip(query.PageIndex * query.PageSize)
.Take(query.PageSize)
var tagsQuery = queryProcessor.Query<Tag>();

if (query is { PageIndex: not null, PageSize: not null })
tagsQuery = tagsQuery
.Skip(query.PageIndex.Value * query.PageSize.Value)
.Take(query.PageSize.Value);

var tags = await tagsQuery
.OrderBy(t => t.Name)
.Select(t => new Dto(t.Id, t.Name))
.ToListAsync();
Expand Down
6 changes: 5 additions & 1 deletion backend/src/Catalog.Domain/Products/Entities/Product.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
namespace Catalog.Domain.Products.Entities;
using Catalog.Domain.Tags.Entities;

namespace Catalog.Domain.Products.Entities;

public sealed class Product
{
public required Guid Id { get; init; }
public required string Name { get; set; }
public required string Description { get; set; }
public required decimal Price { get; set; }

public List<Tag> Tags { get; } = [];
}
4 changes: 2 additions & 2 deletions backend/src/Common.Application/Common.Application.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentValidation" Version="11.10.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
<PackageReference Include="FluentValidation" Version="11.10.0"/>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1"/>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public static IServiceCollection AddHandlers(this IServiceCollection services, A
var handlerInterface = handler.GetInterfaces().Single(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICommandHandler<>));
services.AddTransient(handlerInterface, handler);
}

var queryHandlers = assembly.GetTypes()
.Where(type => type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IQueryHandler<,>)))
.ToList();
Expand Down
6 changes: 3 additions & 3 deletions backend/src/Common.Application/Models/Result.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ public struct Result

public static Result Ok()
{
return new Result();
return new();
}

public static Result Fail(string errorMessage)
{
return new Result
return new()
{
Error = new Error
Error = new()
{
Description = errorMessage
}
Expand Down
2 changes: 1 addition & 1 deletion backend/src/Common.Application/Queries/IQueryProcessor.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace Common.Application.Queries;

public interface IQueryProcessor
public interface IQueryProcessor
{
IQueryable<T> Query<T>() where T : class;
}
2 changes: 1 addition & 1 deletion backend/src/Host.WebApi/Extensions/ResultExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ internal static IResult ToHttp(this Result result)
return result.Error switch
{
null => Results.NoContent(),
_ => Results.Problem(result.Error.Description, statusCode: (int) HttpStatusCode.BadRequest)
_ => Results.Problem(result.Error.Description, statusCode: (int)HttpStatusCode.BadRequest)
};
}
}
8 changes: 4 additions & 4 deletions backend/src/Host.WebApi/Host.WebApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0"/>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Catalog.Application\Catalog.Application.csproj" />
<ProjectReference Include="..\Infrastructure.Data\Infrastructure.Data.csproj" />
<ProjectReference Include="..\Catalog.Application\Catalog.Application.csproj"/>
<ProjectReference Include="..\Infrastructure.Data\Infrastructure.Data.csproj"/>
</ItemGroup>

</Project>
8 changes: 8 additions & 0 deletions backend/src/Host.WebApi/Routes/ProductRoutes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ internal static void MapProductRoutes(this IEndpointRouteBuilder api)
.Produces<GetProducts.Result>()
.ProducesProblem(StatusCodes.Status500InternalServerError);

group.MapGet("{id:guid}", async ([FromServices] IQueryHandler<GetProduct.Query, GetProduct.ProductDto?> handler, [FromRoute] Guid id) =>
{
var result = await handler.HandleAsync(new(id));
return Results.Ok(result);
})
.Produces<GetProduct.ProductDto?>()
.ProducesProblem(StatusCodes.Status500InternalServerError);

group.MapPost("", async ([FromServices] ICommandHandler<AddProduct.Command> handler, [FromBody] AddProduct.Command command) =>
{
var result = await handler.HandleAsync(command);
Expand Down
2 changes: 1 addition & 1 deletion backend/src/Host.WebApi/Routes/TagRoutes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ internal static void MapTagRoutes(this IEndpointRouteBuilder api)
var group = api.MapGroup("tags")
.WithTags("Tags");

group.MapGet("", async ([FromServices] IQueryHandler<GetTags.Query, GetTags.Result> handler, [FromQuery] int pageIndex, [FromQuery] int pageSize) =>
group.MapGet("", async ([FromServices] IQueryHandler<GetTags.Query, GetTags.Result> handler, [FromQuery] int? pageIndex, [FromQuery] int? pageSize) =>
{
var result = await handler.HandleAsync(new(pageIndex, pageSize));
return Results.Ok(result);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,8 @@ public void Configure(EntityTypeBuilder<Product> builder)
builder.Property(x => x.Price)
.IsRequired()
.HasPrecision(18, 2);

builder.HasMany(p => p.Tags)
.WithMany();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static IServiceCollection AddInfrastructureData(this IServiceCollection s
services.AddDbContext<AppDbContext>(builder => builder.UseNpgsql(connectionString));
services.AddScoped<IUnitOfWork, EfUnitOfWork>();
services.AddTransient<IQueryProcessor, EfQueryProcessor>();

services.AddTransient<IProductRepository, EfProductRepository>();
services.AddTransient<ITagRepository, EfTagRepository>();

Expand Down
10 changes: 5 additions & 5 deletions backend/src/Infrastructure.Data/Infrastructure.Data.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="EFCore.NamingConventions" Version="8.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.8" />
<PackageReference Include="EFCore.NamingConventions" Version="8.0.3"/>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.8"/>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Catalog.Domain\Catalog.Domain.csproj" />
<ProjectReference Include="..\Common.Application\Common.Application.csproj" />
<ProjectReference Include="..\Catalog.Domain\Catalog.Domain.csproj"/>
<ProjectReference Include="..\Common.Application\Common.Application.csproj"/>
</ItemGroup>

<ItemGroup>
<Folder Include="Migrations\" />
<Folder Include="Migrations\"/>
</ItemGroup>

</Project>
Loading