Skip to content

Commit 3a82490

Browse files
author
jjcapparell
committed
feat: added GET, POST, and Delete method for Lesson 26 API
1 parent 70f0765 commit 3a82490

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

lesson_26/api/java/api_app/src/main/java/com/codedifferently/lesson26/web/MediaItemsController.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import com.codedifferently.lesson26.library.search.SearchCriteria;
77
import java.io.IOException;
88
import java.util.List;
9+
import java.util.Optional;
910
import java.util.Set;
1011
import org.springframework.web.bind.annotation.CrossOrigin;
1112
import org.springframework.web.bind.annotation.GetMapping;
@@ -29,4 +30,35 @@ public GetMediaItemsResponse getItems() {
2930
var response = GetMediaItemsResponse.builder().items(responseItems).build();
3031
return response;
3132
}
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+
}
3264
}

0 commit comments

Comments
 (0)