Compare commits

..
21 Commits
Author SHA1 Message Date
Technoir 80fdd6ccae Merge branch 'feature/11-status-codes', fixes #11 2026-10-11 14:46:37 +02:00
Technoir 2e062f60b9 console.log mit console.error ersetzt 2026-10-11 14:45:45 +02:00
Technoir 96a0876035 editItem reingelagert 2026-10-11 14:33:30 +02:00
Technoir a7d467f187 Fehlerhandling von Errorcodes
response und das json werden jeweils gespeichert, funktion bricht ab
wenn statuscode nicht übereinstimmt (response.status != xxx zu
!response.ok mass-refactored)
2026-10-11 14:33:14 +02:00
Technoir a49506fece api funktione geben nurnoch die response als solches zurück 2026-10-11 14:31:17 +02:00
Technoir 75721a7465 addItem gibt 201 mit location und json zurück 2026-10-11 13:45:27 +02:00
Technoir 71fd6ee420 deleteItem 404 exception hinzugefügt 2026-10-11 13:45:12 +02:00
Technoir 1e1b8d0ec5 400 und 404 bei deleteAllDoneItems hinzugefügt 2026-10-11 13:44:45 +02:00
Technoir 5a34db09f6 editItem 404 exception hinzugefügt 2026-10-11 13:44:31 +02:00
Technoir a467d3f4a7 addItem 404 exception hinzugefügt 2026-10-11 13:44:14 +02:00
Technoir 7c81870665 imports 2026-10-11 13:38:03 +02:00
Technoir 6f503f311e editCategory wirft 404 bei falscher categoryID 2026-10-11 13:37:59 +02:00
Technoir 9fa60a8d6d addCategory gibt statuscode + neue category als json zurück 2026-10-11 13:37:43 +02:00
Technoir 16dfd340ec deleteCateogry wift 404 bei falscher categoryID 2026-10-11 13:37:26 +02:00
Technoir 8a6bef92f7 deleteCategory wirft 400 bei fehlendem Parameter 2026-10-11 13:36:42 +02:00
Technoir 17b7f485f6 addCategory wift 404 bei falscher ListID 2026-10-11 13:36:16 +02:00
Technoir 7bec1e7b5c imports 2026-10-11 13:35:09 +02:00
Technoir b601083e7a BadRequestException hinzugefügt 2026-10-11 13:34:26 +02:00
Technoir 3d8e7f308b addList gibt 201 mit uri und neuer Ressource als Response 2026-10-11 13:22:13 +02:00
Technoir c8808a9f23 edit- und deleteList geben 404 zurück bei falscher ID 2026-10-11 13:21:30 +02:00
Technoir a6063ad842 ResourceNotFoundException hinzugefügt
eigene custom exception für bessere Fehlermeldung
2026-10-11 13:20:07 +02:00
11 changed files with 192 additions and 87 deletions

No files matched your search

@@ -3,6 +3,8 @@ package de.timaldinger.einkaufsliste.Controller;
import de.timaldinger.einkaufsliste.Dto.Post.ShoppingCategoryPostDTO;
import de.timaldinger.einkaufsliste.Dto.Patch.ShoppingCategoryPatchDTO;
import de.timaldinger.einkaufsliste.Dto.Response.ShoppingCategoryResponseDTO;
import de.timaldinger.einkaufsliste.Exceptions.BadRequestException;
import de.timaldinger.einkaufsliste.Exceptions.ResourceNotFoundException;
import de.timaldinger.einkaufsliste.Models.ShoppingCategory;
import de.timaldinger.einkaufsliste.Models.ShoppingItem;
import de.timaldinger.einkaufsliste.Models.ShoppingList;
@@ -14,7 +16,9 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
import java.util.UUID;
@@ -28,21 +32,27 @@ public class ShoppingCategoryController {
private ShoppingItemRepository shoppingItemRepository;
@PostMapping("/api/categories")
public ShoppingCategoryResponseDTO addCategory(@RequestBody ShoppingCategoryPostDTO newCategory){
public ResponseEntity<ShoppingCategoryResponseDTO> addCategory(@RequestBody ShoppingCategoryPostDTO newCategory){
String name = newCategory.categoryName();
ShoppingList list = shoppingListRepository.findById(newCategory.listID()).orElseThrow();
ShoppingList list = shoppingListRepository.findById(newCategory.listID()).orElseThrow(() -> new ResourceNotFoundException("listID",newCategory.listID()));
ShoppingCategory category = new ShoppingCategory(name, List.of(),list);
shoppingCategoryRepository.save(category);
return new ShoppingCategoryResponseDTO(name, category.getId());
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(category.getId())
.toUri();
return ResponseEntity.created(location).body(new ShoppingCategoryResponseDTO(name, category.getId()));
}
@PatchMapping("/api/categories/{categoryID}")
public ResponseEntity<Void> editCategory(@PathVariable UUID categoryID,@RequestBody ShoppingCategoryPatchDTO toChange){
ShoppingCategory category = shoppingCategoryRepository.findById(categoryID).orElseThrow();
ShoppingCategory category = shoppingCategoryRepository.findById(categoryID).orElseThrow(() -> new ResourceNotFoundException("categoryID",categoryID));
if(toChange.categoryName() != null) category.setCategoryName(toChange.categoryName());
@@ -56,9 +66,11 @@ public class ShoppingCategoryController {
public ResponseEntity<Void> deleteCategory(@PathVariable UUID categoryID, @RequestParam(required = false) Boolean deleteAllItems){
if(deleteAllItems == null){
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Missing required parameter deleteAllItems (can be either true or false)");
throw new BadRequestException("Missing required parameter deleteAllItems (can be either true or false)");
}
shoppingCategoryRepository.findById(categoryID).orElseThrow(() -> new ResourceNotFoundException("categoryID", categoryID));
List<ShoppingItem> itemList = shoppingItemRepository.findAllByCategory_Id(categoryID);
if(deleteAllItems){
itemList.forEach((item) -> shoppingItemRepository.deleteById(item.getId()));
@@ -3,16 +3,23 @@ package de.timaldinger.einkaufsliste.Controller;
import de.timaldinger.einkaufsliste.Dto.Post.ShoppingItemPostDTO;
import de.timaldinger.einkaufsliste.Dto.Patch.ShoppingItemPatchDTO;
import de.timaldinger.einkaufsliste.Dto.Response.ShoppingItemResponseDTO;
import de.timaldinger.einkaufsliste.Exceptions.BadRequestException;
import de.timaldinger.einkaufsliste.Exceptions.ResourceNotFoundException;
import de.timaldinger.einkaufsliste.Models.ShoppingCategory;
import de.timaldinger.einkaufsliste.Models.ShoppingItem;
import de.timaldinger.einkaufsliste.Models.ShoppingList;
import de.timaldinger.einkaufsliste.Repository.ShoppingCategoryRepository;
import de.timaldinger.einkaufsliste.Repository.ShoppingItemRepository;
import de.timaldinger.einkaufsliste.Repository.ShoppingListRepository;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
import java.util.UUID;
@@ -26,30 +33,37 @@ public class ShoppingItemController {
private ShoppingItemRepository shoppingItemRepository;
@PostMapping("/api/items")
public ShoppingItemResponseDTO addItem(@RequestBody ShoppingItemPostDTO newItem){
public ResponseEntity<ShoppingItemResponseDTO> addItem(@RequestBody ShoppingItemPostDTO newItem){
String name = newItem.itemName();
String amount = newItem.itemAmount();
ShoppingCategory c;
if(newItem.categoryID() != null){
c = shoppingCategoryRepository.findById(newItem.categoryID()).orElseThrow();
c = shoppingCategoryRepository.findById(newItem.categoryID()).orElseThrow(() -> new ResourceNotFoundException("categoryID", newItem.categoryID()));
}else{
c = null;
}
ShoppingList list = shoppingListRepository.findById(newItem.listID()).orElseThrow();
ShoppingList list = shoppingListRepository.findById(newItem.listID()).orElseThrow(() -> new ResourceNotFoundException("listID", newItem.listID()));
ShoppingItem item = new ShoppingItem(name, amount, false, c, list);
shoppingItemRepository.save(item);
return new ShoppingItemResponseDTO(name, amount, item.getId(), c != null? c.getId() : null);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(item.getId())
.toUri();
return ResponseEntity.created(location).body(new ShoppingItemResponseDTO(name,amount,item.getId(),c != null ? c.getId() : null));
}
@PatchMapping("/api/items/{itemID}")
public ResponseEntity<Void> editItem(@PathVariable UUID itemID ,@RequestBody ShoppingItemPatchDTO toChange){
ShoppingItem item = shoppingItemRepository.findById(itemID).orElseThrow();
ShoppingItem item = shoppingItemRepository.findById(itemID).orElseThrow(() -> new ResourceNotFoundException("itemID",itemID));
if(toChange.itemName() != null) item.setItemName(toChange.itemName());
if(toChange.itemAmount() != null) item.setItemAmount(toChange.itemAmount());
if(toChange.isDone() != null) item.setDone(toChange.isDone());
if(toChange.categoryID() != null) item.setCategory(shoppingCategoryRepository.findById(toChange.categoryID()).orElseThrow());
if(toChange.categoryID() != null) item.setCategory(shoppingCategoryRepository.findById(toChange.categoryID()).orElseThrow(() -> new ResourceNotFoundException("categoryID",toChange.categoryID())));
shoppingItemRepository.save(item);
@@ -58,9 +72,7 @@ public class ShoppingItemController {
@DeleteMapping("/api/items/{itemID}")
public ResponseEntity<Void> deleteItem(@PathVariable UUID itemID){
if(!shoppingItemRepository.existsById(itemID)){
return ResponseEntity.notFound().build();
}
shoppingItemRepository.findById(itemID).orElseThrow(() ->new ResourceNotFoundException("itemID",itemID));
shoppingItemRepository.deleteById(itemID);
return ResponseEntity.noContent().build();
}
@@ -68,7 +80,8 @@ public class ShoppingItemController {
@DeleteMapping("/api/lists/{listID}/items")
public ResponseEntity<Void> deleteAllDoneItems(@PathVariable UUID listID, @RequestParam boolean done){
if(!done) return ResponseEntity.badRequest().build();
if(!done) throw new BadRequestException("Parameter \"done\" must be true!");
shoppingListRepository.findById(listID).orElseThrow(() -> new ResourceNotFoundException("listID", listID));
List<ShoppingItem> items = shoppingItemRepository.findByList_IdAndIsDoneIsTrue(listID);
shoppingItemRepository.deleteAll(items);
@@ -3,6 +3,7 @@ package de.timaldinger.einkaufsliste.Controller;
import de.timaldinger.einkaufsliste.Dto.Patch.ShoppingListPatchDTO;
import de.timaldinger.einkaufsliste.Dto.Post.ShoppingListPostDTO;
import de.timaldinger.einkaufsliste.Dto.Response.ShoppingListResponseDTO;
import de.timaldinger.einkaufsliste.Exceptions.ResourceNotFoundException;
import de.timaldinger.einkaufsliste.Models.ShoppingItem;
import de.timaldinger.einkaufsliste.Models.ShoppingList;
import de.timaldinger.einkaufsliste.Repository.ShoppingCategoryRepository;
@@ -10,9 +11,13 @@ import de.timaldinger.einkaufsliste.Repository.ShoppingItemRepository;
import de.timaldinger.einkaufsliste.Repository.ShoppingListRepository;
import de.timaldinger.einkaufsliste.Service.ShoppingListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
import java.util.UUID;
@@ -29,22 +34,31 @@ public class ShoppingListController {
private ShoppingListService shoppingListService;
@PostMapping("/api/lists")
public ShoppingListResponseDTO addList(@RequestBody ShoppingListPostDTO newList){
public ResponseEntity<ShoppingListResponseDTO> addList(@RequestBody ShoppingListPostDTO newList){
ShoppingList list = new ShoppingList(newList.listName(), null, null, 0, 0);
shoppingListRepository.save(list);
return new ShoppingListResponseDTO(list.getListName(), list.getId());
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(list.getId())
.toUri();
return ResponseEntity.created(location).body(new ShoppingListResponseDTO(list.getListName(), list.getId()));
}
@DeleteMapping("/api/lists/{listID}")
public ResponseEntity<Void> deleteList(@PathVariable UUID listID){
shoppingListRepository.findById(listID).orElseThrow(() -> new ResourceNotFoundException("listID",listID));
shoppingListService.deleteList(listID);
return ResponseEntity.noContent().build();
}
@PatchMapping("/api/lists/{listID}")
public ResponseEntity<Void> editList(@PathVariable UUID listID,@RequestBody ShoppingListPatchDTO toChange){
ShoppingList list = shoppingListRepository.findById(listID).orElseThrow();
ShoppingList list = shoppingListRepository.findById(listID).orElseThrow(() -> new ResourceNotFoundException("listID", listID));
if(toChange.newListName() != null) list.setListName(toChange.newListName());
@@ -0,0 +1,11 @@
package de.timaldinger.einkaufsliste.Exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
}
@@ -0,0 +1,9 @@
package de.timaldinger.einkaufsliste.Exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String resource, Object value){ super("Resource " + resource + ":"+value.toString()+" not found");}
}
@@ -2,7 +2,7 @@
export async function addList(listName) {
const response = await fetch(`/api/lists`,
return await fetch(`/api/lists`,
{
method: "POST",
body: JSON.stringify({ listName: listName }),
@@ -10,24 +10,19 @@ export async function addList(listName) {
}
);
return response.json();
}
export async function deleteList(id) {
const response = await fetch(`/api/lists/${id}`, { method: "DELETE" });
return response;
return await fetch(`/api/lists/${id}`, { method: "DELETE" });
}
export async function editList(listID, toChange) {
const response = await fetch(`/api/lists/${listID}`,
return await fetch(`/api/lists/${listID}`,
{
method: "PATCH",
body: JSON.stringify(toChange),
headers: { "Content-Type": "application/json" }
});
return response;
}
@@ -5,9 +5,15 @@ import * as ui from "./frontend/indexUI.js"
const addListForm = document.querySelector(".addListForm");
async function addList(listName) {
const listAsJson = await api.addList(listName);
console.log(`${listAsJson}`);
if (listAsJson) ui.addList(listAsJson);
const response = await api.addList(listName);
const json = await response.json();
if (!response.ok) {
console.error(`error creating list ${json}`);
return;
}
ui.addList(json);
}
function editList(listLi) {
@@ -19,13 +25,19 @@ function editList(listLi) {
formElement.querySelector(".editForm__name").focus();
function save() {
async function save() {
let formData = Object.fromEntries(new FormData(formElement));
ui.editList(id, formElement, formData, listLi);
console.log(`editing catogory ${id} with ${formData}`)
api.editList(id, { newListName: formData.newListName });
const response = await api.editList(id, { newListName: formData.newListName });
if (!response.ok) {
const json = await response.json();
console.error(`error editing list ${json}`);
return;
}
ui.editList(id, formElement, formData, listLi);
}
formElement.addEventListener("submit", (event) => {
@@ -44,7 +56,13 @@ async function deleteList(listElement) {
const response = await api.deleteList(listElement.dataset.id);
if (response.status == 204) ui.deleteList(listElement);
if (!response.ok) {
const json = await response.json();
console.error(`error deleting list ${json}`);
return;
}
ui.deleteList(listElement);
}
@@ -1,30 +1,22 @@
export async function addCategory(listID, categoryName) {
const newCategory = await fetch(`/api/categories`,
return await fetch(`/api/categories`,
{
method: "POST"
, body: JSON.stringify({ "categoryName": categoryName, "listID": listID })
, headers: { "Content-Type": "application/json" }
});
return await newCategory.json();
}
export async function editCategory(categoryID, toChange) {
const response = await fetch(`/api/categories/${categoryID}`,
return await fetch(`/api/categories/${categoryID}`,
{
method: "PATCH",
body: JSON.stringify(toChange),
headers: { "Content-Type": "application/json" }
});
return response;
}
export async function deleteCategory(deleteAllItems, categoryID) {
const response = await fetch(`/api/categories/${categoryID}?deleteAllItems=${deleteAllItems}`, { method: "DELETE" });
if (response.status == 204) {
console.log(`deleted item ${categoryID}`);
}
return response;
return await fetch(`/api/categories/${categoryID}?deleteAllItems=${deleteAllItems}`, { method: "DELETE" });
}
@@ -1,7 +1,7 @@
export async function addItem(listID, itemName, itemAmount, categoryID) {
const newItem = await fetch(`/api/items`,
return await fetch(`/api/items`,
{
method: "POST",
body: JSON.stringify({
@@ -12,43 +12,29 @@ export async function addItem(listID, itemName, itemAmount, categoryID) {
}),
headers: { "Content-Type": "application/json" }
});
return await newItem.json();
}
export async function deleteItem(itemID) {
const response = await fetch(`/api/items/${itemID}`, { method: "DELETE" });
if (response.status == 204) {
console.log(`deleted item ${itemID}`);
}
return response;
return await fetch(`/api/items/${itemID}`, { method: "DELETE" });
}
export async function editItem(itemID, toChange) {
const response = await fetch(`/api/items/${itemID}`,
return await fetch(`/api/items/${itemID}`,
{
method: "PATCH",
body: JSON.stringify(toChange),
headers: { "Content-Type": "application/json" }
});
return response;
}
export async function deleteAllDoneItems(listID) {
const response = await fetch(`/api/lists/${listID}/items?done=true`, { method: "DELETE" });
return await fetch(`/api/lists/${listID}/items?done=true`, { method: "DELETE" });
if (response.status == 204) {
console.log(`items have been deleted`);
}
return response;
}
@@ -41,6 +41,17 @@ export function createEditItemForm(textElement) {
return editForm;
}
export function editItem(textElement, formElement, formData) {
let newName = formData.newItemName;
let newAmount = formData.newItemAmount;
textElement.querySelector(".item__textName").textContent = newName;
textElement.querySelector(".item__textAmount").textContent = newAmount;
formElement.replaceWith(textElement);
}
export function deleteItem(li) {
li.remove();
}
+69 -25
View File
@@ -9,16 +9,31 @@ const deleteAllDoneItemsButton = document.querySelector(".deleteAllDoneItemsButt
async function addItem(itemName, itemAmount, categoryID) {
console.log(` adding item with id:${currentList.id}, name: ${itemName}, amount: ${itemAmount}, category: ${categoryID}`)
const itemAsJSON = await api.addItem(currentList.id, itemName, itemAmount, categoryID);
console.log(`rendering frointend item: ${itemAsJSON}`);
ui.addItem(itemAsJSON);
const response = await api.addItem(currentList.id, itemName, itemAmount, categoryID);
const json = await response.json();
if (!response.ok) {
console.error(`Error, item couldnt be created ${json}`);
return;
}
console.log(`rendering frontend item: ${json}`);
ui.addItem(json);
}
async function addCategory(categoryName) {
console.log(`adding category ${categoryName}`)
const categoryAsJSON = await api.addCategory(currentList.id, categoryName);
console.log(categoryAsJSON);
ui.addCategory(categoryAsJSON);
const response = await api.addCategory(currentList.id, categoryName);
const json = await response.json();
if (!response.ok) {
console.error(`Error, category couldnt be created ${json}`)
return;
}
ui.addCategory(json);
return 0;
}
@@ -34,18 +49,20 @@ async function editItem(textElement) {
formElement.querySelector(".editForm__name").focus();
function save() {
async function save() {
let formData = Object.fromEntries(new FormData(formElement));
let newName = formData.newItemName;
let newAmount = formData.newItemAmount;
textElement.querySelector(".item__textName").textContent = newName;
textElement.querySelector(".item__textAmount").textContent = newAmount;
formElement.replaceWith(textElement);
console.log(`editing item ${id} with ${formData}`)
api.editItem(id, { itemName: newName, itemAmount: newAmount });
const response = await api.editItem(id, { itemName: formData.newName, itemAmount: formData.newAmount });
if (!response.ok) {
const json = await response.json();
console.error(`Error editingItem ${json}`);
return;
}
ui.editItem(textElement, formElement, formData);
}
formElement.addEventListener("submit", (event) => {
@@ -60,7 +77,7 @@ async function editItem(textElement) {
}
async function editCategory(categoryElement) {
function editCategory(categoryElement) {
//erstellen das Forms
//wir nutzen für das Element nur das div, weil sonst alle items mitgelöscht werden würden
const categoryDiv = categoryElement.querySelector(".category__div");
@@ -71,13 +88,21 @@ async function editCategory(categoryElement) {
formElement.querySelector(".editForm__name").focus();
function save() {
async function save() {
let formData = Object.fromEntries(new FormData(formElement));
ui.editCategory(id, formElement, formData, categoryDiv);
console.log(`editing catogory ${id} with ${formData}`)
api.editCategory(id, { categoryName: formData.newCategoryName });
const response = await api.editCategory(id, { categoryName: formData.newCategoryName });
if (!response.ok) {
const json = await response.json();
console.error(`Error editing category ${json}`);
return;
}
ui.editCategory(id, formElement, formData, categoryDiv);
}
formElement.addEventListener("submit", (event) => {
@@ -90,20 +115,39 @@ async function editCategory(categoryElement) {
})
}
function deleteItem(li) {
api.deleteItem(li.id);
async function deleteItem(li) {
const response = await api.deleteItem(li.id);
if (!response.ok) {
const json = await response.json();
console.error(`Error deleting item ${json}`);
return;
}
ui.deleteItem(li);
}
function deleteCategory(deleteAllItems, categoryID) {
async function deleteCategory(deleteAllItems, categoryID) {
console.log(`deleting category with allItems: ${deleteAllItems} id: ${categoryID}`);
api.deleteCategory(deleteAllItems, categoryID);
const response = await api.deleteCategory(deleteAllItems, categoryID);
if (!response.ok) {
const json = await response.json();
console.error(`Error deleting category ${json}`);
return;
}
ui.deleteCategory(deleteAllItems, categoryID);
}
function deleteAllDoneItems() {
async function deleteAllDoneItems() {
console.log(`deleting all done items...`)
api.deleteAllDoneItems(currentList.id);
const response = await api.deleteAllDoneItems(currentList.id);
if (!response.ok) {
const json = await response.json();
console.error(`Error deleting all done items ${json}`);
return;
}
ui.deleteAllDoneItems();
}