using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace ScrumTaskboard.Controllers
{
///
/// This is a controller of Users class includes all API's related to the Users.
///
[Route("[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly TaskContext _context;
///
/// Initializes a new instance of the class.
///
///
public UsersController(TaskContext context)
{
_context = context;
}
// GET: api/sprint
///
/// Retrieve all Users in DB.
/// Result can be filtered using the Params.
///
/// string value
/// JSON list of all matching Users
#nullable enable
[HttpGet]
public async Task>> GetUser([FromQuery]string? name)
{
var filtered = _context.Users.AsQueryable();
if (name != null)
{
filtered = filtered.Where(u => u.Name.Contains(name));
}
return await filtered.ToListAsync();
}
#nullable disable
// GET: api/sprint/5
///
/// Retrieve the User by it's ID.
///
/// ID of searched User
/// JSON object
[HttpGet("{id}")]
public async Task> GetUser(int id)
{
var user = await _context.Users.FindAsync(id);
if (user == null)
{
return NotFound();
}
return user;
}
// PUT: api/sprint/5
///
/// Update the User identified by it's ID.
///
/// to edit User's ID
/// modified Sprint
/// the proper status code
[HttpPut("{id}")]
public async Task PutUser(int id, ScrumUser sprint)
{
// The user's ID must not be changed
if (id != sprint.Id)
{
return BadRequest();
}
// Save the changed user in the context
_context.Entry(sprint).State = EntityState.Modified;
try
{
// Apply the changes to the database
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
// If the user does not exist, return status code 404
if (!UserExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/User
///
/// Create a new User.
///
/// new Sprint
/// the proper status code
[HttpPost]
public async Task> PostUser(ScrumUser sprint)
{
_context.Users.Add(sprint);
await _context.SaveChangesAsync();
// The new user has been created and can be called up using the GetUser method
return CreatedAtAction("GetUser", new { id = sprint.Id }, sprint);
}
// DELETE: api/User/5
///
/// Delete a User identified by it's ID.
///
/// to delete User's ID
/// the proper status code
[HttpDelete("{id}")]
public async Task> DeleteUser(int id)
{
var scrumUser = await _context.Users.FindAsync(id);
if (scrumUser == null)
{
return NotFound();
}
// Remove the user from the context
_context.Users.Remove(scrumUser);
// Save the changes in the database
await _context.SaveChangesAsync();
return scrumUser;
}
///
/// Checks whether a user with the specified ID already exists.
///
private bool UserExists(int id)
{
return _context.Users.Any(e => e.Id == id);
}
}
}