The Update method now checks if CatTitle is being changed and returns a 400 Bad Request if so. It also returns 404 Not Found if the catalog does not exist before attempting an update. This ensures CatTitle remains immutable during updates.
78 lines
2.2 KiB
C#
78 lines
2.2 KiB
C#
using DbFirst.Application.Catalogs;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
namespace DbFirst.API.Controllers;
|
|
|
|
[ApiController]
|
|
[Route("api/[controller]")]
|
|
public class CatalogsController : ControllerBase
|
|
{
|
|
private readonly ICatalogService _service;
|
|
|
|
public CatalogsController(ICatalogService service)
|
|
{
|
|
_service = service;
|
|
}
|
|
|
|
[HttpGet]
|
|
public async Task<ActionResult<IEnumerable<CatalogReadDto>>> GetAll(CancellationToken cancellationToken)
|
|
{
|
|
var result = await _service.GetAllAsync(cancellationToken);
|
|
return Ok(result);
|
|
}
|
|
|
|
[HttpGet("{id:int}")]
|
|
public async Task<ActionResult<CatalogReadDto>> GetById(int id, CancellationToken cancellationToken)
|
|
{
|
|
var result = await _service.GetByIdAsync(id, cancellationToken);
|
|
if (result == null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
return Ok(result);
|
|
}
|
|
|
|
[HttpPost]
|
|
public async Task<ActionResult<CatalogReadDto>> Create(CatalogWriteDto dto, CancellationToken cancellationToken)
|
|
{
|
|
var created = await _service.CreateAsync(dto, cancellationToken);
|
|
if (created == null)
|
|
{
|
|
return Conflict();
|
|
}
|
|
return CreatedAtAction(nameof(GetById), new { id = created.Guid }, created);
|
|
}
|
|
|
|
[HttpPut("{id:int}")]
|
|
public async Task<ActionResult<CatalogReadDto>> Update(int id, CatalogWriteDto dto, CancellationToken cancellationToken)
|
|
{
|
|
var current = await _service.GetByIdAsync(id, cancellationToken);
|
|
if (current == null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
if (!string.Equals(current.CatTitle, dto.CatTitle, StringComparison.Ordinal))
|
|
{
|
|
return BadRequest("CatTitle cannot be changed.");
|
|
}
|
|
|
|
var updated = await _service.UpdateAsync(id, dto, cancellationToken);
|
|
if (updated == null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
return Ok(updated);
|
|
}
|
|
|
|
[HttpDelete("{id:int}")]
|
|
public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken)
|
|
{
|
|
var deleted = await _service.DeleteAsync(id, cancellationToken);
|
|
if (!deleted)
|
|
{
|
|
return NotFound();
|
|
}
|
|
return NoContent();
|
|
}
|
|
}
|