PlotDirector/PlotLine/Controllers/ContextThreadsController.cs
2026-12-02 15:14:34 +00:00

32 lines
1.3 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Services.Context;
namespace PlotLine.Controllers;
[Authorize, ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class ContextThreadsController(ContextThreads threads) : Controller
{
private async Task<IActionResult> Guard(Func<Task<IActionResult>> action)
{
try { return await action(); }
catch (UnauthorizedAccessException) { return Forbid(); }
catch (SqlException e) when (e.Number is 51010 or 51011 or 51012)
{ return StatusCode(e.Number == 51010 ? 403 : 409, new { message = e.Message }); }
catch (ArgumentException e) { return BadRequest(new { message = e.Message }); }
}
[HttpGet]
public Task<IActionResult> State(int bookId, int sceneId) => Guard(async () =>
ModelState.IsValid && bookId > 0 && sceneId > 0 ? Json(await threads.Read(bookId, sceneId)) : BadRequest());
[HttpPost, ValidateAntiForgeryToken]
public Task<IActionResult> Add([FromBody] ContextThreadSelection input) => Guard(async () =>
{
if (!ModelState.IsValid || input == null || input.BookID <= 0 || input.SceneID <= 0) return BadRequest();
await threads.Add(input);
return Json(new { saved = true });
});
}