72 lines
3.1 KiB
C#
72 lines
3.1 KiB
C#
using HuntingAppApi.Models;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Npgsql;
|
|
|
|
namespace HuntingAppApi.Controllers;
|
|
|
|
[ApiController]
|
|
[Authorize]
|
|
[Route("api/map-points")]
|
|
public sealed class MapPointsController(NpgsqlDataSource dataSource) : ControllerBase
|
|
{
|
|
[HttpGet("area/{huntAreaId:guid}")]
|
|
public async Task<ActionResult<List<MapPointDto>>> GetByArea(Guid huntAreaId, CancellationToken ct)
|
|
{
|
|
var result = new List<MapPointDto>();
|
|
await using var conn = await dataSource.OpenConnectionAsync(ct);
|
|
await using var cmd = new NpgsqlCommand("""
|
|
SELECT mp.id, mp.hunt_area_id, t.name, t.icon, t.color, mp.name, mp.description,
|
|
ST_Y(mp.geom), ST_X(mp.geom), mp.image_url
|
|
FROM map_point mp
|
|
JOIN map_point_type t ON t.id = mp.type_id
|
|
WHERE mp.hunt_area_id = @hunt_area_id AND mp.is_active = true
|
|
ORDER BY t.name, mp.name
|
|
""", conn);
|
|
cmd.Parameters.AddWithValue("hunt_area_id", huntAreaId);
|
|
await using var r = await cmd.ExecuteReaderAsync(ct);
|
|
while (await r.ReadAsync(ct))
|
|
{
|
|
result.Add(new MapPointDto
|
|
{
|
|
Id = r.GetGuid(0),
|
|
HuntAreaId = r.GetGuid(1),
|
|
Type = r.GetString(2),
|
|
Icon = r.IsDBNull(3) ? null : r.GetString(3),
|
|
Color = r.IsDBNull(4) ? null : r.GetString(4),
|
|
Name = r.GetString(5),
|
|
Description = r.IsDBNull(6) ? null : r.GetString(6),
|
|
Latitude = r.GetDouble(7),
|
|
Longitude = r.GetDouble(8),
|
|
ImageUrl = r.IsDBNull(9) ? null : r.GetString(9)
|
|
});
|
|
}
|
|
return Ok(result);
|
|
}
|
|
|
|
[HttpPost]
|
|
public async Task<ActionResult<ApiId>> Create([FromBody] CreateMapPointRequest request, CancellationToken ct)
|
|
{
|
|
var id = Guid.NewGuid();
|
|
await using var conn = await dataSource.OpenConnectionAsync(ct);
|
|
await using var cmd = new NpgsqlCommand("""
|
|
INSERT INTO map_point (id, hunt_area_id, type_id, name, description, geom, image_url)
|
|
SELECT @id, @hunt_area_id, t.id, @name, @description,
|
|
ST_SetSRID(ST_MakePoint(@longitude, @latitude), 4326), @image_url
|
|
FROM map_point_type t
|
|
WHERE t.name = @type
|
|
""", conn);
|
|
cmd.Parameters.AddWithValue("id", id);
|
|
cmd.Parameters.AddWithValue("hunt_area_id", request.HuntAreaId);
|
|
cmd.Parameters.AddWithValue("type", request.Type);
|
|
cmd.Parameters.AddWithValue("name", request.Name);
|
|
cmd.Parameters.AddWithValue("description", (object?)request.Description ?? DBNull.Value);
|
|
cmd.Parameters.AddWithValue("longitude", request.Longitude);
|
|
cmd.Parameters.AddWithValue("latitude", request.Latitude);
|
|
cmd.Parameters.AddWithValue("image_url", (object?)request.ImageUrl ?? DBNull.Value);
|
|
var rows = await cmd.ExecuteNonQueryAsync(ct);
|
|
if (rows == 0) return BadRequest($"Unknown map point type: {request.Type}");
|
|
return Ok(new ApiId(id));
|
|
}
|
|
}
|