|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+package io.zipcoder.tc_spring_poll_application.controllers;
|
|
|
2
|
+
|
|
|
3
|
+import io.zipcoder.tc_spring_poll_application.domain.Vote;
|
|
|
4
|
+import io.zipcoder.tc_spring_poll_application.repositories.VoteRepository;
|
|
|
5
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
6
|
+import org.springframework.http.HttpHeaders;
|
|
|
7
|
+import org.springframework.http.HttpStatus;
|
|
|
8
|
+import org.springframework.http.ResponseEntity;
|
|
|
9
|
+import org.springframework.web.bind.annotation.*;
|
|
|
10
|
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
|
|
11
|
+
|
|
|
12
|
+import java.net.URI;
|
|
|
13
|
+
|
|
|
14
|
+/**
|
|
|
15
|
+ * project: spring-demo
|
|
|
16
|
+ * package: io.zipcoder.tc_spring_poll_application.controllers
|
|
|
17
|
+ * author: https://github.com/vvmk
|
|
|
18
|
+ * date: 4/6/18
|
|
|
19
|
+ */
|
|
|
20
|
+@RestController
|
|
|
21
|
+public class VoteController {
|
|
|
22
|
+ private VoteRepository voteRepository;
|
|
|
23
|
+
|
|
|
24
|
+ @Autowired
|
|
|
25
|
+ public VoteController(VoteRepository voteRepository) {
|
|
|
26
|
+ this.voteRepository = voteRepository;
|
|
|
27
|
+ }
|
|
|
28
|
+
|
|
|
29
|
+ @RequestMapping(value = "/polls/{pollId}/votes", method = RequestMethod.POST)
|
|
|
30
|
+ public ResponseEntity<Vote> createVote(@PathVariable Long pollId, @RequestBody Vote vote) {
|
|
|
31
|
+ vote = voteRepository.save(vote);
|
|
|
32
|
+
|
|
|
33
|
+ //
|
|
|
34
|
+ URI newVoteUri;
|
|
|
35
|
+ try {
|
|
|
36
|
+ newVoteUri = ServletUriComponentsBuilder
|
|
|
37
|
+ .fromCurrentRequest()
|
|
|
38
|
+ .path("/{id}")
|
|
|
39
|
+ .buildAndExpand(vote.getId())
|
|
|
40
|
+ .toUri();
|
|
|
41
|
+
|
|
|
42
|
+ } catch (IllegalStateException ise) {
|
|
|
43
|
+ newVoteUri = ServletUriComponentsBuilder
|
|
|
44
|
+ .fromUriString("http://roflmao:69/polls")
|
|
|
45
|
+ .path("/{id}")
|
|
|
46
|
+ .buildAndExpand(vote.getId())
|
|
|
47
|
+ .toUri();
|
|
|
48
|
+ }
|
|
|
49
|
+
|
|
|
50
|
+ //
|
|
|
51
|
+ HttpHeaders responseHeaders = new HttpHeaders();
|
|
|
52
|
+ responseHeaders.setLocation(newVoteUri);
|
|
|
53
|
+
|
|
|
54
|
+ return new ResponseEntity<>(vote, responseHeaders, HttpStatus.CREATED);
|
|
|
55
|
+ }
|
|
|
56
|
+}
|