#nullable disable
using CORE.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Users.APP.Features.Statuses;
//Generated from Custom Microservices Template.
namespace Users.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
// Way 1:
//[Authorize(Roles = "Admin,User")]
// Only authenticated users with Admin or User role
// can execute all of the actions of this controller.
// Way 2:
[Authorize]
// Only authenticated users can execute all of the
// actions of this controller.
// Since we have only 2 roles Admin and User, we can
// use Authorize to check auhenticated users without
// defining roles.
public class StatusesController : ControllerBase
{
private readonly ILogger<StatusesController> _logger;
private readonly IMediator _mediator;
// Constructor: injects logger to log the errors to Kestrel Console or Output Window and mediator
public StatusesController(ILogger<StatusesController> logger, IMediator mediator)
{
_logger = logger;
_mediator = mediator;
}
// GET: api/Statuses
[HttpGet]
[AllowAnonymous]
// Can be used to allow authenticated and unauthenticated
// users (everyone) to execute this action.
// Overrides the Authorize defined for the controller.
public async Task<IActionResult> Get()
{
try
{
// Send a query request to get query response
var response = await _mediator.Send(new StatusQueryRequest());
// Convert the query response to a list
var list = await response.ToListAsync();
// If there are items, return them with 200 OK
if (list.Any())
return Ok(list);
// If no items found, return 204 No Content
return NoContent();
}
catch (Exception exception)
{
// Log the exception
_logger.LogError("StatusesGet Exception: " + exception.Message);
// Return 500 Internal Server Error with an error command response with message
return StatusCode(StatusCodes.Status500InternalServerError, new CommandResponse(false, "An exception occured during StatusesGet."));
}
}
// GET: api/Statuses/5
[HttpGet("{id}")]
// Only authenticated users (since Authorize is defined
// at the controller level) can execute this action.
public async Task<IActionResult> Get(int id)
{
try
{
// Send a query request to get query response
var response = await _mediator.Send(new StatusQueryRequest());
// Find the item with the given id
var item = await response.SingleOrDefaultAsync(r => r.Id == id);
// If item found, return it with 200 OK
if (item is not null)
return Ok(item);
// If item not found, return 204 No Content
return NoContent();
}
catch (Exception exception)
{
// Log the exception
_logger.LogError("StatusesGetById Exception: " + exception.Message);
// Return 500 Internal Server Error with an error command response with message
return StatusCode(StatusCodes.Status500InternalServerError, new CommandResponse(false, "An exception occured during StatusesGetById."));
}
}
// POST: api/Statuses
[HttpPost]
[Authorize(Roles = "Admin")]
// Only authenticated users with role Admin can execute
// this action.
// Overrides the Authorize defined for the controller.
public async Task<IActionResult> Post(StatusAddRequest request)
{
try
{
// Check if the request model is valid through data annotations
if (ModelState.IsValid)
{
// Send the create request
var response = await _mediator.Send(request);
// If creation is successful, return 200 OK with success command response
if (response.IsSuccessful)
{
//return CreatedAtAction(nameof(Get), new { id = response.Id }, response);
return Ok(response);
}
// If creation failed, add error command response message to model state
ModelState.AddModelError("StatusesPost", response.Message);
}
// Return 400 Bad Request with all data annotation validation error messages and the error command response message if added seperated by |
return BadRequest(new CommandResponse(false, string.Join("|", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage))));
}
catch (Exception exception)
{
// Log the exception
_logger.LogError("StatusesPost Exception: " + exception.Message);
// Return 500 Internal Server Error with an error command response with message
return StatusCode(StatusCodes.Status500InternalServerError, new CommandResponse(false, "An exception occured during StatusesPost."));
}
}
// PUT: api/Statuses
[HttpPut]
[Authorize(Roles = "Admin")]
// Only authenticated users with role Admin can execute
// this action.
// Overrides the Authorize defined for the controller.
public async Task<IActionResult> Put(StatusUpdateRequest request)
{
try
{
// Check if the request model is valid through data annotations
if (ModelState.IsValid)
{
// Send the update request
var response = await _mediator.Send(request);
// If update is successful, return 200 OK with success command response
if (response.IsSuccessful)
{
//return NoContent();
return Ok(response);
}
// If update failed, add error command response message to model state
ModelState.AddModelError("StatusesPut", response.Message);
}
// Return 400 Bad Request with all data annotation validation error messages and the error command response message if added seperated by |
return BadRequest(new CommandResponse(false, string.Join("|", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage))));
}
catch (Exception exception)
{
// Log the exception
_logger.LogError("StatusesPut Exception: " + exception.Message);
// Return 500 Internal Server Error with an error command response with message
return StatusCode(StatusCodes.Status500InternalServerError, new CommandResponse(false, "An exception occured during StatusesPut."));
}
}
// DELETE: api/Statuses/5
[HttpDelete("{id}")]
[Authorize(Roles = "Admin")]
// Only authenticated users with role Admin can execute
// this action.
// Overrides the Authorize defined for the controller.
public async Task<IActionResult> Delete(int id)
{
try
{
// Send the delete request
var response = await _mediator.Send(new StatusRemoveRequest() { Id = id });
// If delete is successful, return 200 OK with success command response
if (response.IsSuccessful)
{
//return NoContent();
return Ok(response);
}
// If delete failed, add error command response message to model state
ModelState.AddModelError("StatusesDelete", response.Message);
// Return 400 Bad Request with the error command response message
return BadRequest(new CommandResponse(false, string.Join("|", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage))));
}
catch (Exception exception)
{
// Log the exception
_logger.LogError("StatusesDelete Exception: " + exception.Message);
// Return 500 Internal Server Error with an error command response with message
return StatusCode(StatusCodes.Status500InternalServerError, new CommandResponse(false, "An exception occured during StatusesDelete."));
}
}
}
}