66import com .codedifferently .lesson26 .library .search .SearchCriteria ;
77import java .io .IOException ;
88import java .util .List ;
9+ import java .util .Optional ;
910import java .util .Set ;
1011import org .springframework .web .bind .annotation .CrossOrigin ;
1112import org .springframework .web .bind .annotation .GetMapping ;
@@ -29,4 +30,35 @@ public GetMediaItemsResponse getItems() {
2930 var response = GetMediaItemsResponse .builder ().items (responseItems ).build ();
3031 return response ;
3132 }
33+
34+ // GET a single item by its ID
35+ @ GetMapping ("/items/{id}" )
36+ public MediaItemResponse getItem (@ PathVariable String id ) {
37+ Optional <MediaItem > item = library .search (SearchCriteria .builder ().id (id ).build ()).stream ().findFirst ();
38+ if (item .isPresent ()) {
39+ return MediaItemResponse .from (item .get ());
40+ } else {
41+ throw new ItemNotFoundException (id );
42+ }
43+ }
44+
45+ // POST a new item to /items
46+ @ PostMapping ("/items" )
47+ public MediaItemResponse addItem (@ RequestBody AddMediaItemRequest request ) {
48+ MediaItem newItem = request .toMediaItem ();
49+ library .addItem (newItem ); // Assuming the library has an addItem method
50+ return MediaItemResponse .from (newItem );
51+ }
52+
53+ // DELETE an item by its ID
54+ @ DeleteMapping ("/items/{id}" )
55+ @ ResponseStatus (HttpStatus .NO_CONTENT ) // No content when successfully deleted
56+ public void deleteItem (@ PathVariable String id ) {
57+ Set <MediaItem > items = library .search (SearchCriteria .builder ().id (id ).build ());
58+ if (items .isEmpty ()) {
59+ throw new ItemNotFoundException (id );
60+ }
61+ MediaItem itemToDelete = items .iterator ().next ();
62+ library .removeItem (itemToDelete ); // Assuming the library has a removeItem method
63+ }
3264}
0 commit comments