[Practice] 사용자 API 만들기 (7)
2021. 4. 14. 00:01ㆍSpring/Practice
1. 문제
- 사용자 비밀번호를 수정하는 API
- 이전 비밀번호와 일치하는 경우 수정
- 일치하지 않을 경우 PasswordNotMatchException 발생
- 발생 메시지는 "비밀번호가 일치하지 않습니다."
2. 풀이
- PasswordNotMatchException.java
package com.example.jpa.sample.user.exception;
public class PasswordNotMatchException extends RuntimeException {
public PasswordNotMatchException(String message) {
super(message);
}
}
- ApiUserController.java
package com.example.jpa.sample.user.controller;
import com.example.jpa.sample.notice.entity.Notice;
import com.example.jpa.sample.notice.model.NoticeResponse;
import com.example.jpa.sample.notice.model.ResponseError;
import com.example.jpa.sample.notice.repository.NoticeRepository;
import com.example.jpa.sample.user.entity.User;
import com.example.jpa.sample.user.exception.ExistsEmailException;
import com.example.jpa.sample.user.exception.PasswordNotMatchException;
import com.example.jpa.sample.user.exception.UserNotFoundException;
import com.example.jpa.sample.user.model.UserInput;
import com.example.jpa.sample.user.model.UserInputPassword;
import com.example.jpa.sample.user.model.UserResponse;
import com.example.jpa.sample.user.model.UserUpdate;
import com.example.jpa.sample.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@RequiredArgsConstructor
@RestController
public class ApiUserController {
private final UserRepository userRepository;
private final NoticeRepository noticeRepository;
/*
// 문제 1
@PostMapping("/api/user")
public ResponseEntity<?> addUser(@RequestBody @Valid UserInput userInput, Errors errors) {
List<ResponseError> responseErrorList = new ArrayList<>();
if(errors.hasErrors()) {
errors.getAllErrors().forEach(e -> {
responseErrorList.add(ResponseError.of((FieldError)e));
});
return new ResponseEntity<>(responseErrorList, HttpStatus.BAD_REQUEST);
}
// return ResponseEntity.ok().build();
return new ResponseEntity<>(HttpStatus.OK);
}
*/
/*
// 문제 2
@PostMapping("/api/user")
public ResponseEntity<?> addUser(@RequestBody @Valid UserInput userInput, Errors errors) {
List<ResponseError> responseErrorList = new ArrayList<>();
if(errors.hasErrors()) {
errors.getAllErrors().forEach(e -> {
responseErrorList.add(ResponseError.of((FieldError)e));
});
return new ResponseEntity<>(responseErrorList, HttpStatus.BAD_REQUEST);
}
userRepository.save(User.builder()
.email(userInput.getEmail())
.name(userInput.getName())
.password(userInput.getPassword())
.phone(userInput.getPhone())
.regDate(LocalDateTime.now())
.build()
);
return new ResponseEntity<>(HttpStatus.OK);
}
*/
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<?> handlerUserNotFoundException(UserNotFoundException exception) {
return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
// 문제 3
@PutMapping("/api/user/{id}")
public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody @Valid UserUpdate userUpdate, Errors errors) {
List<ResponseError> responseErrorList = new ArrayList<>();
if(errors.hasErrors()) {
errors.getAllErrors().forEach(e -> {
responseErrorList.add(ResponseError.of((FieldError)e));
});
return new ResponseEntity<>(responseErrorList, HttpStatus.BAD_REQUEST);
}
User user = userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("사용자 정보가 없습니다."));
user.setPhone(userUpdate.getPhone());
user.setUpdateDate(LocalDateTime.now());
userRepository.save(user);
return ResponseEntity.ok().build();
}
// 문제 4
@GetMapping("/api/user/{id}")
public UserResponse getUser(@PathVariable Long id) {
User user = userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("사용자 정보가 없습니다."));
// UserResponse userResponse = new UserResponse(user);
UserResponse userResponse = UserResponse.of(user);
return userResponse;
}
// 문제 5
@GetMapping("/api/user/{id}/notice")
public List<NoticeResponse> userNotice(@PathVariable Long id) {
User user = userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("사용자 정보가 없습니다."));
List<Notice> noticeList = noticeRepository.findByUser(user);
List<NoticeResponse> noticeResponsesList = new ArrayList<>();
noticeList.stream().forEach(e -> {
noticeResponsesList.add(NoticeResponse.of(e));
});
return noticeResponsesList;
}
@ExceptionHandler(value = {ExistsEmailException.class, PasswordNotMatchException.class})
public ResponseEntity<?> handlerExistsEmailException(RuntimeException exception) {
return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
// 문제 6
@PostMapping("/api/user")
public ResponseEntity<?> addUser(@RequestBody @Valid UserInput userInput, Errors errors) {
List<ResponseError> responseErrorList = new ArrayList<>();
if(errors.hasErrors()) {
errors.getAllErrors().forEach(e -> {
responseErrorList.add(ResponseError.of((FieldError)e));
});
return new ResponseEntity<>(responseErrorList, HttpStatus.BAD_REQUEST);
}
if(userRepository.countByEmail(userInput.getEmail()) > 0) {
throw new ExistsEmailException("이미 가입된 이메일이 존재합니다.");
}
userRepository.save(User.builder()
.email(userInput.getEmail())
.name(userInput.getName())
.password(userInput.getPassword())
.phone(userInput.getPhone())
.regDate(LocalDateTime.now())
.build()
);
return new ResponseEntity<>(HttpStatus.OK);
}
// 문제 7
@PatchMapping("/api/user/{id}/password")
public ResponseEntity<?> updateUserPassword(@PathVariable Long id, @RequestBody @Valid UserInputPassword userInputPassword, Errors errors) {
List<ResponseError> responseErrorList = new ArrayList<>();
if(errors.hasErrors()) {
errors.getAllErrors().forEach(e -> {
responseErrorList.add(ResponseError.of((FieldError)e));
});
return new ResponseEntity<>(responseErrorList, HttpStatus.BAD_REQUEST);
}
User user = userRepository.findByIdAndPassword(id, userInputPassword.getPassword()).orElseThrow(() -> new PasswordNotMatchException("비밀번호가 일치하지 않습니다."));
user.setPassword(userInputPassword.getNewPassword());
userRepository.save(user);
return ResponseEntity.ok().build();
}
}
별도로 핸들러를 지정해도 되지만, 한번에 처리가 가능하다.
@ExceptionHandler(value = {ExistsEmailException.class, PasswordNotMatchException.class})
public ResponseEntity<?> handlerExistsEmailException(RuntimeException exception) {
return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
728x90
'Spring > Practice' 카테고리의 다른 글
[Practice] 사용자 API 만들기 (9) (0) | 2021.04.14 |
---|---|
[Practice] 사용자 API 만들기 (8) (0) | 2021.04.14 |
[Practice] 사용자 API 만들기 (6) (0) | 2021.04.13 |
[Practice] 사용자 API 만들기 (5) (0) | 2021.04.13 |