7
7
import java .io .IOException ;
8
8
import java .util .List ;
9
9
import java .util .Set ;
10
+ import org .springframework .http .HttpStatus ;
10
11
import org .springframework .http .ResponseEntity ;
11
12
import org .springframework .web .bind .annotation .CrossOrigin ;
13
+ import org .springframework .web .bind .annotation .DeleteMapping ;
12
14
import 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 ;
13
18
import org .springframework .web .bind .annotation .RestController ;
14
19
15
20
@ RestController
@@ -27,8 +32,43 @@ public MediaItemsController(Library library) throws IOException {
27
32
@ GetMapping ("/items" )
28
33
public ResponseEntity <GetMediaItemsResponse > getItems () {
29
34
Set <MediaItem > items = library .search (SearchCriteria .builder ().build ());
35
+ if (items .isEmpty ()) {
36
+ return ResponseEntity .notFound ().build ();
37
+ }
30
38
List <MediaItemResponse > responseItems = items .stream ().map (MediaItemResponse ::from ).toList ();
31
39
var response = GetMediaItemsResponse .builder ().items (responseItems ).build ();
32
40
return ResponseEntity .ok (response );
33
41
}
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
+ }
34
74
}
0 commit comments