VEU.WathBody/3-app/2-cli/Server.WatchBody.Web/Controllers/SyncController.cs

62 lines
1.7 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Server.WatchBody.Web.Dto;
using Server.WatchBody.Web.Services;
namespace Server.WatchBody.Web.Controllers;
/// <summary>POST /api/v1/sync — приём пакета телефона (spec 03-sync-post).</summary>
public class SyncController : Controller
{
private readonly SyncService _sync;
public SyncController(SyncService sync) => _sync = sync;
public ActionResult Sync()
{
int athleteId;
try
{
athleteId = AthleteId();
}
catch (InvalidOperationException)
{
return Error(401, "unauthorized");
}
List<SyncItem> items;
try
{
using var reader = new StreamReader(Request.Body);
items = SyncItemParser.Parse(reader.ReadToEndAsync().Result);
}
catch (SyncException e)
{
return Error(e.StatusCode, e.Message);
}
try
{
var accepted = _sync.Process(athleteId, items);
return new JsonResult(new SyncResponse { Accepted = accepted });
}
catch (SyncException e)
{
return Error(e.StatusCode, e.Code);
}
catch (Exception e)
{
// сбой БД внутри пакета: откат (TransactionScope) + 400, текст — в лог
Console.Error.WriteLine($"sync error: {e}");
return Error(400, "sync_failed: " + e.Message);
}
}
private int AthleteId() => (int)HttpContext.Items[Middleware.ApiKeyMiddleware.AthleteIdItem]!;
private ActionResult Error(int statusCode, string message)
{
Response.StatusCode = statusCode;
return new JsonResult(new ErrorResponse { Error = message });
}
}