CodeLiturgy.Dashboard/BlueWest.Api/Controllers/UserController.cs

116 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using BlueWest.Data;
using BlueWest.WebApi.EF;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BlueWest.WebApi.Controllers
{
[ApiController]
[Route("[controller]")]
internal class UserController : ControllerBase
{
private readonly UserDbContext _dbContext;
/// <summary>
/// Controller responsible to handle user data
/// </summary>
/// <param name="dbContext"></param>
public UserController(UserDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Gets all the users in the user table12312
/// </summary>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[HttpGet]
public ActionResult Get()
{
var users = _dbContext.Users.ToArray();
return Ok(users);
}
/// <summary>
/// Get User by Id
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{userId}", Name = nameof(GetUserById))]
public ActionResult GetUserById(int userId)
{
var user = _dbContext.Users.FirstOrDefault(x => x.Id == userId);
if (user != null)
{
return Ok(user);
}
return new NotFoundResult();
}
/// <summary>
/// Adds a user to the database
/// </summary>
/// <param name="userCreate">User to add </param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status201Created)]
[HttpPost]
public ActionResult AddUser(UserCreate userCreate)
{
var user = new User(userCreate);
_dbContext.Users.Add(user);
_dbContext.SaveChanges();
return CreatedAtRoute(nameof(GetUserById), new {userId = user.Id}, user);
}
/// <summary>
/// Updates user data
/// </summary>
/// <param name="userId">User id</param>
/// <param name="userCreate"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpPut($"{{userId:int}}")]
public ActionResult UpdateUser(int userId, UserCreate userCreate)
{
return new NotFoundResult();
}
/// <summary>
/// Deletes a user from the database
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpDelete("{id:int}")]
public ActionResult DeleteUser(int id)
{
var user = _dbContext.Users.FirstOrDefault(u => u.Id == id);
if (user == null)
{
return new NotFoundResult();
}
_dbContext.Users.Remove(user);
_dbContext.SaveChanges();
return Ok();
}
}
}