4
4
import com .codedifferently .lesson26 .library .Library ;
5
5
import com .codedifferently .lesson26 .library .MediaItem ;
6
6
import com .codedifferently .lesson26 .library .search .SearchCriteria ;
7
+ import io .swagger .v3 .oas .annotations .parameters .RequestBody ;
7
8
import java .io .IOException ;
8
9
import java .util .List ;
10
+ import java .util .Map ;
9
11
import java .util .Set ;
12
+ import org .springframework .http .HttpStatus ;
13
+ import org .springframework .http .ResponseEntity ;
10
14
import org .springframework .web .bind .annotation .CrossOrigin ;
11
15
import org .springframework .web .bind .annotation .GetMapping ;
16
+ import org .springframework .web .bind .annotation .PathVariable ;
17
+ import org .springframework .web .bind .annotation .PostMapping ;
12
18
import org .springframework .web .bind .annotation .RestController ;
13
19
14
20
@ RestController
@@ -29,4 +35,37 @@ public GetMediaItemsResponse getItems() {
29
35
var response = GetMediaItemsResponse .builder ().items (responseItems ).build ();
30
36
return response ;
31
37
}
38
+
39
+ // Get item
40
+ @ GetMapping ("/items/{id}" )
41
+ public ResponseEntity <MediaItemResponse > getItem (@ PathVariable String id ) {
42
+ SearchCriteria criteria = SearchCriteria .builder ().id (id ).build ();
43
+ Set <MediaItem > items = library .search (criteria );
44
+ if (items .isEmpty ()) {
45
+ return ResponseEntity .status (HttpStatus .NOT_FOUND ).build ();
46
+ }
47
+ {
48
+ MediaItem item = items .iterator ().next ();
49
+ return ResponseEntity .ok (MediaItemResponse .from (item ));
50
+ }
51
+ }
52
+
53
+ // post item
54
+ @ PostMapping ("/items" )
55
+ public ResponseEntity <?> addsItem (@ RequestBody CreateMediaItemRequest request ) {
56
+ if (request == null || request .getItem () == null ) {
57
+ return ResponseEntity .status (HttpStatus .BAD_REQUEST ).body ("Missing item in the body" );
58
+ }
59
+ try {
60
+ MediaItem newItem = MediaItemRequest .asMediaItem (request .getItem ());
61
+
62
+ library .addMediaItem (newItem , librarian );
63
+
64
+ return ResponseEntity .ok (Map .of ("item" , MediaItemResponse .from (newItem )));
65
+ } catch (IllegalArgumentException e ) {
66
+ return ResponseEntity .status (HttpStatus .BAD_REQUEST ).body (e .getMessage ());
67
+ }
68
+ }
32
69
}
70
+
71
+ // Delete
0 commit comments