Skip to content

Commit

Permalink
Versão inicial da API 1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
leandroribeiro committed Dec 28, 2020
1 parent d3ab888 commit 105c261
Show file tree
Hide file tree
Showing 20 changed files with 429 additions and 67 deletions.
104 changes: 46 additions & 58 deletions ProvaML.API/Controllers/ProdutoController.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using System.Security.Policy;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic.CompilerServices;
using ProvaML.API.Model;
using ProvaML.Application;
using ProvaML.Domain.Entities;
using ProvaML.Domain.Repositories;
using ProvaML.Infrastructure;
using ProvaML.Infrastructure.File;

namespace ProvaML.API.Controllers
{
Expand All @@ -22,54 +24,40 @@ public class ProdutoController : ControllerBase

private readonly ILogger<ProdutoController> _logger;
private readonly IProdutoRepository _repository;
private readonly IWebHostEnvironment _environment;
private readonly IProdutoAppService _produtoAppService;

public ProdutoController(ILogger<ProdutoController> logger, [FromServices] IProdutoRepository repository, IWebHostEnvironment environment)
public ProdutoController(ILogger<ProdutoController> logger, [FromServices] IProdutoRepository repository, IProdutoAppService produtoAppService)
{
_logger = logger;
_repository = repository;
_environment = environment;
_produtoAppService = produtoAppService;
}


[HttpGet]
public ActionResult<IEnumerable<Produto>> Get()
public ActionResult<IEnumerable<ProdutoViewModel>> Get()
{
return Ok(_repository.Obter());
var produtos = _repository.Obter();

return Ok(produtos.Select(x => new ProdutoViewModel(x, Url)));
}

[HttpGet("{id}")]
public ActionResult<Produto> Get(int id)
public ActionResult<ProdutoViewModel> Get(int id)
{
if (id <= 0)
{
return BadRequest();
}

var produto = _repository.Obter(id);

if (produto == null)
{
return NotFound();
}
var produto = _repository.Obter(id);

return produto;
}

[HttpPost]
[ProducesResponseType((int)HttpStatusCode.Created)]
public IActionResult Post([FromBody] CreateProdutoRequest data)
{
if (data is null)
if (produto == null)
{
return BadRequest();
return NotFound();
}

//var campaign = MapCampaignDtoToModel(campaignDto);

// _repository.Inserir();

return CreatedAtAction(nameof(Get), routeValues: new { data.Id }, null);
return new ProdutoViewModel(produto, Url);
}

[HttpPut("{id}")]
Expand All @@ -81,7 +69,7 @@ public ActionResult<Produto> Put(int id, [FromBody] AtualizarProdutoRequest data
}

var produtoParaAtualizar = _repository.Obter(id);

if (produtoParaAtualizar is null)
{
return NotFound();
Expand All @@ -106,45 +94,45 @@ public ActionResult Delete(int id)
}

var produtoParaExcluir = _repository.Obter(id);

if (produtoParaExcluir is null)
{
return NotFound();
}

_repository.Excluir(produtoParaExcluir);

return NoContent();

}

[HttpPost("upload")]
public async Task<string> EnviaArquivo([FromForm] IFormFile arquivo)
[HttpPost]
[ProducesResponseType((int)HttpStatusCode.Created)]
public IActionResult Post([FromForm] string nome, [FromForm] decimal valorVenda, [FromForm] IFormFile arquivo)
{
if (arquivo.Length > 0)
{
try
{
if (!Directory.Exists(_environment.ContentRootPath + "\\imagens\\"))
{
Directory.CreateDirectory(_environment.ContentRootPath + "\\imagens\\");
}
using (FileStream filestream = System.IO.File.Create(_environment.ContentRootPath + "\\imagens\\" + arquivo.FileName))
{
await arquivo.CopyToAsync(filestream);
filestream.Flush();
return "\\imagens\\" + arquivo.FileName;
}
}
catch (Exception ex)
{
return ex.ToString();
}
}
else
if (arquivo.Length <= 0)
return BadRequest("Nenhuma imagem enviada.");

var produto = _produtoAppService.Criar(nome, valorVenda, arquivo);

return CreatedAtAction(nameof(Get), routeValues: new { produto.Id }, null);

}

[HttpGet("{id}/imagem", Name = "GetImagem")]
public ActionResult<Produto> GetImagem(int id)
{
if (id <= 0)
{
return "Ocorreu uma falha no envio do arquivo...";
return BadRequest();
}

var imagem = _produtoAppService.BaixarImagem(id);

if (imagem != null)
return File(imagem.Stream, imagem.ContentType);

return NotFound();
}
}
}
27 changes: 27 additions & 0 deletions ProvaML.API/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /api
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src

COPY "ProvaML.sln" "ProvaML.sln"
COPY "ProvaML.API/ProvaML.API.csproj" "ProvaML.API/ProvaML.API.csproj"
COPY "ProvaML.Application/ProvaML.Application.csproj" "ProvaML.Application/ProvaML.Application.csproj"
COPY "ProvaML.Domain/ProvaML.Domain.csproj" "ProvaML.Domain/ProvaML.Domain.csproj"
COPY "ProvaML.Infrastructure/ProvaML.Infrastructure.csproj" "ProvaML.Infrastructure/ProvaML.Infrastructure.csproj"
COPY "ProvaML.Infrastructure.Tests/ProvaML.Infrastructure.Tests.csproj" "ProvaML.Infrastructure.Tests/ProvaML.Infrastructure.Tests.csproj"
COPY "ProvaML.Migration/ProvaML.Migration.csproj" "ProvaML.Migration/ProvaML.Migration.csproj"
RUN dotnet restore


COPY . .
WORKDIR /src/ProvaML.API
RUN dotnet publish -c Release -o /api

FROM build AS publish

FROM base AS final
WORKDIR /api
COPY --from=publish /api .
ENTRYPOINT ["dotnet", "ProvaML.API.dll"]
24 changes: 24 additions & 0 deletions ProvaML.API/Model/ProdutoViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using Microsoft.AspNetCore.Mvc;
using ProvaML.Domain.Entities;

namespace ProvaML.API.Model
{
public class ProdutoViewModel
{
public ProdutoViewModel(Produto produto, IUrlHelper urlHelper)
{
this.Id = produto.Id;
this.Nome = produto.Nome;
this.ValorDeVenda = produto.ValorVenda;
this.Imagem = urlHelper.RouteUrl("GetImagem", new { id=produto.Id });
}

public string Imagem { get; set; }

public decimal ValorDeVenda { get; set; }

public string Nome { get; set; }

public int Id { get; set; }
}
}
11 changes: 11 additions & 0 deletions ProvaML.API/ProvaML.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,19 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\ProvaML.Application\ProvaML.Application.csproj" />
<ProjectReference Include="..\ProvaML.Domain\ProvaML.Domain.csproj" />
<ProjectReference Include="..\ProvaML.Infrastructure\ProvaML.Infrastructure.csproj" />
</ItemGroup>

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

<ItemGroup>
<None Update="imagens\notfound.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
27 changes: 22 additions & 5 deletions ProvaML.API/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using ProvaML.Application;
using ProvaML.Infrastructure.Data;
using ProvaML.Domain.Repositories;
using ProvaML.Infrastructure;
using ProvaML.Infrastructure.File;

namespace ProvaML.API
{
Expand All @@ -33,12 +35,25 @@ public void ConfigureServices(IServiceCollection services)
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo {Title = "ProvaML.API", Version = "v1"});
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Prova ML API",
Version = "v1",
Contact = new OpenApiContact()
{
Name = "Leandro Ribeiro",
Email = string.Empty,
Url = new Uri("https://github.com/leandroribeiro")
}
});
});

services.AddEntityFrameworkSqlServer()
.AddDbContext<ProvaMLContext>(options => options.UseSqlServer(Configuration["ConnectionString"]));
.AddDbContext<ProvaMLContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddScoped<IProdutoRepository, ProdutoRepository>();
services.AddSingleton<IImageStorage, LocalImageStorage>();
services.AddScoped<IProdutoAppService, ProdutoAppService>();

}

Expand All @@ -48,17 +63,19 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ProvaML.API v1"));
}

app.UseHttpsRedirection();
//TODO
//app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ProvaML API v1"));
}
}
}
4 changes: 3 additions & 1 deletion ProvaML.API/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
{
"ConnectionString": "Server=localhost,5434;Database=ProvaML;User Id=sa;Password=Dev123456789;",
"ConnectionStrings": {
"DefaultConnection": "Server=localhost,5434;Database=ProvaML;User Id=sa;Password=Dev123456789;"
},

"Logging": {
"LogLevel": {
Expand Down
Binary file added ProvaML.API/imagens/notfound.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 11 additions & 0 deletions ProvaML.Application/IProdutoAppService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using Microsoft.AspNetCore.Http;
using ProvaML.Domain.Entities;

namespace ProvaML.Application
{
public interface IProdutoAppService
{
Produto Criar(string nome, decimal valorVenda, IFormFile arquivo);
ImagemDTO BaixarImagem(int id);
}
}
13 changes: 13 additions & 0 deletions ProvaML.Application/ImagemDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace ProvaML.Application
{
public class ImagemDTO
{
public ImagemDTO()
{

}

public byte[] Stream { get; set; }
public string ContentType { get; set; }
}
}
Loading

0 comments on commit 105c261

Please sign in to comment.