study-lib-backend/API/Controllers/GroupCandidatesController.cs
2020-12-30 00:28:50 +01:00

72 lines
2.3 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using StudyLib.API.Data;
using StudyLib.API.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StudyLib.API.Controllers
{
[Route("api/groupCandidates")]
[Authorize]
[ApiController]
public class GroupCandidatesController : ControllerBase
{
private readonly StudyLibContext _context;
public GroupCandidatesController(StudyLibContext context)
{
_context = context;
}
[HttpGet("list/{groupId}")]
public async Task<ActionResult<IEnumerable<User>>> GetGroupCandidates(long groupId)
{
return await _context.GroupCandidates.Where(g => g.Group.ID == groupId).Include(g => g.User).Select(g => g.User).ToListAsync();
}
[HttpPost("join-request")]
public async Task<IActionResult> GroupCandidate(GroupCandidateSaveModel groupCandidateSaveModel)
{
var user = await _context.Users.FindAsync(groupCandidateSaveModel.UserId);
var group = await _context.Groups.FindAsync(groupCandidateSaveModel.GroupId);
var groupCandidate = new GroupCandidate
{
GroupId = groupCandidateSaveModel.GroupId,
Group = group,
UserId = groupCandidateSaveModel.UserId,
User = user
};
_context.GroupCandidates.Add(groupCandidate);
await _context.SaveChangesAsync();
return NoContent();
}
[HttpDelete("delete/{groupId}/{userId}")]
public async Task<IActionResult> DeleteGroupCandidate(long groupId, string userId)
{
var groupCandidate = await _context.GroupCandidates.Where(g => g.Group.ID == groupId && g.User.Id == userId).FirstAsync();
if (groupCandidate == null)
{
return NotFound();
}
_context.GroupCandidates.Remove(groupCandidate);
await _context.SaveChangesAsync();
return NoContent();
}
private bool GroupCandidateExists(long groupId, string userId)
{
return _context.GroupCandidates.Any(g => g.Group.ID == groupId && g.User.Id == userId);
}
}
}