44import com .codedifferently .lesson26 .library .Library ;
55import com .codedifferently .lesson26 .library .MediaItem ;
66import com .codedifferently .lesson26 .library .search .SearchCriteria ;
7+
78import java .io .IOException ;
89import java .util .List ;
910import java .util .Optional ;
1011import java .util .Set ;
1112import org .springframework .web .bind .annotation .CrossOrigin ;
1213import org .springframework .web .bind .annotation .GetMapping ;
1314import org .springframework .web .bind .annotation .RestController ;
15+ import org .springframework .web .server .ResponseStatusException ;
1416import org .springframework .web .bind .annotation .PostMapping ;
1517import org .springframework .web .bind .annotation .DeleteMapping ;
1618import org .springframework .web .bind .annotation .PathVariable ;
1719import org .springframework .web .bind .annotation .RequestBody ;
1820import org .springframework .web .bind .annotation .ResponseStatus ;
1921import org .springframework .http .HttpStatus ;
22+ import org .springframework .validation .annotation .Validated ;
2023
2124@ RestController
2225@ CrossOrigin
@@ -44,16 +47,17 @@ public MediaItemResponse getItem(@PathVariable String id) {
4447 if (item .isPresent ()) {
4548 return MediaItemResponse .from (item .get ());
4649 } else {
47- throw new IllegalArgumentException ( "Unknown media item ID: " + id );
50+ throw new ResponseStatusException ( HttpStatus . NOT_FOUND , "Unknown media item ID: " + id );
4851 }
4952 }
5053
5154 // POST a new item to /items
5255 @ PostMapping ("/items" )
53- public MediaItemResponse addItem (@ RequestBody CreateMediaItemRequest request ) {
56+ public MediaItemResponse addItem (@ RequestBody @ Validated CreateMediaItemRequest request ) {
57+ // Validate the request body and ensure fields are not empty
5458 MediaItemRequest mediaItemRequest = request .getItem ();
5559 MediaItem newItem = MediaItemRequest .asMediaItem (mediaItemRequest );
56- library .addMediaItem (newItem , librarian ); // Assuming the library has an addItem method
60+ library .addMediaItem (newItem , librarian );
5761 return MediaItemResponse .from (newItem );
5862 }
5963
@@ -63,9 +67,10 @@ public MediaItemResponse addItem(@RequestBody CreateMediaItemRequest request) {
6367 public void deleteItem (@ PathVariable String id ) {
6468 Set <MediaItem > items = library .search (SearchCriteria .builder ().id (id ).build ());
6569 if (items .isEmpty ()) {
66- throw new IllegalArgumentException ("This ID does not exsist to delete! ID: " + id );
70+ // Return 404 Not Found if item doesn't exist
71+ throw new ResponseStatusException (HttpStatus .NOT_FOUND , "Item not found for deletion: " + id );
6772 }
6873 MediaItem itemToDelete = items .iterator ().next ();
69- library .removeMediaItem (itemToDelete , librarian ); // Assuming the library has a removeItem method
74+ library .removeMediaItem (itemToDelete , librarian );
7075 }
7176}
0 commit comments