- URI for Location Header
- CRUD - create
This commit is contained in:
djmil 2023-07-21 12:38:51 +02:00
parent 38f86076c2
commit 19aa42941f
2 changed files with 37 additions and 0 deletions

View File

@ -2,10 +2,14 @@ package djmil.cashcard;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
import java.util.Optional;
@RestController
@ -28,4 +32,15 @@ public class CashCardController {
return ResponseEntity.notFound().build();
}
}
@PostMapping
private ResponseEntity<Void> createCashCard(@RequestBody CashCard newCashCardRequest, UriComponentsBuilder ucb) {
CashCard savedCashCard = cashCardRepository.save(newCashCardRequest); // CRUD - Create
URI locationOfNewCashCard = ucb
.path("cashcards/{id}")
.buildAndExpand(savedCashCard.id())
.toUri();
return ResponseEntity.created(locationOfNewCashCard).build();
}
}

View File

@ -11,6 +11,8 @@ import org.springframework.http.ResponseEntity;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import java.net.URI;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ -45,4 +47,24 @@ class CashcardApplicationTests {
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(response.getBody()).isBlank();
}
@Test
void shouldCreateANewCashCard() {
CashCard newCashCard = new CashCard(null, 250.00);
ResponseEntity<Void> createResponse = restTemplate.postForEntity("/cashcards", newCashCard, Void.class );
assertThat(createResponse.getStatusCode()).isEqualTo(HttpStatus.CREATED);
URI locationOfNewCashCard = createResponse.getHeaders().getLocation();
ResponseEntity<String> getResponse = restTemplate.getForEntity(locationOfNewCashCard, String.class);
assertThat(getResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
// Validate created CashCard JSON
DocumentContext documentContext = JsonPath.parse(getResponse.getBody());
Number id = documentContext.read("$.id");
Double amount = documentContext.read("$.amount");
assertThat(id).isNotNull();
assertThat(amount).isEqualTo(250.00);
}
}