Skip to content
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
16 changes: 16 additions & 0 deletions ApiEcommerce.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,23 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Scalar.AspNetCore" Version="2.13.15" />
</ItemGroup>

<ItemGroup>
<Folder Include="Controllers/" />
<Folder Include="Mapping/" />
</ItemGroup>

</Project>
20 changes: 20 additions & 0 deletions ApplicationDbContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using ApiEcommerce.Models;
using Microsoft.EntityFrameworkCore;

namespace ApiEcommerce;

// El DbContext es la unidad de trabajo que representa una sesión con la base de datos
public class ApplicationDbContext : DbContext
{
// El constructor recibe las configuraciones (como la cadena de conexión)
// y las pasa a la clase base (base) de Entity Framework.
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
// Aquí no solemos escribir lógica, EF se encarga de la inicialización.
}

// Un DbSet representa una colección de entidades en el código
// que se mapea directamente a una tabla física en la base de datos.
// En este caso: La clase 'Category' se convertirá en la tabla 'Categories'.
public DbSet<Category> Categories { get; set; }
}
134 changes: 134 additions & 0 deletions Controllers/CategoriesController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
using ApiEcommerce.Models;
using ApiEcommerce.Models.DTOs;
using ApiEcommerce.Repositories.Interfaces;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;

namespace ApiEcommerce.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CategoriesController : ControllerBase

{
private ICategoryRepository _categoryRepository;
private readonly IMapper _mapper;

public CategoriesController(ICategoryRepository categoryRepository, IMapper mapper)
{
_categoryRepository = categoryRepository;
_mapper = mapper;
}

[HttpGet]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status200OK)]
public IActionResult GetCategories()
{
var categories = _categoryRepository.GetCategories();
var categoriesDto = new List<CategoryDto>();

foreach (var category in categories)
{
categoriesDto.Add(_mapper.Map<CategoryDto>(category));
}

return Ok(categoriesDto);
}

[HttpGet("{id:int}", Name = "GetCategory")]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status200OK)]
public IActionResult GetCategory(int id)
{
var category = _categoryRepository.GetCategory(id);

if (category == null)
return NotFound($"La categoria con el id {id} no existe");

var categoryDto = _mapper.Map<CategoryDto>(category);

return Ok(categoryDto);
}

[HttpPost]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status201Created)]
public IActionResult CreateCategory([FromBody] CreateCategoryDto createCategoryDto)
{
if (createCategoryDto == null)
return BadRequest(ModelState);

if (_categoryRepository.CategoryExists(createCategoryDto.Name))
{
ModelState.AddModelError("CustomError", $"La categoria con el nombre {createCategoryDto.Name} ya existe");
return BadRequest(ModelState);
}

var category = _mapper.Map<Category>(createCategoryDto);

if (!_categoryRepository.CreateCategory(category))
{
ModelState.AddModelError("CustomError", $"Ocurrió un error al guardar la categoria {category.Name}");
return StatusCode(500, ModelState);
}

return CreatedAtRoute("GetCategory", new { id = category.Id }, category);
}
[HttpPatch("{id:int}", Name = "UpdateCategory")]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult UpdateCategtory([FromBody] CreateCategoryDto updateCategoryDto, int id)
{
if (!_categoryRepository.CategoryExists(id))
return NotFound($"La categoria con el id {id} no existe");

if (updateCategoryDto == null || id <= 0)
return BadRequest(ModelState);

if (_categoryRepository.CategoryExists(updateCategoryDto.Name))
{
ModelState.AddModelError("CustomError", $"La categoria con el nombre {updateCategoryDto.Name} ya existe");
return BadRequest(ModelState);
}

var category = _mapper.Map<Category>(updateCategoryDto);
category.Id = id;

if (!_categoryRepository.UpdateCategory(category))
{
ModelState.AddModelError("CustomError", $"Ocurrió un error al actualizar la categoria {category.Name}");
return StatusCode(500, ModelState);
}

return NoContent();
}

[HttpDelete("{id:int}", Name = "DeleteCategory")]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult DeleteCategory(int id)
{
var category = _categoryRepository.GetCategory(id);

if(category == null)
return NotFound($"La categoria con el id {id} no existe");

if (!_categoryRepository.DeleteCategory(category))
{
ModelState.AddModelError("CustomError", $"Ocurrió un error al eliminar la categoria {category.Name}");
return StatusCode(500, ModelState);
}

return NoContent();
}
}
}



14 changes: 14 additions & 0 deletions Mapping/CategoryProfile.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using ApiEcommerce.Models;
using ApiEcommerce.Models.DTOs;
using AutoMapper;

namespace ApiEcommerce.Mapping;

public class CategoryProfile : Profile
{
public CategoryProfile()
{
CreateMap<Category, CategoryDto>().ReverseMap();
CreateMap<Category, CreateCategoryDto>().ReverseMap();
}
}
50 changes: 50 additions & 0 deletions Migrations/20260326022034_InitialMigration.Designer.cs

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

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

#nullable disable

namespace ApiEcommerce.Migrations
{
/// <inheritdoc />
public partial class InitialMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Categories",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
CreationDate = table.Column<DateTime>(type: "datetime2", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Categories", x => x.Id);
});
}

/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Categories");
}
}
}
47 changes: 47 additions & 0 deletions Migrations/ApplicationDbContextModelSnapshot.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// <auto-generated />
using System;
using ApiEcommerce;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

#nullable disable

namespace ApiEcommerce.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 128);

SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);

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

SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));

b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");

b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.HasKey("Id");

b.ToTable("Categories");
});
#pragma warning restore 612, 618
}
}
}
15 changes: 15 additions & 0 deletions Models/Category.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System.ComponentModel.DataAnnotations;

namespace ApiEcommerce.Models;

public class Category
{
[Key]
public int Id { get; set; }

[Required]
public string Name { get; set; } = string.Empty;

[Required]
public DateTime CreationDate { get; set; }
}
12 changes: 12 additions & 0 deletions Models/DTOs/CategoryDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System;

namespace ApiEcommerce.Models.DTOs;

public class CategoryDto
{
public int Id { get; set; }

public string Name { get; set; } = string.Empty;

public DateTime CreationDate { get; set; }
}
11 changes: 11 additions & 0 deletions Models/DTOs/CreateCategoryDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System.ComponentModel.DataAnnotations;

namespace ApiEcommerce.Models.DTOs;

public class CreateCategoryDto
{
[Required(ErrorMessage = "El nombre es obligatorio.")]
[MaxLength(50, ErrorMessage = "El nombre no puede tener mas de 50 caracteres,")]
[MinLength(3, ErrorMessage = "El nombre no puede tener menos de 3 caracteres.")]
public string Name { get; set; } = string.Empty;
}
Loading