6
6
import com .codedifferently .lesson26 .library .search .SearchCriteria ;
7
7
import java .io .IOException ;
8
8
import java .util .List ;
9
+ import java .util .Optional ;
9
10
import java .util .Set ;
10
11
import org .springframework .web .bind .annotation .CrossOrigin ;
11
12
import org .springframework .web .bind .annotation .GetMapping ;
@@ -29,4 +30,35 @@ public GetMediaItemsResponse getItems() {
29
30
var response = GetMediaItemsResponse .builder ().items (responseItems ).build ();
30
31
return response ;
31
32
}
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
+ }
32
64
}
0 commit comments