Guest User

QuestionController.java

a guest
Feb 27th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. package com.example.apidemo.controller;
  2.  
  3. import com.example.apidemo.exception.ResourceNotFoundException;
  4. import com.example.apidemo.model.Question;
  5. import com.example.apidemo.repository.QuestionRepository;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.data.domain.Page;
  8. import org.springframework.data.domain.Pageable;
  9. import org.springframework.http.ResponseEntity;
  10. import org.springframework.web.bind.annotation.*;
  11. import javax.validation.Valid;
  12.  
  13. @RestController
  14. public class QuestionController {
  15.    
  16.     @Autowired
  17.     private QuestionRepository questionRepository;
  18.    
  19.     @GetMapping("/questions")
  20.     public Page<Question> getQuestions(Pageable pageable) {
  21.         return questionRepository.findAll(pageable);
  22.     }
  23.    
  24.     @PostMapping("/questions")
  25.     public Question createQuestion(@Valid @RequestBody Question question) {
  26.         return questionRepository.save(question);
  27.     }
  28.    
  29.     @PutMapping("/questions/{questionId}")
  30.     public Question updateQuestion(@PathVariable Long questionId, @Valid @RequestBody Question questionRequest) {
  31.         return questionRepository.findById(questionId)
  32.                 .map(question -> {
  33.                     question.setTitle(questionRequest.getTitle());
  34.                     question.setDescription(questionRequest.getDescription());
  35.                     return questionRepository.save(question);
  36.                 }).orElseThrow(() -> new ResourceNotFoundException("Question not found with id " + questionId));
  37.     }
  38.  
  39.     @DeleteMapping("/questions/{questionId}")
  40.     public ResponseEntity<?> deleteQuestion(@PathVariable Long questionId) {
  41.         return questionRepository.findById(questionId)
  42.                 .map(question -> {
  43.                     questionRepository.delete(question);
  44.                     return ResponseEntity.ok().build();
  45.                 }).orElseThrow(() -> new ResourceNotFoundException("Question not found with id " + questionId));
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment