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

Api Construída! #85

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
24 changes: 19 additions & 5 deletions Context/OrganizadorContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,27 @@

namespace TrilhaApiDesafio.Context
{
public class OrganizadorContext : DbContext
public class AppDbContext : DbContext
{
public OrganizadorContext(DbContextOptions<OrganizadorContext> options) : base(options)
public DbSet<Tarefa> Tarefas { get; set; }

// Construtor necessário para o AddDbContext funcionar
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{

}

public DbSet<Tarefa> Tarefas { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Tarefa>()
.Property(t => t.Titulo)
.HasColumnType("TEXT"); // MySQL-compatible type for large text
modelBuilder.Entity<Tarefa>()
.Property(t => t.Descricao)
.HasColumnType("TEXT"); // MySQL-compatible type for large text
modelBuilder.Entity<Tarefa>()
.Property(t => t.Data)
.HasColumnType("DATETIME"); // MySQL-compatible type for date and time
}
}
}
}
83 changes: 61 additions & 22 deletions Controllers/TarefaController.cs
Original file line number Diff line number Diff line change
@@ -1,58 +1,73 @@
using Microsoft.AspNetCore.Mvc;
using TrilhaApiDesafio.Context;
using TrilhaApiDesafio.Models;
using System.Linq;

namespace TrilhaApiDesafio.Controllers
{
[ApiController]
[Route("[controller]")]
public class TarefaController : ControllerBase
{
private readonly OrganizadorContext _context;
private readonly AppDbContext _context;

public TarefaController(OrganizadorContext context)
public TarefaController(AppDbContext context)
{
_context = context;
}

[HttpGet("{id}")]
public IActionResult ObterPorId(int id)
{
// TODO: Buscar o Id no banco utilizando o EF
// TODO: Validar o tipo de retorno. Se não encontrar a tarefa, retornar NotFound,
// caso contrário retornar OK com a tarefa encontrada
return Ok();
// Buscar o ID no banco de dados
var tarefa = _context.Tarefas.Find(id);

// Se não encontrar, retornar NotFound
if (tarefa == null)
return NotFound();

// Caso contrário, retornar OK com a tarefa encontrada
return Ok(tarefa);
}

[HttpGet("ObterTodos")]
public IActionResult ObterTodos()
{
// TODO: Buscar todas as tarefas no banco utilizando o EF
return Ok();
// Buscar todas as tarefas no banco
var tarefas = _context.Tarefas.ToList();

// Retornar OK com a lista de tarefas
return Ok(tarefas);
}

[HttpGet("ObterPorTitulo")]
public IActionResult ObterPorTitulo(string titulo)
{
// TODO: Buscar as tarefas no banco utilizando o EF, que contenha o titulo recebido por parâmetro
// Dica: Usar como exemplo o endpoint ObterPorData
return Ok();
// Buscar tarefas que contenham o título especificado
var tarefas = _context.Tarefas.Where(t => t.Titulo.Contains(titulo)).ToList();

// Retornar OK com a lista de tarefas encontradas
return Ok(tarefas);
}

[HttpGet("ObterPorData")]
public IActionResult ObterPorData(DateTime data)
{
var tarefa = _context.Tarefas.Where(x => x.Data.Date == data.Date);
return Ok(tarefa);
// Buscar tarefas com a mesma data (desconsiderando o horário)
var tarefas = _context.Tarefas.Where(x => x.Data.Date == data.Date).ToList();

// Retornar OK com as tarefas encontradas
return Ok(tarefas);
}

[HttpGet("ObterPorStatus")]
public IActionResult ObterPorStatus(EnumStatusTarefa status)
{
// TODO: Buscar as tarefas no banco utilizando o EF, que contenha o status recebido por parâmetro
// Dica: Usar como exemplo o endpoint ObterPorData
var tarefa = _context.Tarefas.Where(x => x.Status == status);
return Ok(tarefa);
// Buscar tarefas com o status especificado
var tarefas = _context.Tarefas.Where(x => x.Status == status).ToList();

// Retornar OK com as tarefas encontradas
return Ok(tarefas);
}

[HttpPost]
Expand All @@ -61,35 +76,59 @@ public IActionResult Criar(Tarefa tarefa)
if (tarefa.Data == DateTime.MinValue)
return BadRequest(new { Erro = "A data da tarefa não pode ser vazia" });

// TODO: Adicionar a tarefa recebida no EF e salvar as mudanças (save changes)
// Adicionar a nova tarefa ao banco
_context.Tarefas.Add(tarefa);

// Salvar as mudanças
_context.SaveChanges();

// Retornar CreatedAtAction com os dados da nova tarefa
return CreatedAtAction(nameof(ObterPorId), new { id = tarefa.Id }, tarefa);
}

[HttpPut("{id}")]
public IActionResult Atualizar(int id, Tarefa tarefa)
{
// Buscar a tarefa no banco pelo ID
var tarefaBanco = _context.Tarefas.Find(id);

// Se não encontrar, retornar NotFound
if (tarefaBanco == null)
return NotFound();

if (tarefa.Data == DateTime.MinValue)
return BadRequest(new { Erro = "A data da tarefa não pode ser vazia" });

// TODO: Atualizar as informações da variável tarefaBanco com a tarefa recebida via parâmetro
// TODO: Atualizar a variável tarefaBanco no EF e salvar as mudanças (save changes)
return Ok();
// Atualizar os dados da tarefaBanco com os dados recebidos
tarefaBanco.Titulo = tarefa.Titulo;
tarefaBanco.Descricao = tarefa.Descricao;
tarefaBanco.Data = tarefa.Data;
tarefaBanco.Status = tarefa.Status;

// Salvar as mudanças no banco
_context.SaveChanges();

// Retornar OK
return Ok(tarefaBanco);
}

[HttpDelete("{id}")]
public IActionResult Deletar(int id)
{
// Buscar a tarefa no banco pelo ID
var tarefaBanco = _context.Tarefas.Find(id);

// Se não encontrar, retornar NotFound
if (tarefaBanco == null)
return NotFound();

// TODO: Remover a tarefa encontrada através do EF e salvar as mudanças (save changes)
// Remover a tarefa encontrada
_context.Tarefas.Remove(tarefaBanco);

// Salvar as mudanças no banco
_context.SaveChanges();

// Retornar NoContent
return NoContent();
}
}
Expand Down
49 changes: 49 additions & 0 deletions Migrations/20241204185720_UpdateForMySql.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

68 changes: 68 additions & 0 deletions Migrations/20241204185720_UpdateForMySql.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace TrilhaApiDesafio.Migrations
{
public partial class UpdateForMySql : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "Titulo",
table: "Tarefas",
type: "TEXT",
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(max)",
oldNullable: true);

migrationBuilder.AlterColumn<string>(
name: "Descricao",
table: "Tarefas",
type: "TEXT",
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(max)",
oldNullable: true);

migrationBuilder.AlterColumn<DateTime>(
name: "Data",
table: "Tarefas",
type: "DATETIME",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "datetime2(6)");
}

protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "Titulo",
table: "Tarefas",
type: "nvarchar(max)",
nullable: true,
oldClrType: typeof(string),
oldType: "TEXT",
oldNullable: true);

migrationBuilder.AlterColumn<string>(
name: "Descricao",
table: "Tarefas",
type: "nvarchar(max)",
nullable: true,
oldClrType: typeof(string),
oldType: "TEXT",
oldNullable: true);

migrationBuilder.AlterColumn<DateTime>(
name: "Data",
table: "Tarefas",
type: "datetime2(6)",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "DATETIME");
}
}
}
47 changes: 47 additions & 0 deletions Migrations/OrganizadorContextModelSnapshot.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using TrilhaApiDesafio.Context;

#nullable disable

namespace TrilhaApiDesafio.Migrations
{
[DbContext(typeof(AppDbContext))]
partial class OrganizadorContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.33")
.HasAnnotation("Relational:MaxIdentifierLength", 64);

modelBuilder.Entity("TrilhaApiDesafio.Models.Tarefa", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");

b.Property<DateTime>("Data")
.HasColumnType("DATETIME");

b.Property<string>("Descricao")
.HasColumnType("TEXT");

b.Property<int>("Status")
.HasColumnType("int");

b.Property<string>("Titulo")
.HasColumnType("TEXT");

b.HasKey("Id");

b.ToTable("Tarefas");
});
#pragma warning restore 612, 618
}
}
}
5 changes: 3 additions & 2 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddDbContext<OrganizadorContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("ConexaoPadrao")));
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseMySQL(
builder.Configuration.GetConnectionString("MySql")));

builder.Services.AddControllers().AddJsonOptions(options =>
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
Expand Down
5 changes: 5 additions & 0 deletions TrilhaApiDesafio.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="MySql.EntityFrameworkCore" Version="8.0.8" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>

Expand Down
2 changes: 1 addition & 1 deletion appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
}
},
"ConnectionStrings": {
"ConexaoPadrao": "COLOCAR SUA CONNECTION STRING AQUI"
"MySql": "Server = localhost; Database = api_desafio; Uid = root; pwd = Gabrieleition2@"
}
}
5 changes: 4 additions & 1 deletion appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,8 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"ConnectionStrings": {
"MySql": "Informações de conexão retiradas"
}
}
Loading