Browse Source

Part 3.2 - Create class VoteController

Nick Satinover 5 years ago
parent
commit
a49a2bb4c1

+ 33
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controllers/VoteController.java View File

@@ -0,0 +1,33 @@
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
+@RestController
13
+public class VoteController {
14
+
15
+    @Autowired
16
+    VoteRepository voteRepository;
17
+
18
+    VoteController(@Autowired VoteRepository voteRepository){
19
+        this.voteRepository = voteRepository;
20
+    }
21
+
22
+    @RequestMapping(value = "/polls/{pollId}/votes", method = RequestMethod.POST)
23
+    public ResponseEntity<?> createVote(@PathVariable Long pollId, @RequestBody Vote vote){
24
+        vote = voteRepository.save(vote);
25
+        HttpHeaders responseHeaders = new HttpHeaders();
26
+        responseHeaders.setLocation(ServletUriComponentsBuilder
27
+            .fromCurrentRequest()
28
+            .path("{id}")
29
+            .buildAndExpand(vote.getId())
30
+            .toUri());
31
+        return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED);
32
+    }
33
+}