2020-06-11 19:13:29 +07:00
|
|
|
package com.cubetiqs.demo.rest;
|
|
|
|
|
|
|
|
import com.cubetiqs.demo.domain.UserEntity;
|
|
|
|
import com.cubetiqs.demo.repository.UserRepository;
|
2020-06-16 19:19:26 +07:00
|
|
|
import com.cubetiqs.demo.service.UserService;
|
2020-06-11 19:13:29 +07:00
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
|
import org.springframework.data.domain.Pageable;
|
2020-06-15 19:38:02 +07:00
|
|
|
import org.springframework.http.HttpStatus;
|
|
|
|
import org.springframework.http.ResponseEntity;
|
2020-06-11 19:13:29 +07:00
|
|
|
import org.springframework.web.bind.annotation.*;
|
|
|
|
|
2020-06-16 19:19:26 +07:00
|
|
|
import java.util.List;
|
2020-06-15 19:38:02 +07:00
|
|
|
import java.util.Optional;
|
2020-06-11 19:13:29 +07:00
|
|
|
|
|
|
|
@RestController
|
|
|
|
@RequestMapping(path = {"/users"})
|
|
|
|
public class UserController {
|
|
|
|
private final UserRepository userRepository;
|
2020-06-16 19:19:26 +07:00
|
|
|
private final UserService userService;
|
2020-06-11 19:13:29 +07:00
|
|
|
|
|
|
|
@Autowired
|
2020-06-16 19:19:26 +07:00
|
|
|
public UserController(UserRepository userRepository, UserService userService) {
|
2020-06-11 19:13:29 +07:00
|
|
|
this.userRepository = userRepository;
|
2020-06-16 19:19:26 +07:00
|
|
|
this.userService = userService;
|
2020-06-11 19:13:29 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
@GetMapping
|
2020-06-16 19:19:26 +07:00
|
|
|
public List<UserEntity> getAllUsers(Pageable pageable) {
|
2020-06-17 17:54:21 +07:00
|
|
|
return userService.findAll();
|
2020-06-11 19:13:29 +07:00
|
|
|
}
|
|
|
|
|
2020-06-15 19:38:02 +07:00
|
|
|
@GetMapping("/{id}")
|
|
|
|
public UserEntity getUserById(
|
|
|
|
@PathVariable Long id
|
|
|
|
) {
|
|
|
|
return userRepository.findById(id).orElse(null);
|
|
|
|
}
|
|
|
|
|
2020-06-11 19:13:29 +07:00
|
|
|
@PostMapping
|
|
|
|
public UserEntity createUser(
|
|
|
|
@RequestBody UserEntity user
|
|
|
|
) {
|
|
|
|
return userRepository.save(user);
|
|
|
|
}
|
2020-06-15 19:38:02 +07:00
|
|
|
|
|
|
|
@PutMapping("/{id}")
|
|
|
|
public UserEntity updateUser(
|
|
|
|
@PathVariable Long id,
|
|
|
|
@RequestBody UserEntity user
|
|
|
|
) {
|
|
|
|
Optional<UserEntity> userEntityOptional = userRepository.findById(id);
|
|
|
|
if(userEntityOptional.isPresent()) {
|
|
|
|
// found
|
|
|
|
user.setId(id);
|
|
|
|
return userRepository.save(user);
|
|
|
|
} else {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@DeleteMapping("/{id}")
|
|
|
|
public ResponseEntity<Object> deleteUser(
|
|
|
|
@PathVariable Long id
|
|
|
|
) {
|
|
|
|
Optional<UserEntity> userEntityOptional = userRepository.findById(id);
|
|
|
|
if (userEntityOptional.isPresent()) {
|
|
|
|
userRepository.delete(userEntityOptional.get());
|
|
|
|
return ResponseEntity.status(HttpStatus.OK).body("user deleted");
|
|
|
|
} else {
|
|
|
|
return ResponseEntity.badRequest().body("not found");
|
|
|
|
}
|
|
|
|
}
|
2020-06-11 19:13:29 +07:00
|
|
|
}
|