using AsbCloudApp.Exceptions; using AsbCloudApp.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.ComponentModel.DataAnnotations; using System.Threading; using System.Threading.Tasks; namespace AsbCloudWebApi.Controllers { [Route("api/[controller]")] [ApiController] [Authorize] public class UserSettingsController : ControllerBase { private readonly IUserSettingsRepository service; public UserSettingsController(IUserSettingsRepository service) { this.service = service; } [HttpGet("{key}")] [Permission] [ProducesResponseType(typeof(object), (int)System.Net.HttpStatusCode.OK)] [Produces("application/json")] public virtual async Task GetAsync( [StringLength(255, MinimumLength = 1, ErrorMessage = "The key value cannot less then 1 character and greater then 255. ")] string key, CancellationToken token) { var userId = User.GetUserId(); if (userId is null) return Forbid(); var result = await service.GetOrDefaultAsync((int)userId, key, token).ConfigureAwait(false); var actionResult = new JsonResult(result); actionResult.ContentType = "application/json"; return actionResult; } [HttpPost("{key}")] [Permission] public virtual async Task> InsertAsync(string key, [FromBody] System.Text.Json.JsonDocument value, CancellationToken token) { var userId = User.GetUserId(); if (userId is null) return Forbid(); var result = await service.InsertAsync((int)userId, key, value, token).ConfigureAwait(false); if (result == IUserSettingsRepository.ErrorKeyIsUsed) return BadRequest(ArgumentInvalidException.MakeValidationError(nameof(key), "is already used")); return Ok(result); } [HttpPut("{key}")] public virtual async Task> UpdateAsync(string key, [FromBody] System.Text.Json.JsonDocument value, CancellationToken token) { var userId = User.GetUserId(); if (userId is null) return Forbid(); var result = await service.UpdateAsync((int)userId, key, value, token).ConfigureAwait(false); if (result < 0) return BadRequest(ArgumentInvalidException.MakeValidationError(nameof(key), "not found")); return Ok(result); } [HttpDelete("{key}")] public virtual async Task> DeleteAsync(string key, CancellationToken token) { var userId = User.GetUserId(); if (userId is null) return Forbid(); var result = await service.DeleteAsync((int)userId, key, token).ConfigureAwait(false); if (result < 0) return BadRequest(ArgumentInvalidException.MakeValidationError(nameof(key), "not found")); return Ok(result); } } }