Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Added functions postItems, getMediaItem, and deleteMediaItem #362

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,20 @@
import com.codedifferently.lesson16.library.Library;
import com.codedifferently.lesson16.library.MediaItem;
import com.codedifferently.lesson16.library.search.SearchCriteria;
import jakarta.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

@RestController
public class MediaItemsController {
Expand All @@ -27,4 +36,31 @@ public GetMediaItemsResponse getItems() {
var response = GetMediaItemsResponse.builder().items(responseItems).build();
return response;
}

@PostMapping("/items")
public CreateMediaItemResponse postItem(@Valid @RequestBody CreateMediaItemRequest req) {
MediaItem media = MediaItemRequest.asMediaItem(req.getItem());
library.addMediaItem(media, librarian);
return CreateMediaItemResponse.builder().item(MediaItemResponse.from(media)).build();
}

@GetMapping("/items/{id}")
public GetMediaItemsResponse getMediaItem(@PathVariable String id) {
Set<MediaItem> items = library.search(SearchCriteria.builder().id(id).build());
if (items.isEmpty()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Media item not found");
}
List<MediaItemResponse> responseItems = items.stream().map(MediaItemResponse::from).toList();
var response = GetMediaItemsResponse.builder().items(responseItems).build();
return response;
}

@DeleteMapping("/items/{id}")
public ResponseEntity<Void> deleteMediaItem(@PathVariable String id) {
Moibrahi7 marked this conversation as resolved.
Show resolved Hide resolved
if (!library.hasMediaItem(UUID.fromString(id))) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Media item not found");
Moibrahi7 marked this conversation as resolved.
Show resolved Hide resolved
}
library.removeMediaItem(UUID.fromString(id), librarian);
return ResponseEntity.noContent().build();
}
}