Skip to content

Commit

Permalink
Merge pull request #10 from HammerheadShark666/run-vs-code-cleanup
Browse files Browse the repository at this point in the history
Run VS code cleanup
  • Loading branch information
HammerheadShark666 authored Aug 21, 2024
2 parents 9cd30e5 + 7fb757d commit 86c2766
Show file tree
Hide file tree
Showing 19 changed files with 58 additions and 61 deletions.
10 changes: 5 additions & 5 deletions Microservice.Customer.Api.Test.Unit/GetCustomerMediatrTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ namespace Microservice.Customer.Api.Test.Unit;
[TestFixture]
public class GetCustomerMediatrTests
{
private Mock<ICustomerRepository> customerRepositoryMock = new Mock<ICustomerRepository>();
private Mock<ICustomerHttpAccessor> customerHttpAccessorMock = new Mock<ICustomerHttpAccessor>();
private ServiceCollection services = new ServiceCollection();
private Mock<ICustomerRepository> customerRepositoryMock = new();
private Mock<ICustomerHttpAccessor> customerHttpAccessorMock = new();
private ServiceCollection services = new();
private ServiceProvider serviceProvider;
private IMediator mediator;

Expand Down Expand Up @@ -81,13 +81,13 @@ public void Get_customer_return_exception()
customerHttpAccessorMock.Setup(x => x.CustomerId)
.Returns(customerId);

var getCustomerRequest = new GetCustomerRequest(Guid.NewGuid());
var getCustomerRequest = new GetCustomerRequest(Guid.NewGuid());

var validationException = Assert.ThrowsAsync<NotFoundException>(async () =>
{
await mediator.Send(getCustomerRequest);
});

Assert.That(validationException.Message, Is.EqualTo("Customer not found."));
}
}
27 changes: 13 additions & 14 deletions Microservice.Customer.Api.Test.Unit/UpdateCustomerMediatrTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using MediatR;
using Microservice.Customer.Api.Data.Repository.Interfaces;
using Microservice.Customer.Api.Helpers;
using Microservice.Customer.Api.Helpers.Exceptions;
using Microservice.Customer.Api.Helpers.Interfaces;
using Microservice.Customer.Api.MediatR.AddCustomer;
using Microsoft.Extensions.DependencyInjection;
Expand All @@ -14,9 +13,9 @@ namespace Microservice.Customer.Api.Test.Unit;
[TestFixture]
public class UpdateCustomerMediatrTests
{
private Mock<ICustomerRepository> customerRepositoryMock = new Mock<ICustomerRepository>();
private Mock<ICustomerHttpAccessor> customerHttpAccessorMock = new Mock<ICustomerHttpAccessor>();
private ServiceCollection services = new ServiceCollection();
private Mock<ICustomerRepository> customerRepositoryMock = new();
private Mock<ICustomerHttpAccessor> customerHttpAccessorMock = new();
private ServiceCollection services = new();
private ServiceProvider serviceProvider;
private IMediator mediator;
private Guid customerId;
Expand All @@ -32,7 +31,7 @@ public void OneTimeSetup()
services.AddAutoMapper(Assembly.GetAssembly(typeof(UpdateCustomerMapper)));

serviceProvider = services.BuildServiceProvider();
mediator = serviceProvider.GetRequiredService<IMediator>();
mediator = serviceProvider.GetRequiredService<IMediator>();
}

[OneTimeTearDown]
Expand Down Expand Up @@ -75,7 +74,7 @@ public async Task Customer_updated_return_success_message()
customer.Email = "Changed Email";

customerRepositoryMock
.Setup(x => x.UpdateAsync(customer));
.Setup(x => x.UpdateAsync(customer));

var updateCustomerRequest = new UpdateCustomerRequest(customerId, "[email protected]", "TestSurname", "TestFirstName");

Expand All @@ -93,14 +92,14 @@ public void Customer_not_updated_id_does_not_exists_return_exception_fail_messag
.Returns(Task.FromResult(false));

var updateCustomerRequest = new UpdateCustomerRequest(customerId, "[email protected]", "TestSurname", "TestFirstName");

var validationException = Assert.ThrowsAsync<ValidationException>(async () =>
{
await mediator.Send(updateCustomerRequest);
});

Assert.That(validationException.Errors.Count, Is.EqualTo(1));
Assert.That(validationException.Errors.ElementAt(0).ErrorMessage, Is.EqualTo("The customer does not exists."));
Assert.That(validationException.Errors.ElementAt(0).ErrorMessage, Is.EqualTo("The customer does not exists."));
}

[Test]
Expand All @@ -116,9 +115,9 @@ public void Customer_not_updated_email_exists_return_exception_fail_message()
{
await mediator.Send(updateCustomerRequest);
});
Assert.That(validationException .Errors.Count, Is.EqualTo(1));
Assert.That(validationException.Errors.ElementAt(0).ErrorMessage, Is.EqualTo("Customer with this email already exists"));

Assert.That(validationException.Errors.Count, Is.EqualTo(1));
Assert.That(validationException.Errors.ElementAt(0).ErrorMessage, Is.EqualTo("Customer with this email already exists"));
}

[Test]
Expand Down Expand Up @@ -160,7 +159,7 @@ public void Customer_not_updated_invalid_surname_firstname_return_exception_fail

[Test]
public void Customer_not_updated_no_email_surname_firstname_return_exception_fail_message()
{
{
customerRepositoryMock
.Setup(x => x.ExistsAsync("[email protected]"))
.Returns(Task.FromResult(false));
Expand All @@ -175,10 +174,10 @@ public void Customer_not_updated_no_email_surname_firstname_return_exception_fai
Assert.That(validationException.Errors.Count, Is.EqualTo(7));
Assert.That(validationException.Errors.ElementAt(0).ErrorMessage, Is.EqualTo("Email is required."));
Assert.That(validationException.Errors.ElementAt(1).ErrorMessage, Is.EqualTo("Email length between 8 and 150."));
Assert.That(validationException.Errors.ElementAt(2).ErrorMessage, Is.EqualTo("Invalid Email."));
Assert.That(validationException.Errors.ElementAt(2).ErrorMessage, Is.EqualTo("Invalid Email."));
Assert.That(validationException.Errors.ElementAt(3).ErrorMessage, Is.EqualTo("Surname is required."));
Assert.That(validationException.Errors.ElementAt(4).ErrorMessage, Is.EqualTo("Surname length between 1 and 30."));
Assert.That(validationException.Errors.ElementAt(5).ErrorMessage, Is.EqualTo("First name is required."));
Assert.That(validationException.Errors.ElementAt(6).ErrorMessage, Is.EqualTo("First name length between 1 and 30."));
}
}
}
8 changes: 4 additions & 4 deletions Microservice.Customer.Api/Data/Context/CustomerDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
namespace Microservice.Customer.Api.Data.Contexts;

public class CustomerDbContext : DbContext
{
{
public CustomerDbContext(DbContextOptions<CustomerDbContext> options) : base(options) { }

public DbSet<Domain.Customer> Customer { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
base.OnModelCreating(modelBuilder);

modelBuilder.Entity<Domain.Customer>().HasData(DefaultData.GetCustomerDefaultData());
modelBuilder.Entity<Domain.Customer>().HasData(DefaultData.GetCustomerDefaultData());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
namespace Microservice.Customer.Api.Data.Repository;

public class CustomerRepository(IDbContextFactory<CustomerDbContext> dbContextFactory) : ICustomerRepository
{
{
public IDbContextFactory<CustomerDbContext> _dbContextFactory { get; set; } = dbContextFactory;

public async Task<Domain.Customer> AddAsync(Domain.Customer customer)
{
await using var db = await _dbContextFactory.CreateDbContextAsync();
await db.AddAsync(customer);
await db.SaveChangesAsync();
await db.SaveChangesAsync();

return customer;
}
Expand All @@ -21,8 +21,8 @@ public async Task UpdateAsync(Domain.Customer entity)
{
using var db = _dbContextFactory.CreateDbContext();
db.Customer.Update(entity);
await db.SaveChangesAsync();
}
await db.SaveChangesAsync();
}

public async Task<IEnumerable<Domain.Customer>> AllAsync()
{
Expand Down
2 changes: 1 addition & 1 deletion Microservice.Customer.Api/Domain/Customer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace Microservice.Customer.Api.Domain;
[Table("MSOS_Customer")]
public class Customer
{
[Key]
[Key]
public Guid Id { get; set; }

[MaxLength(30)]
Expand Down
4 changes: 2 additions & 2 deletions Microservice.Customer.Api/Endpoints/Endpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ public static void ConfigureRoutes(this WebApplication app, ConfigurationManager

customerGroup.MapPut("/update", [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
async ([FromBody] UpdateCustomerRequest updateCustomerRequest, [FromServices] IMediator mediator, ICustomerHttpAccessor customerHttpAccessor) =>
{
{
updateCustomerRequest = updateCustomerRequest with { Id = customerHttpAccessor.CustomerId };
var updateCustomerResponse = await mediator.Send(updateCustomerRequest);
var updateCustomerResponse = await mediator.Send(updateCustomerRequest);
return Results.Ok(updateCustomerResponse);
})
.Accepts<UpdateCustomerRequest>("application/json")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using Microservice.Customer.Api.Helpers;
using Microservice.Customer.Api.Helpers.Interfaces;
using Microservice.Customer.Api.Helpers.Swagger;
using Microservice.Customer.Api.MediatR.AddCustomer;
using Microservice.Customer.Api.MediatR.GetCustomer;
using Microservice.Customer.Api.Middleware;
using Microsoft.EntityFrameworkCore;
Expand All @@ -20,7 +19,7 @@
namespace Microservice.Customer.Api.Extensions;

public static class IServiceCollectionExtensions
{
{
public static void ConfigureExceptionHandling(this IServiceCollection services)
{
services.AddTransient<ExceptionHandlingMiddleware>();
Expand All @@ -35,10 +34,10 @@ public static void ConfigureDI(this IServiceCollection services)
{
services.AddMemoryCache();
services.AddHttpContextAccessor();
services.AddSingleton<ICustomerHttpAccessor, CustomerHttpAccessor>();
services.AddScoped<ICustomerRepository, CustomerRepository>();
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
services.AddSingleton<ICustomerHttpAccessor, CustomerHttpAccessor>();
services.AddScoped<ICustomerRepository, CustomerRepository>();
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

public static void ConfigureAutoMapper(this IServiceCollection services)
{
Expand All @@ -49,14 +48,14 @@ public static void ConfigureDatabaseContext(this IServiceCollection services, Co
{
services.AddDbContextFactory<CustomerDbContext>(options =>
options.UseSqlServer(configuration.GetConnectionString(Helpers.Constants.DatabaseConnectionString),
options => options.EnableRetryOnFailure()));
}
options => options.EnableRetryOnFailure()));
}

public static void ConfigureMediatr(this IServiceCollection services)
{
services.AddValidatorsFromAssemblyContaining<GetCustomerValidator>();
services.AddMediatR(_ => _.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorBehavior<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorBehavior<,>));
}

public static void ConfigureApiVersioning(this IServiceCollection services)
Expand Down
6 changes: 3 additions & 3 deletions Microservice.Customer.Api/Extensions/JwtExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
namespace Microservice.Customer.Api.Address.Api.Extensions;

public static class JwtExtensions
{
{
public static void AddJwtAuthentication(this IServiceCollection services)
{
services.AddAuthentication(optiones =>
Expand All @@ -30,6 +30,6 @@ public static void AddJwtAuthentication(this IServiceCollection services)
};

o.MapInboundClaims = false;
});
}
});
}
}
2 changes: 1 addition & 1 deletion Microservice.Customer.Api/Helpers/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ public class Constants
{
public const string JwtIssuer = "JWT_ISSUER";
public const string JwtAudience = "JWT_AUDIENCE";
public const string JwtSymmetricSecurityKey = "JWT_SYMMETRIC_SECURITY_KEY";
public const string JwtSymmetricSecurityKey = "JWT_SYMMETRIC_SECURITY_KEY";

public const string DatabaseConnectionString = "SQLAZURECONNSTR_CUSTOMER";
}
2 changes: 1 addition & 1 deletion Microservice.Customer.Api/Helpers/CustomerHttpAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ public CustomerHttpAccessor(IHttpContextAccessor accessor)
_accessor = accessor;
}

public Guid CustomerId => new Guid( _accessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier));
public Guid CustomerId => new(_accessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier));
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ public class GetCustomerMapper : Profile
{
public GetCustomerMapper()
{
base.CreateMap<Api.Domain.Customer, GetCustomerResponse>();
base.CreateMap<Api.Domain.Customer, GetCustomerResponse>();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@ namespace Microservice.Customer.Api.MediatR.GetCustomer;

public class GetCustomerQueryHandler(ICustomerRepository customerRepository, IMapper mapper) : IRequestHandler<GetCustomerRequest, GetCustomerResponse>
{
private ICustomerRepository _customerRepository { get; set; } = customerRepository ;
private ICustomerRepository _customerRepository { get; set; } = customerRepository;
private IMapper _mapper { get; set; } = mapper;

public async Task<GetCustomerResponse> Handle(GetCustomerRequest request, CancellationToken cancellationToken)
{
{
var customer = await _customerRepository.ByIdAsync(request.Id);
if (customer == null)
{
throw new NotFoundException("Customer not found.");
}
}

return _mapper.Map<GetCustomerResponse>(customer);
return _mapper.Map<GetCustomerResponse>(customer);
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
namespace Microservice.Customer.Api.MediatR.GetCustomer;

public record GetCustomerResponse(string Email, string Surname, string FirstName);
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

namespace Microservice.Customer.Api.MediatR.AddCustomer;

public class UpdateCustomerCommandHandler(ICustomerRepository customerRepository,
public class UpdateCustomerCommandHandler(ICustomerRepository customerRepository,
IMapper mapper, ICustomerHttpAccessor customerHttpAccessor) : IRequestHandler<UpdateCustomerRequest, UpdateCustomerResponse>
{
private ICustomerRepository _customerRepository { get; set; } = customerRepository;
Expand All @@ -19,7 +19,7 @@ public async Task<UpdateCustomerResponse> Handle(UpdateCustomerRequest updateCus
if (existingCustomer == null)
throw new NotFoundException("Customer not found.");

existingCustomer = _mapper.Map(updateCustomerRequest, existingCustomer);
existingCustomer = _mapper.Map(updateCustomerRequest, existingCustomer);

await _customerRepository.UpdateAsync(existingCustomer);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public class UpdateCustomerMapper : Profile
public UpdateCustomerMapper()
{
base.CreateMap<UpdateCustomerRequest, Microservice.Customer.Api.Domain.Customer>()
.ForMember(dest => dest.Id, opt => opt.Ignore())
.ForMember(dest => dest.Id, opt => opt.Ignore())
.ForMember(x => x.Email, act => act.MapFrom(src => src.Email))
.ForMember(x => x.Surname, act => act.MapFrom(src => src.Surname))
.ForMember(x => x.FirstName, act => act.MapFrom(src => src.FirstName))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ public UpdateCustomerValidator(ICustomerRepository customerRepository)
RuleFor(updateCustomerRequest => updateCustomerRequest.Email)
.NotEmpty().WithMessage("Email is required.")
.Length(8, 150).WithMessage("Email length between 8 and 150.")
.EmailAddress().WithMessage("Invalid Email.");
.EmailAddress().WithMessage("Invalid Email.");

RuleFor(updateCustomerRequest => updateCustomerRequest).MustAsync(async (updateCustomerRequest, cancellation) => {
RuleFor(updateCustomerRequest => updateCustomerRequest).MustAsync(async (updateCustomerRequest, cancellation) =>
{
return await EmailExists(updateCustomerRequest);
}).WithMessage("Customer with this email already exists");

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using FluentValidation;
using FluentValidation.Results;
using Microservice.Customer.Api.Helpers.Exceptions;
using Microservice.Customer.Api.Helpers.Exceptions;
using System.Net;
using System.Text.Json;
using static Microservice.Customer.Api.Helpers.Enums;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

Expand Down
3 changes: 1 addition & 2 deletions Microservice.Customer.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using Microservice.Customer.Api.Endpoints;
using Microservice.Customer.Api.Extensions;
using Microservice.Customer.Api.Middleware;

var builder = WebApplication.CreateBuilder(args);

Expand All @@ -13,7 +12,7 @@
builder.Services.ConfigureDatabaseContext(builder.Configuration);
builder.Services.ConfigureExceptionHandling();
builder.Services.ConfigureJwt();
builder.Services.ConfigureMediatr();
builder.Services.ConfigureMediatr();
builder.Services.ConfigureSwagger();

var app = builder.Build();
Expand Down

0 comments on commit 86c2766

Please sign in to comment.