|
| 1 | +package com.codedifferently.lesson26.web; |
| 2 | + |
| 3 | +import com.codedifferently.lesson26.library.Librarian; |
| 4 | +import com.codedifferently.lesson26.library.Library; |
| 5 | +import com.codedifferently.lesson26.library.search.SearchCriteria; |
| 6 | +import jakarta.validation.Valid; |
| 7 | +import java.util.UUID; |
| 8 | +import org.springframework.http.ResponseEntity; |
| 9 | +import org.springframework.web.bind.annotation.*; |
| 10 | + |
| 11 | +@RestController |
| 12 | +@RequestMapping("/items") |
| 13 | +@CrossOrigin |
| 14 | +public class MediaItemController { |
| 15 | + |
| 16 | + private final Library library; |
| 17 | + private final Librarian librarian; |
| 18 | + |
| 19 | + public MediaItemController(Library library, Librarian librarian) { |
| 20 | + this.library = library; |
| 21 | + this.librarian = librarian; |
| 22 | + } |
| 23 | + |
| 24 | + @GetMapping |
| 25 | + public GetMediaItemsResponse getItems() { |
| 26 | + var items = library.search(SearchCriteria.builder().build()); |
| 27 | + var responseItems = items.stream().map(MediaItemResponse::from).toList(); |
| 28 | + return GetMediaItemsResponse.builder().items(responseItems).build(); |
| 29 | + } |
| 30 | + |
| 31 | + @GetMapping("/{id}") |
| 32 | + public ResponseEntity<MediaItemResponse> getItemById(@PathVariable UUID id) { |
| 33 | + var criteria = SearchCriteria.builder().id(id.toString()).build(); |
| 34 | + var results = library.search(criteria); |
| 35 | + return results.isEmpty() |
| 36 | + ? ResponseEntity.notFound().build() |
| 37 | + : ResponseEntity.ok(MediaItemResponse.from(results.iterator().next())); |
| 38 | + } |
| 39 | + |
| 40 | + @PostMapping |
| 41 | + public CreateMediaItemResponse addItem(@Valid @RequestBody CreateMediaItemRequest request) { |
| 42 | + var item = MediaItemRequest.asMediaItem(request.getItem()); |
| 43 | + library.addMediaItem(item, librarian); |
| 44 | + var response = getItemById(item.getId()).getBody(); |
| 45 | + return CreateMediaItemResponse.builder().item(response).build(); |
| 46 | + } |
| 47 | + |
| 48 | + @DeleteMapping("/{id}") |
| 49 | + public ResponseEntity<Void> deleteItem(@PathVariable UUID id) { |
| 50 | + var criteria = SearchCriteria.builder().id(id.toString()).build(); |
| 51 | + var results = library.search(criteria); |
| 52 | + if (results.isEmpty()) return ResponseEntity.notFound().build(); |
| 53 | + |
| 54 | + library.removeMediaItem(results.iterator().next(), librarian); |
| 55 | + return ResponseEntity.noContent().build(); |
| 56 | + } |
| 57 | +} |
0 commit comments