728x90
[DELETE]
UserController
@RestController
@RequestMapping("/users")
public class UserController {
final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private final UserProvider userProvider;
@Autowired
private final UserService userService;
@Autowired
private final JwtService jwtService;
public UserController(UserProvider userProvider, UserService userService, JwtService jwtService){
this.userProvider = userProvider;
this.userService = userService;
this.jwtService = jwtService;
}
/**
* 회원 조회 API
* [GET] /users
* 이메일 검색 조회 API
* [GET] /users? Email=
* @return BaseResponse<GetUserRes>
*/
//Query String
@ResponseBody
@GetMapping("") // (GET) 127.0.0.1:9000/users
public BaseResponse<GetUserRes> getUsers(@RequestParam(required = true) String Email) {
try{
// TODO: email 관련한 짧은 validation 예시입니다. 그 외 더 부가적으로 추가해주세요!
if(Email.length()==0){
return new BaseResponse<>(POST_USERS_EMPTY_EMAIL);
}
// 이메일 정규표현
if(!isRegexEmail(Email)){
return new BaseResponse<>(POST_USERS_INVALID_EMAIL);
}
GetUserRes getUsersRes = userProvider.getUsersByEmail(Email);
return new BaseResponse<>(getUsersRes);
} catch(BaseException exception){
return new BaseResponse<>((exception.getStatus()));
}
}
@ResponseBody
@GetMapping("/{userIdx}") // (GET) 127.0.0.1:9000/users/:userIdx
public BaseResponse<GetUserRes> getUserByIdx(@PathVariable("userIdx")int userIdx) {
try{
GetUserRes getUsersRes = userProvider.getUsersByIdx(userIdx);
return new BaseResponse<>(getUsersRes);
} catch(BaseException exception){
return new BaseResponse<>((exception.getStatus()));
}
}
@ResponseBody
@DeleteMapping("/delete/{userIdx}") // (GET) 127.0.0.1:9000/users/:userIdx
public BaseResponse<Object> deleteUserByIdx(@PathVariable("userIdx")int userIdx) {
try{
if(userProvider.getUsersByIdx(userIdx) == null){
return new BaseResponse<>(USERS_EMPTY_USER_ID);
}
userProvider.deleteUser(userIdx);
return new BaseResponse<>(userProvider.deleteUser(userIdx));
} catch (BaseException e) {
throw new RuntimeException(e);
}
}
/**
* 회원가입 API
* [POST] /users
* @return BaseResponse<PostUserRes>
*/
// Body
@ResponseBody
@PostMapping("") // (POST) 127.0.0.1:9000/users
public BaseResponse<PostUserRes> createUser(@RequestBody PostUserReq postUserReq) {
// TODO: email 관련한 짧은 validation 예시입니다. 그 외 더 부가적으로 추가해주세요!
if(postUserReq.getEmail() == null){
return new BaseResponse<>(POST_USERS_EMPTY_EMAIL);
}
// 이메일 정규표현
if(!isRegexEmail(postUserReq.getEmail())){
return new BaseResponse<>(POST_USERS_INVALID_EMAIL);
}
try{
PostUserRes postUserRes = userService.createUser(postUserReq);
return new BaseResponse<>(postUserRes);
} catch(BaseException exception){
return new BaseResponse<>((exception.getStatus()));
}
}
/**
* 유저정보변경 API
* [PATCH] /users/:userIdx
* @return BaseResponse<String>
*/
@ResponseBody
@PatchMapping("/{userIdx}") // (PATCH) 127.0.0.1:9000/users/:userIdx
public BaseResponse<String> modifyUserName(@PathVariable("userIdx") int userIdx, @RequestBody User user){
try {
/* TODO: jwt는 다음주차에서 배울 내용입니다!
jwt에서 idx 추출.
int userIdxByJwt = jwtService.getUserIdx();
userIdx와 접근한 유저가 같은지 확인
if(userIdx != userIdxByJwt){
return new BaseResponse<>(INVALID_USER_JWT);
}
*/
PatchUserReq patchUserReq = new PatchUserReq(userIdx,user.getNickName());
userService.modifyUserName(patchUserReq);
String result = "";
return new BaseResponse<>(result);
} catch (BaseException exception) {
return new BaseResponse<>((exception.getStatus()));
}
}
}
UserDAO
@Repository
public class UserDao {
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(DataSource dataSource){
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<GetUserRes> getUsers(){
String getUsersQuery = "select userIdx,name,nickName,email from User";
return this.jdbcTemplate.query(getUsersQuery,
(rs,rowNum) -> new GetUserRes(
rs.getInt("userIdx"),
rs.getString("name"),
rs.getString("nickName"),
rs.getString("email")
));
}
public GetUserRes getUsersByEmail(String email){
String getUsersByEmailQuery = "select userIdx,name,nickName,email from User where email=?";
String getUsersByEmailParams = email;
return this.jdbcTemplate.queryForObject(getUsersByEmailQuery,
(rs, rowNum) -> new GetUserRes(
rs.getInt("userIdx"),
rs.getString("name"),
rs.getString("nickName"),
rs.getString("email")),
getUsersByEmailParams);
}
public GetUserRes getUsersByIdx(int userIdx){
String getUsersByIdxQuery = "select userIdx,name,nickName,email from User where userIdx=?";
int getUsersByIdxParams = userIdx;
return this.jdbcTemplate.queryForObject(getUsersByIdxQuery,
(rs, rowNum) -> new GetUserRes(
rs.getInt("userIdx"),
rs.getString("name"),
rs.getString("nickName"),
rs.getString("email")),
getUsersByIdxParams);
}
public int createUser(PostUserReq postUserReq){
String createUserQuery = "insert into User (name, nickName, phone, email, password) VALUES (?,?,?,?,?)";
Object[] createUserParams = new Object[]{postUserReq.getName(), postUserReq.getNickName(),postUserReq.getPhone(), postUserReq.getEmail(), postUserReq.getPassword()};
this.jdbcTemplate.update(createUserQuery, createUserParams);
String lastInserIdQuery = "select last_insert_id()";
return this.jdbcTemplate.queryForObject(lastInserIdQuery,int.class);
}
public int checkEmail(String email){
String checkEmailQuery = "select exists(select email from User where email = ?)";
String checkEmailParams = email;
return this.jdbcTemplate.queryForObject(checkEmailQuery,
int.class,
checkEmailParams);
}
public int modifyUserName(PatchUserReq patchUserReq){
String modifyUserNameQuery = "update User set nickName = ? where userIdx = ? ";
Object[] modifyUserNameParams = new Object[]{patchUserReq.getNickName(), patchUserReq.getUserIdx()};
return this.jdbcTemplate.update(modifyUserNameQuery,modifyUserNameParams);
}
// Delete User
public int deleteUser(int userId) {
String deleteUserByIdQuery = "delete from User where userIdx = ?";
int deleteUsersByIdParams = userId;
return this.jdbcTemplate.update(deleteUserByIdQuery,deleteUsersByIdParams);
}
}
UserProvider
//Provider : Read의 비즈니스 로직 처리
@Service
public class UserProvider {
private final UserDao userDao;
private final JwtService jwtService;
final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
public UserProvider(UserDao userDao, JwtService jwtService) {
this.userDao = userDao;
this.jwtService = jwtService;
}
public GetUserRes getUsersByEmail(String email) throws BaseException{
try{
GetUserRes getUsersRes = userDao.getUsersByEmail(email);
return getUsersRes;
}
catch (Exception exception) {
throw new BaseException(DATABASE_ERROR);
}
}
public GetUserRes getUsersByIdx(int userIdx) throws BaseException{
try{
GetUserRes getUsersRes = userDao.getUsersByIdx(userIdx);
return getUsersRes;
}
catch (Exception exception) {
throw new BaseException(DATABASE_ERROR);
}
}
public int checkEmail(String email) throws BaseException{
try{
return userDao.checkEmail(email);
} catch (Exception exception){
throw new BaseException(DATABASE_ERROR);
}
}
public int deleteUser(int userIdx) throws BaseException{
try{
return userDao.deleteUser(userIdx);
} catch (Exception exception){
throw new BaseException(DATABASE_ERROR);
}
}
}
UserService
// Service Create, Update, Delete 의 로직 처리
@Service
public class UserService {
final Logger logger = LoggerFactory.getLogger(this.getClass());
private final UserDao userDao;
private final UserProvider userProvider;
private final JwtService jwtService;
@Autowired
public UserService(UserDao userDao, UserProvider userProvider, JwtService jwtService) {
this.userDao = userDao;
this.userProvider = userProvider;
this.jwtService = jwtService;
}
public PostUserRes createUser(PostUserReq postUserReq) throws BaseException {
// 이메일 중복 확인
if(userProvider.checkEmail(postUserReq.getEmail()) ==1){
throw new BaseException(POST_USERS_EXISTS_EMAIL);
}
String pwd;
try{
//암호화
pwd = new SHA256().encrypt(postUserReq.getPassword()); postUserReq.setPassword(pwd);
} catch (Exception ignored) {
throw new BaseException(PASSWORD_ENCRYPTION_ERROR);
}
try{
int userIdx = userDao.createUser(postUserReq);
//jwt 발급.
// TODO: jwt는 다음주차에서 배울 내용입니다!
String jwt = jwtService.createJwt(userIdx);
return new PostUserRes(jwt,userIdx);
} catch (Exception exception) {
throw new BaseException(DATABASE_ERROR);
}
}
public void modifyUserName(PatchUserReq patchUserReq) throws BaseException {
try{
int result = userDao.modifyUserName(patchUserReq);
if(result == 0){
throw new BaseException(MODIFY_FAIL_USERNAME);
}
} catch(Exception exception){
throw new BaseException(DATABASE_ERROR);
}
}
public void deleteUser(int userIdx) {
userDao.deleteUser(userIdx);
}
}
확인하기
- Post Man에서@DeleteMapping 사용시 옆에 왼쪽을 delete로 변경
데이터 그립에서 잘 삭제되어 있다!
만약 url을 다르게 설정하고 싶으면
728x90
'Server🧤 > SpringBoot' 카테고리의 다른 글
[Springboot] AWS S3 버킷을 이용한 PresignedUrl로 이미지 업로드 구현하기 (0) | 2023.08.10 |
---|---|
[Server] 개발환경 구축하기 - Spring (0) | 2022.04.28 |