2019-07-20 18:21:14 +09:00

64 lines
2.3 KiB
Java

package com.totopia.server.user.controller;
import com.totopia.server.commons.base.exception.ResourceNotFoundException;
import com.totopia.server.user.model.User;
import com.totopia.server.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@PostMapping(value = "/users")
@ResponseStatus(code = HttpStatus.CREATED)
public User save(@RequestBody User user) {
return userRepository.save(user);
}
@GetMapping(value = "/users")
public Page<User> all(Pageable pageable) {
return userRepository.findAll(pageable);
}
@GetMapping(value = "/users/{userId}")
public User findByUserId(@PathVariable Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User [userId=" + userId + "] can't be found"));
}
@DeleteMapping(value = "/users/{userId}")
public ResponseEntity<?> deleteUser(@PathVariable Long userId) {
return userRepository.findById(userId).map(user -> {
userRepository.delete(user);
return ResponseEntity.ok().build();
}).orElseThrow(() -> new ResourceNotFoundException("User [userId=" + userId + "] can't be found"));
}
@PutMapping(value = "/users/{userId}")
public ResponseEntity<User> updateUser(@PathVariable Long userId, @RequestBody User newUser) {
return userRepository.findById(userId).map(user -> {
userRepository.save(user);
return ResponseEntity.ok(user);
}).orElseThrow(() -> new ResourceNotFoundException("User [userId=" + userId + "] can't be found"));
}
}