57 lines
2.1 KiB
C#
57 lines
2.1 KiB
C#
using HuntingAppApi.Models;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Npgsql;
|
|
|
|
namespace HuntingAppApi.Controllers;
|
|
|
|
[ApiController]
|
|
[Authorize]
|
|
[Route("api/hunt-areas")]
|
|
public sealed class HuntAreasController(NpgsqlDataSource dataSource) : ControllerBase
|
|
{
|
|
[HttpGet]
|
|
public async Task<ActionResult<List<HuntAreaDto>>> GetAll(CancellationToken ct)
|
|
{
|
|
var result = new List<HuntAreaDto>();
|
|
await using var conn = await dataSource.OpenConnectionAsync(ct);
|
|
await using var cmd = new NpgsqlCommand("""
|
|
SELECT id, name, description, CASE WHEN geom IS NULL THEN NULL ELSE ST_AsGeoJSON(geom) END
|
|
FROM hunt_area
|
|
ORDER BY name
|
|
""", conn);
|
|
await using var r = await cmd.ExecuteReaderAsync(ct);
|
|
while (await r.ReadAsync(ct))
|
|
{
|
|
result.Add(new HuntAreaDto
|
|
{
|
|
Id = r.GetGuid(0),
|
|
Name = r.GetString(1),
|
|
Description = r.IsDBNull(2) ? null : r.GetString(2),
|
|
GeoJson = r.IsDBNull(3) ? null : r.GetString(3)
|
|
});
|
|
}
|
|
return Ok(result);
|
|
}
|
|
|
|
[HttpPost]
|
|
public async Task<ActionResult<ApiId>> Create([FromBody] CreateHuntAreaRequest request, CancellationToken ct)
|
|
{
|
|
var id = Guid.NewGuid();
|
|
await using var conn = await dataSource.OpenConnectionAsync(ct);
|
|
await using var cmd = new NpgsqlCommand("""
|
|
INSERT INTO hunt_area (id, name, description, geom)
|
|
VALUES (@id, @name, @description,
|
|
CASE WHEN @geojson::text IS NULL OR @geojson::text = '' THEN NULL
|
|
ELSE ST_SetSRID(ST_GeomFromGeoJSON(@geojson), 4326)::geometry(MultiPolygon, 4326)
|
|
END)
|
|
""", conn);
|
|
cmd.Parameters.AddWithValue("id", id);
|
|
cmd.Parameters.AddWithValue("name", request.Name);
|
|
cmd.Parameters.AddWithValue("description", (object?)request.Description ?? DBNull.Value);
|
|
cmd.Parameters.AddWithValue("geojson", (object?)request.GeoJson ?? DBNull.Value);
|
|
await cmd.ExecuteNonQueryAsync(ct);
|
|
return Ok(new ApiId(id));
|
|
}
|
|
}
|