DAS_2024_1/aleikin_artem_lab_3/TaskProject/Controllers/TaskController.cs

78 lines
2.5 KiB
C#

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using TaskProject.Entity;
using static System.Runtime.InteropServices.JavaScript.JSType;
using Task = TaskProject.Entity.Task;
namespace TaskProject.Controllers
{
[ApiController]
[Route("tasks")]
public class TaskController : ControllerBase
{
private static readonly List<Task> Tasks = new();
[HttpGet]
public ActionResult<List<Task>> GetTasks() => Ok(Tasks);
[HttpGet("{id}")]
public ActionResult<Task> GetTask(Guid id)
{
var task = Tasks.FirstOrDefault(t => t.Id == id);
return task is null ? NotFound() : Ok(task);
}
[HttpPost]
public ActionResult<Task> CreateTask([FromBody] TaskDto taskDto)
{
Task task = new Task
{
Title = taskDto.Title,
Description = taskDto.Description,
ProjectId = taskDto.ProjectId,
};
var client = new HttpClient();
var response = client.GetAsync($"http://nginx/projectservice/projects/{task.ProjectId}").Result;
if (!response.IsSuccessStatusCode) return BadRequest("Project not found");
Tasks.Add(task);
return CreatedAtAction(nameof(GetTask), new { id = task.Id }, task);
}
[HttpPut("{id}")]
public ActionResult<Task> UpdateTask(Guid id, [FromBody] TaskDto taskDto)
{
var task = Tasks.FirstOrDefault(t => t.Id == id);
if (task is null) return NotFound();
var client = new HttpClient();
var response = client.GetAsync($"http://nginx/projectservice/projects/{task.ProjectId}").Result;
if (!response.IsSuccessStatusCode) return BadRequest("Project not found");
task.Title = taskDto.Title;
task.Description = taskDto.Description;
task.ProjectId = taskDto.ProjectId;
return Ok(task);
}
[HttpDelete("{id}")]
public IActionResult DeleteTask(Guid id)
{
var task = Tasks.FirstOrDefault(t => t.Id == id);
if (task is null) return NotFound();
Tasks.Remove(task);
return Ok();
}
[HttpDelete("by-project/{projectId}")]
public IActionResult DeleteTasksByProject(Guid projectId)
{
Tasks.RemoveAll(t => t.ProjectId == projectId);
return Ok();
}
}
}