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

Feature add crud operations for products #255

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 3 additions & 3 deletions IGroceryStore.sln.DotSettings.user
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
<PhysicalFolder Path="/Users/adrianfranczak/.nuget/packages/opentelemetry.instrumentation.http/1.0.0-rc9.5" Loaded="True" />
<PhysicalFolder Path="/Users/adrianfranczak/.nuget/packages/opentelemetry.instrumentation.http/1.0.0-rc9.6" Loaded="True" />
&lt;/AssemblyExplorer&gt;</s:String>
<s:String x:Key="/Default/Environment/Highlighting/HighlightingSourceSnapshotLocation/@EntryValue">/Users/adrianfranczak/Library/Caches/JetBrains/Rider2022.2/resharper-host/temp/Rider/vAny/CoverageData/_IGroceryStore.1213299661/Snapshot/snapshot.utdcvr</s:String>


<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=bb40838d_002De9ff_002D4741_002Da625_002D9ff5d7dda92b/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" IsActive="True" Name="All tests from &amp;lt;tests&amp;gt;" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;
&lt;Project Location="/Users/adrianfranczak/Repos/Private/IGroceryStore" Presentation="&amp;lt;tests&amp;gt;" /&gt;

<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=bb40838d_002De9ff_002D4741_002Da625_002D9ff5d7dda92b/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" IsActive="True" Name="All tests from &amp;lt;tests&amp;gt;" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;&#xD;
&lt;Project Location="\Users\adrianfranczak\Repos\Private\IGroceryStore" Presentation="&amp;lt;tests&amp;gt;" /&gt;&#xD;
&lt;/SessionState&gt;</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Respawner/@EntryIndexedValue">True</s:Boolean>

Expand Down
2 changes: 1 addition & 1 deletion src/API/Middlewares/ExceptionMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,4 @@ public async Task InvokeAsync(HttpContext context, RequestDelegate next)
}
private static string ToUnderscoreCase(string value)
=> string.Concat(value.Select((x, i) => i > 0 && char.IsUpper(x) && !char.IsUpper(value[i-1]) ? $"_{x}" : x.ToString())).ToLower();
}
}
8 changes: 4 additions & 4 deletions src/API/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@
}

//AWS
if (!builder.Environment.IsDevelopment() && !builder.Environment.IsTestEnvironment())
{
builder.Configuration.AddSystemsManager("/Production/IGroceryStore", TimeSpan.FromSeconds(30));
}
// if (!builder.Environment.IsDevelopment() && !builder.Environment.IsTestEnvironment())
// {
// builder.Configuration.AddSystemsManager("/Production/IGroceryStore", TimeSpan.FromSeconds(30));
// }

//DateTime
builder.Services.AddSingleton<DateTimeService>();
Expand Down
2 changes: 1 addition & 1 deletion src/API/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"profiles": {
"Postman": {
"commandName": "Project",
"launchBrowser": false,
"launchBrowser": true,
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
Expand Down
2 changes: 1 addition & 1 deletion src/API/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
]
},
"ElasticConfiguration": {
"Uri": "foo"
"Uri": "http://localhost:9200"
},
"Postgres": {
"ConnectionString": "foo",
Expand Down
4 changes: 4 additions & 0 deletions src/Baskets/Baskets.Core/Baskets.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,8 @@
<PackageReference Include="MongoDB.Driver" Version="2.18.0" />
</ItemGroup>

<ItemGroup>
<Folder Include="Persistence" />
</ItemGroup>

</Project>
3 changes: 3 additions & 0 deletions src/Products/Products.Contracts/Events/ProductUpdated.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace IGroceryStore.Products.Contracts.Events;

public record class ProductUpdated(ulong Id, string Name);
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class UpdateCategoryEndpoint : IEndpoint
{
public void RegisterEndpoint(IEndpointRouteBuilder endpoints) =>
endpoints.MapPut<UpdateCategory>("api/categories/{id}")
.AddEndpointFilter<ValidationFilter<UpdateCategory.UpdateCategoryBody>>()
.AddEndpointFilter<ValidationFilter<UpdateCategory>>()
.WithTags(SwaggerTags.Products)
.Produces(202)
.Produces(400);
Expand Down Expand Up @@ -55,11 +55,11 @@ await _productsDbContext.Categories
}
}

internal class UpdateCategoryValidator : AbstractValidator<UpdateCategory.UpdateCategoryBody>
internal class UpdateCategoryValidator : AbstractValidator<UpdateCategory>
{
public UpdateCategoryValidator()
{
RuleFor(x => x.Name)
RuleFor(x => x.Body.Name)
.MinimumLength(3)
.NotEmpty();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
using IGroceryStore.Shared.Services;
using IGroceryStore.Shared.Validation;
using MassTransit;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
Expand All @@ -32,9 +31,11 @@ public class CreateProductEndpoint : IEndpoint
{
public void RegisterEndpoint(IEndpointRouteBuilder endpoints) =>
endpoints.MapPost<CreateProduct>("api/products")
.RequireAuthorization()
.AddEndpointFilter<ValidationFilter<CreateProduct.CreateProductBody>>()
.WithTags(SwaggerTags.Products);
//.RequireAuthorization()
.AddEndpointFilter<ValidationFilter<CreateProduct>>()
.WithTags(SwaggerTags.Products)
.Produces(400)
.Produces(202);
}

internal class CreateProductHandler : ICommandHandler<CreateProduct, IResult>
Expand Down Expand Up @@ -81,32 +82,32 @@ public async Task<IResult> HandleAsync(CreateProduct command, CancellationToken
}
}

internal class CreateProductValidator : AbstractValidator<CreateProduct.CreateProductBody>
internal class CreateProductValidator : AbstractValidator<CreateProduct>
{
public CreateProductValidator()
{
RuleFor(x => x.Name)
RuleFor(x => x.Body.Name)
.NotEmpty()
.MinimumLength(3);

RuleFor(x => x.Quantity)
RuleFor(x => x.Body.Quantity)
.NotNull()
.DependentRules(() =>
{
RuleFor(x => x.Quantity.Amount)
RuleFor(x => x.Body.Quantity.Amount)
.GreaterThan(0);

RuleFor(x => x.Quantity.Unit)
RuleFor(x => x.Body.Quantity.Unit)
.NotEmpty();
});

RuleFor(x => x.BrandId)
RuleFor(x => x.Body.BrandId)
.NotEmpty();

RuleFor(x => x.CountryId)
RuleFor(x => x.Body.CountryId)
.NotEmpty();

RuleFor(x => x.CategoryId)
RuleFor(x => x.Body.CategoryId)
.NotEmpty();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using IGroceryStore.Products.Exceptions;
using IGroceryStore.Products.Persistence.Contexts;
using IGroceryStore.Shared.Abstraction.Commands;
using IGroceryStore.Shared.Abstraction.Common;
using IGroceryStore.Shared.Abstraction.Constants;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;

namespace IGroceryStore.Products.Core.Features.Products.Commands;

internal record DeleteProduct(ulong Id) : IHttpCommand;

public class DeleteProductEndpoint : IEndpoint
{
public void RegisterEndpoint(IEndpointRouteBuilder endpoints) =>
endpoints.MapDelete<DeleteProduct>("api/products/{id}")
//.RequireAuthorization()
.WithTags(SwaggerTags.Products)
.Produces(204)
.Produces(400);

}

internal class DeleteProductHandler : ICommandHandler<DeleteProduct, IResult>
{
private readonly ProductsDbContext _productsDbContext;

public DeleteProductHandler(ProductsDbContext productsDbContext)
{
_productsDbContext = productsDbContext;
}

public async Task<IResult> HandleAsync(DeleteProduct command, CancellationToken cancellationToken = default)
{
var products = await _productsDbContext.Products.ToListAsync();

var product =
await _productsDbContext.Products.FirstOrDefaultAsync(x => x.Id.Equals(command.Id), cancellationToken);

if (product is null) throw new ProductNotFoundException(command.Id);

_productsDbContext.Products.Remove(product);
await _productsDbContext.SaveChangesAsync(cancellationToken);

return Results.NoContent();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,58 @@
namespace IGroceryStore.Products.Features.Products.Commands;
using IGroceryStore.Products.Contracts.Events;
using IGroceryStore.Products.Exceptions;
using IGroceryStore.Products.Persistence.Contexts;
using IGroceryStore.Shared.Abstraction.Commands;
using IGroceryStore.Shared.Abstraction.Common;
using IGroceryStore.Shared.Abstraction.Constants;
using MassTransit;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;

internal class UpdateDetails
namespace IGroceryStore.Products.Features.Products.Commands;

internal record UpdateDetails(UpdateDetails.UpdateDetailsBody DetailsBody, ulong Id) : IHttpCommand
{
internal record UpdateDetailsBody(string Name,
string Description
);
}

public class UpdateDetailsEndpoint : IEndpoint
{
public void RegisterEndpoint(IEndpointRouteBuilder endpoints)
=> endpoints.MapPut<UpdateDetails>("api/products")
.WithTags(SwaggerTags.Products)
.Produces(204)
.Produces(400);
}

internal class UpdateDetailsHandler : ICommandHandler<UpdateDetails, IResult>
{
private readonly ProductsDbContext _context;
private readonly IBus _bus;

public UpdateDetailsHandler(ProductsDbContext context, IBus bus)
{
_context = context;
_bus = bus;
}

public async Task<IResult> HandleAsync(UpdateDetails command, CancellationToken cancellationToken = default)
{
var product = await _context.Products.FirstOrDefaultAsync(x => x.Id.Equals(command.Id), cancellationToken);

if (product is null) throw new ProductNotFoundException(command.Id);

var (name, description) = command.DetailsBody;

product.Name = name;
product.Description = description;
_context.Update(product);
await _context.SaveChangesAsync(cancellationToken);

await _bus.Publish(new ProductUpdated(command.Id, name), cancellationToken);

return Results.NoContent();
}
}
16 changes: 10 additions & 6 deletions src/Products/Products.Core/Products.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,22 @@
</PropertyGroup>

<ItemGroup>
<InternalsVisibleTo Include="$(AssemblyName).UnitTests"/>
<InternalsVisibleTo Include="$(AssemblyName).IntegrationTests"/>
<InternalsVisibleTo Include="$(AssemblyName).UnitTests" />
<InternalsVisibleTo Include="$(AssemblyName).IntegrationTests" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\Shared\Shared\Shared.csproj"/>
<ProjectReference Include="..\Products.Contracts\Products.Contracts.csproj"/>
<ProjectReference Include="..\..\Shared\Shared\Shared.csproj" />
<ProjectReference Include="..\Products.Contracts\Products.Contracts.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="7.0.0-rc.2.22476.2"/>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.0-rc.2"/>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="7.0.0-rc.2.22476.2" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.0-rc.2" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="Products.IntegrationTests" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion src/Products/Products.Core/modulesettings.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"Products": {
"ModuleEnabled": false
"ModuleEnabled": true
}
}
20 changes: 10 additions & 10 deletions src/Users/Users.Core/Users.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,22 @@
</PropertyGroup>

<ItemGroup>
<InternalsVisibleTo Include="$(AssemblyName).UnitTests"/>
<InternalsVisibleTo Include="$(AssemblyName).IntegrationTests"/>
<InternalsVisibleTo Include="$(AssemblyName).UnitTests" />
<InternalsVisibleTo Include="$(AssemblyName).IntegrationTests" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Users.Contracts\Users.Contracts.csproj"/>
<ProjectReference Include="..\..\Shared\Shared\Shared.csproj"/>
<ProjectReference Include="..\Users.Contracts\Users.Contracts.csproj" />
<ProjectReference Include="..\..\Shared\Shared\Shared.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.0-rc.2.22476.2"/>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.0-rc.2.22472.11"/>
<PackageReference Include="JWT" Version="10.0.0-beta9"/>
<PackageReference Include="JWT.Extensions.AspNetCore" Version="10.0.0-beta4"/>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3"/>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.0-rc.2"/>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.0-rc.2.22476.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.0-rc.2.22472.11" />
<PackageReference Include="JWT" Version="10.0.0-beta9" />
<PackageReference Include="JWT.Extensions.AspNetCore" Version="10.0.0-beta4" />
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.0-rc.2" />
</ItemGroup>

</Project>
24 changes: 24 additions & 0 deletions tests/Products/Products.IntegrationTests/DbConfigExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using DotNet.Testcontainers.Containers;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Products.IntegrationTests;

public static class DbConfigExtensions
{
public static void CleanDbContextOptions<T>(this IServiceCollection services)
where T : DbContext
{
var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<T>));
if (descriptor != null) services.Remove(descriptor);
services.RemoveAll(typeof(T));
}

public static void AddPostgresContext<T>(this IServiceCollection services, TestcontainerDatabase dbContainer)
where T : DbContext
{
services.AddDbContext<T>(ctx =>
ctx.UseNpgsql(dbContainer.ConnectionString));
}
}