Skip to content

Lesson16 #394

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

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.codedifferently.lesson16.web;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class CreatePatronRequest {
@NotNull(message = "item is required") @Valid
private PatronRequest patron;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.codedifferently.lesson16.web;

import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class CreatePatronResponse {
private PatronResponse patron;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.codedifferently.lesson16.web;

import java.util.List;
import lombok.Builder;
import lombok.Data;
import lombok.Singular;

@Data
@Builder
public class GetPatronResponse {
@Singular private List<PatronResponse> patronResponses;
}


Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.codedifferently.lesson16.web;

import java.util.List;
import lombok.Builder;
import lombok.Data;
import lombok.Singular;

@Data
@Builder
public class GetPatronsResponse {
@Singular private List<PatronResponse> patronResponses;
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,13 @@
import com.codedifferently.lesson16.library.search.SearchCriteria;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.springframework.web.bind.annotation.CrossOrigin;
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;

@RestController
Expand All @@ -29,4 +33,28 @@ public GetMediaItemsResponse getItems() {
var response = GetMediaItemsResponse.builder().items(responseItems).build();
return response;
}

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

@GetMapping("/items/{id}")
public ResponseEntity<MediaItemResponse> getItem(@PathVariable UUID id) {
Optional<MediaItem> item =
library.search(SearchCriteria.builder().id(id.toString()).build()).stream().findFirst();

if (item.isEmpty()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(MediaItemResponse.from(item.get()));
}

@DeleteMapping("/items/{id}")
public ResponseEntity<Void> deleteItem(@PathVariable("id") UUID id) {
library.removeMediaItem(id, librarian);
return ResponseEntity.noContent().build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package com.codedifferently.lesson16.web;

public class PatronRequest {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.codedifferently.lesson16.web;

import com.codedifferently.lesson16.library.LibraryGuest;
import java.util.UUID;
import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class PatronResponse {
private UUID id;
private String name;
private String email;

public static PatronResponse from(LibraryGuest guest) {
return PatronResponse.builder()
.id(guest.getId())
.name(guest.getName())
.email(guest.getEmail())
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.codedifferently.lesson16.web;

import com.codedifferently.lesson16.library.Librarian;
import com.codedifferently.lesson16.library.Library;
import com.codedifferently.lesson16.library.LibraryGuest;
import com.codedifferently.lesson16.library.Patron;
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.*;

@RestController
public class PatronsController {
private final Library library;
private final Librarian librarian;

public PatronsController(Library library) throws IOException {
this.library = library;
this.librarian = library.getLibrarians().stream().findFirst().orElseThrow();
}

@GetMapping("/patrons")
public ResponseEntity<GetPatronsResponse> getPatrons() {
Set<LibraryGuest> guests = library.getPatrons();
List<PatronResponse> patrons = guests.stream().map(PatronResponse::from).toList();
var response = GetPatronsResponse.builder().patrons(patrons).build();
return ResponseEntity.ok(response);
}

@PostMapping("/patrons")
public ResponseEntity<GetPatronsResponse> addPatron(@RequestBody PatronRequest patronRequest) {
Patron patron = PatronRequest.toPatron(patronRequest);
library.addLibraryGuest(patron);
return ResponseEntity.status(HttpStatus.CREATED).body(GetPatronsResponse.from(patron));
}

@GetMapping("/patrons/{id}")
public ResponseEntity<PatronResponse> getPatron(@PathVariable UUID id) {
Patron patron = library.getPatrons(id);
if (patron == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(PatronResponse.from(patron));
}

@DeleteMapping("/patrons/{id}")
public ResponseEntity<Void> deletePatron(@PathVariable UUID id) {
Patron patron = library.getPatrons(id);
if (patron == null) {
return ResponseEntity.notFound().build();
}
library.removeLibraryGuest(patron);
return ResponseEntity.noContent().build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package com.codedifferently.lesson16.web;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import com.codedifferently.lesson16.Lesson16;
import com.codedifferently.lesson16.library.Library;
import com.codedifferently.lesson16.library.Patron;
import com.codedifferently.lesson16.library.search.PatronSearchCriteria;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest
@ContextConfiguration(classes = Lesson16.class)
class PatronsControllerTest {

private static MockMvc mockMvc;
@Autowired private Library library;

@BeforeEach
void setUp() {}

@Test
void testController_getsAllPatrons() throws Exception {
mockMvc
.perform(get("/patrons").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.patrons").isArray());
}

@Test
void testController_getsAPatron() throws Exception {
Patron patron = new Patron("John Doe");
library.addLibraryGuest(patron);

mockMvc
.perform(get("/patrons/{id}", patron.getId()).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}

@Test
void testController_returnsNotFoundOnGetPatron() throws Exception {
mockMvc
.perform(get("/patrons/{id}", "00000").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}

@Test
void testController_reportsBadRequestOnAddPatron() throws Exception {
String json = "{}";

mockMvc
.perform(post("/patrons").contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors").isArray())
.andExpect(jsonPath("$.errors.length()").value(1));
}

@Test
void testController_addsPatron() throws Exception {
String json = "{\"name\": \"John Doe\"}";

mockMvc
.perform(post("/patrons").contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.patron.id").isString());

Set<Patron> patrons =
library.searchPatrons(PatronSearchCriteria.builder().name("John Doe").build());
assertThat(patrons).hasSize(1);
}

@Test
void testController_returnsNotFoundOnDeletePatron() throws Exception {
mockMvc
.perform(delete("/patrons/{id}", "00000").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}

@Test
void testController_deletesPatron() throws Exception {
Patron patron = new Patron("John Doe");
library.addLibraryGuest(patron);

mockMvc
.perform(delete("/patrons/{id}", patron.getId()).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());

Set<Patron> patrons =
library.searchPatrons(PatronSearchCriteria.builder().id(patron.getId().toString()).build());
assertThat(patrons).hasSize(0);
}
}