Skip to content
This repository has been archived by the owner on Aug 24, 2023. It is now read-only.

Teste C# para Belezanaweb (Boticário) #104

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
17 changes: 17 additions & 0 deletions src/Belezanaweb.API/Belezanaweb.API.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MediatR" Version="10.0.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Belezanaweb.Application.Core\Belezanaweb.Application.Core.csproj" />
<ProjectReference Include="..\Belezanaweb.Infra.IoC\Belezanaweb.Infra.IoC.csproj" />
</ItemGroup>


</Project>
45 changes: 45 additions & 0 deletions src/Belezanaweb.API/Controllers/ProductController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using Belezanaweb.Application.Core.Commands;
using Belezanaweb.Application.Products.Commands;
using Belezanaweb.Application.Products.Queries;
using Belezanaweb.Application.Products.ViewModels;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace Belezanaweb.API.Controllers
{
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
private readonly IMediator _mediator;

public ProductController(IMediator mediator)
{
_mediator = mediator;
}

[HttpGet("{sku:long}")]
public async Task<Response<ProductViewModel>> GetProductBySkuAsync([FromRoute] long sku)
{
return await _mediator.Send(new GetProductBySkuQuery(sku));
}

[HttpPost]
public async Task<Response> CreateProductAsync([FromBody] CreateProductCommand command)
{
return await _mediator.Send(command);
}

[HttpPut]
public async Task<Response> AlterProductAsync([FromBody] AlterProductCommand command)
{
return await _mediator.Send(command);
}

[HttpDelete("{sku:long}")]
public async Task<Response> DeleteProductAsync([FromRoute] long sku)
{
return await _mediator.Send(new DeleteProductCommand(sku));
}
}
}
20 changes: 20 additions & 0 deletions src/Belezanaweb.API/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace Belezanaweb.API
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
56 changes: 56 additions & 0 deletions src/Belezanaweb.API/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using Belezanaweb.Application.Core.Middlewares;
using Belezanaweb.Infra.IoC;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


namespace Belezanaweb.API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
IoC.Load(services);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseGlobalExceptionHandlerMiddleware();

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
9 changes: 9 additions & 0 deletions src/Belezanaweb.API/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
10 changes: 10 additions & 0 deletions src/Belezanaweb.API/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentValidation" Version="11.0.1" />
<PackageReference Include="MediatR" Version="10.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Belezanaweb.Core\Belezanaweb.Core.csproj" />
</ItemGroup>

</Project>
9 changes: 9 additions & 0 deletions src/Belezanaweb.Application.Core/Commands/IRequestBase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using FluentValidation.Results;

namespace Belezanaweb.Application.Core.Commands
{
public interface IRequestBase
{
ValidationResult ValidationResult { get; }
}
}
13 changes: 13 additions & 0 deletions src/Belezanaweb.Application.Core/Commands/RequestBase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using FluentValidation.Results;
using MediatR;
using System.Text.Json.Serialization;

namespace Belezanaweb.Application.Core.Commands
{
public abstract class RequestBase<TQuery> : IRequestBase, IRequest<TQuery>
{
[JsonIgnore]
public ValidationResult ValidationResult { get; set; }
public abstract bool IsValid();
}
}
50 changes: 50 additions & 0 deletions src/Belezanaweb.Application.Core/Commands/Response.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using Newtonsoft.Json;

namespace Belezanaweb.Application.Core.Commands
{
public class BaseResponse<TRequest> where TRequest : class
{
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("errorMessages")]
public string[] ErrorMessages { get; set; }
[JsonProperty("data")]
public TRequest Data { get; set; }
}

public class Response<TRequest> : BaseResponse<TRequest> where TRequest : class
{
public Response(string errorMessage)
{
base.ErrorMessages = new[] { errorMessage } ;
Success = false;
Data = default;
}

public Response(TRequest data)
{
Data = data;
Success = true;
}
}

public class Response : BaseResponse<object>
{
public Response(string errorMessage)
{
ErrorMessages = new[] { errorMessage };
Success = false;
}

public Response(string[] errorMessages)
{
ErrorMessages = errorMessages;
Success = false;
}

public Response()
{
Success = true;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using Belezanaweb.Application.Core.Commands;
using Belezanaweb.Core.Exceptions;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;

namespace Belezanaweb.Application.Core.Middlewares
{
public class GlobalExceptionHandlerMiddleware : IMiddleware
{
public GlobalExceptionHandlerMiddleware()
{
}

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await next(context);
}
catch (BusinessException ex)
{
await HandleExceptionAsync(context, ex, (int)HttpStatusCode.BadRequest);
}
catch (ValidatorException ex)
{
await HandleExceptionAsync(context, ex);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex, (int)HttpStatusCode.InternalServerError);
}
}

private Task HandleExceptionAsync(HttpContext context, ValidatorException payload)
{
ConfigureErrorResponse(context, (int)HttpStatusCode.BadRequest);

var text = string.Empty;
if (payload != null)
{
var errors = new List<string>();
foreach (Exception ex in payload.Exceptions)
{
errors.Add(ex.Message);
}
text = JsonConvert.SerializeObject(new Response(errors.ToArray()));
}
return context.Response.WriteAsync(text);
}

private Task HandleExceptionAsync(HttpContext context, Exception payload, int statusCode)
{
ConfigureErrorResponse(context, statusCode);

var text = string.Empty;
if (payload != null)
{
text = JsonConvert.SerializeObject(new Response(payload.Message));
}
return context.Response.WriteAsync(text);
}

private void ConfigureErrorResponse(HttpContext context, int statusCode)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = statusCode;
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;

namespace Belezanaweb.Application.Core.Middlewares
{
public static class GlobalExceptionHandlerMiddlewareExtension
{
public static IServiceCollection AddGlobalExceptionHandlerMiddleware(this IServiceCollection services)
{
return services.AddTransient<GlobalExceptionHandlerMiddleware>();
}

public static void UseGlobalExceptionHandlerMiddleware(this IApplicationBuilder app)
{
app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
}
}
}
8 changes: 8 additions & 0 deletions src/Belezanaweb.Application.Core/Queries/IQuery.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using MediatR;

namespace Belezanaweb.Application.Core.Queries
{
public interface IQuery : IRequest
{
}
}
19 changes: 19 additions & 0 deletions src/Belezanaweb.Application/Belezanaweb.Application.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AutoMapper" Version="11.0.1" />
<PackageReference Include="FluentValidation" Version="11.0.1" />
<PackageReference Include="MediatR" Version="10.0.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Belezanaweb.Application.Core\Belezanaweb.Application.Core.csproj" />
<ProjectReference Include="..\Belezanaweb.Core\Belezanaweb.Core.csproj" />
<ProjectReference Include="..\Belezanaweb.Infra.Data\Belezanaweb.Infra.Data.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Belezanaweb.Application.Validators.Products;

namespace Belezanaweb.Application.Products.Commands
{
public class AlterProductCommand : BaseProductCommand
{
public override bool IsValid()
{
ValidationResult = new AlterProductValidator().Validate(this);
return ValidationResult.IsValid;
}
}
}
Loading