69 lines
1.7 KiB
C#

using LocationsApi.Models;
using LocationsApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace LocationsApi.Controllers;
[ApiController]
[Route("api/[controller]")]
public class LocationsController : ControllerBase
{
private readonly LocationStore _locations;
public LocationsController(LocationStore locations)
{
_locations = locations;
}
[HttpPost]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> Create([FromBody] CreateLocationRequest req)
{
if (string.IsNullOrWhiteSpace(req.Name))
return BadRequest("Name required");
var location = new Location
{
Name = req.Name.Trim(),
CreatedUtc = DateTime.UtcNow
};
await _locations.CreateAsync(location);
return Ok(location);
}
[HttpGet]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> ListMine()
{
var locations = await _locations.GetAllAsync();
return Ok(locations);
}
[HttpDelete("{id}")]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> Delete(string id)
{
var deleted = await _locations.DeleteAsync(id);
if (!deleted)
return NotFound();
return Ok("Deleted");
}
[HttpPut("{id}")]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> Update(string id, [FromBody] UpdateLocationRequest req)
{
if (string.IsNullOrWhiteSpace(req.Name))
return BadRequest("Name required");
var updated = await _locations.UpdateNameAsync(id, req.Name.Trim());
if (!updated)
return NotFound();
return Ok("Updated");
}
}