-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathPollController.java
More file actions
58 lines (48 loc) · 2.27 KB
/
PollController.java
File metadata and controls
58 lines (48 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.example.polls.controller;
import com.example.polls.model.*;
import com.example.polls.payload.*;
import com.example.polls.security.CurrentUser;
import com.example.polls.security.UserPrincipal;
import com.example.polls.service.PollService;
import com.example.polls.util.AppConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.validation.Valid;
import java.net.URI;
@RestController
@RequestMapping("/api/polls")
public class PollController {
@Autowired
private PollService pollService;
@GetMapping
public PagedResponse<PollResponse> getPolls(@CurrentUser UserPrincipal currentUser,
@RequestParam(value = "page", defaultValue = AppConstants.DEFAULT_PAGE_NUMBER) int page,
@RequestParam(value = "size", defaultValue = AppConstants.DEFAULT_PAGE_SIZE) int size) {
return pollService.getAllPolls(currentUser, page, size);
}
@PostMapping
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> createPoll(@Valid @RequestBody PollRequest pollRequest) {
Poll poll = pollService.createPoll(pollRequest);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest().path("/{pollId}")
.buildAndExpand(poll.getId()).toUri();
return ResponseEntity.created(location)
.body(new ApiResponse(true, "Poll Created Successfully"));
}
@GetMapping("/{pollId}")
public PollResponse getPollById(@CurrentUser UserPrincipal currentUser,
@PathVariable Long pollId) {
return pollService.getPollById(pollId, currentUser);
}
@PostMapping("/{pollId}/votes")
@PreAuthorize("hasRole('USER')")
public PollResponse castVote(@CurrentUser UserPrincipal currentUser,
@PathVariable Long pollId,
@Valid @RequestBody VoteRequest voteRequest) {
return pollService.castVoteAndGetUpdatedPoll(pollId, voteRequest, currentUser);
}
}