77import java .io .IOException ;
88import java .util .List ;
99import java .util .Set ;
10+ import org .springframework .http .HttpStatus ;
1011import org .springframework .http .ResponseEntity ;
1112import org .springframework .web .bind .annotation .CrossOrigin ;
13+ import org .springframework .web .bind .annotation .DeleteMapping ;
1214import org .springframework .web .bind .annotation .GetMapping ;
15+ import org .springframework .web .bind .annotation .PathVariable ;
16+ import org .springframework .web .bind .annotation .PostMapping ;
17+ import org .springframework .web .bind .annotation .RequestBody ;
1318import org .springframework .web .bind .annotation .RestController ;
1419
1520@ RestController
@@ -27,8 +32,43 @@ public MediaItemsController(Library library) throws IOException {
2732 @ GetMapping ("/items" )
2833 public ResponseEntity <GetMediaItemsResponse > getItems () {
2934 Set <MediaItem > items = library .search (SearchCriteria .builder ().build ());
35+ if (items .isEmpty ()) {
36+ return ResponseEntity .notFound ().build ();
37+ }
3038 List <MediaItemResponse > responseItems = items .stream ().map (MediaItemResponse ::from ).toList ();
3139 var response = GetMediaItemsResponse .builder ().items (responseItems ).build ();
3240 return ResponseEntity .ok (response );
3341 }
42+
43+ @ GetMapping ("/items/{id}" )
44+ public ResponseEntity <GetMediaItemsResponse > getItem (@ PathVariable ("id" ) String id ) {
45+ Set <MediaItem > items = library .search (SearchCriteria .builder ().id (id ).build ());
46+ if (items .isEmpty ()) {
47+ return ResponseEntity .notFound ().build ();
48+ }
49+ MediaItemResponse responseItem = MediaItemResponse .from (items .iterator ().next ());
50+ GetMediaItemsResponse response = GetMediaItemsResponse .builder ().item (responseItem ).build ();
51+ return ResponseEntity .ok (response );
52+ }
53+
54+ @ PostMapping ("/items" )
55+ public ResponseEntity <MediaItemResponse > postItem (@ RequestBody CreateMediaItemRequest request ) {
56+ MediaItemRequest item = request .getItem ();
57+ MediaItem response = MediaItemRequest .asMediaItem (item );
58+ MediaItemResponse itemResponse = MediaItemResponse .from (response );
59+ CreateMediaItemResponse createItemResponse =
60+ CreateMediaItemResponse .builder ().item (itemResponse ).build ();
61+ MediaItemResponse createdItem = createItemResponse .getItem ();
62+ return ResponseEntity .status (HttpStatus .CREATED ).body (createdItem );
63+ }
64+
65+ @ DeleteMapping ("/items/{id}" )
66+ public ResponseEntity <Void > deleteItem (@ PathVariable ("id" ) String id ) {
67+ Set <MediaItem > item = library .search (SearchCriteria .builder ().id (id ).build ());
68+ if (item .isEmpty ()) {
69+ return ResponseEntity .notFound ().build ();
70+ }
71+ library .removeMediaItem (item .iterator ().next (), librarian );
72+ return ResponseEntity .noContent ().build ();
73+ }
3474}
0 commit comments