From c5ddb62a0d13f4fc6c2c1609afa7488867d81650 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Tracewicz?= Date: Fri, 27 Sep 2024 17:50:17 +0200 Subject: [PATCH] Closes #60 Imporve API response codes --- backend/src/api/Controllers/TodoController.cs | 44 ++++++++++++++++--- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/backend/src/api/Controllers/TodoController.cs b/backend/src/api/Controllers/TodoController.cs index 0986aec..be20025 100644 --- a/backend/src/api/Controllers/TodoController.cs +++ b/backend/src/api/Controllers/TodoController.cs @@ -104,12 +104,16 @@ public async Task CreateItem([FromBody] TodoItem request) return userId switch { null => Unauthorized(), - var user => await Create(user, request), + var user => await Handle(user, request), }; - async Task Create(string user, TodoItem item) + async Task Handle(string user, TodoItem item) { var newItem = await _service.CreateItem(user, item); + if (newItem is null) + { + return BadRequest(); + } return Created(HttpContext.Request.Path.Add(new PathString($"/{newItem.Id}")), newItem); } } @@ -134,8 +138,18 @@ public async Task GetItem([FromRoute] int id) return userId switch { null => Unauthorized(), - var user => Ok(await _service.GetItem(user, id)), + var user => await Handle(user, id), }; + + async Task Handle(string user, int id) + { + var item = await _service.GetItem(user, id); + if (item is null) + { + return NotFound(); + } + return Ok(item); + } } [HttpDelete("items/{id}")] @@ -146,8 +160,18 @@ public async Task DeleteItem([FromRoute] int id) return userId switch { null => Unauthorized(), - var user => Ok(await _service.DeleteItem(user, id)), + var user => await Handle(user, id), }; + + async Task Handle(string user, int id) + { + var success = await _service.DeleteItem(user, id); + if (success) + { + return Ok(); + } + return BadRequest(); + } } [HttpPut("items/{id}")] @@ -158,8 +182,18 @@ public async Task UpdateItem([FromRoute] int id, [FromBody] TodoI return userId switch { null => Unauthorized(), - var user => Ok(await _service.UpdateItem(user, request)), + var user => await Handle(user, id), }; + + async Task Handle(string user, int id) + { + var success = await _service.UpdateItem(user, request); + if (success) + { + return Ok(); + } + return BadRequest(); + } } }