40 lines
1.7 KiB
C#
40 lines
1.7 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 or 51100 or 51101)
|
|
{ return StatusCode(e.Number is 51010 or 51100 ? 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 });
|
|
});
|
|
|
|
[HttpPost, ValidateAntiForgeryToken]
|
|
public Task<IActionResult> Remove([FromBody] ContextThreadRemoval input) => Guard(async () =>
|
|
{
|
|
if (!ModelState.IsValid || input == null || input.BookID <= 0 || input.SceneID <= 0 || input.ThreadID <= 0) return BadRequest();
|
|
await threads.Remove(input);
|
|
return Json(new { saved = true });
|
|
});
|
|
}
|