Skip to content

Commit

Permalink
Merge pull request #19 from EWHA-LUX/feature/#18
Browse files Browse the repository at this point in the history
[Feature] 공통 응답 포맷 생성, 예외 처리 추가
  • Loading branch information
Haewonny authored Feb 4, 2024
2 parents a010347 + a0d8127 commit fdd47e3
Show file tree
Hide file tree
Showing 6 changed files with 175 additions and 48 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package ewha.lux.once.domain.home.controller;

import ewha.lux.once.domain.home.service.HomeService;
import ewha.lux.once.global.common.ResponseDto;
import ewha.lux.once.global.common.CommonResponse;
import ewha.lux.once.global.common.ResponseCode;
import ewha.lux.once.global.common.UserAccount;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
Expand All @@ -14,29 +14,39 @@
@RequiredArgsConstructor
@RequestMapping("home")
public class HomeController {

private final HomeService homeService;

// [Get] 챗봇 카드 추천
@GetMapping()
public ResponseEntity<ResponseDto<Object>> homeChat (@AuthenticationPrincipal UserAccount userAccount, @RequestParam(name = "keyword") String keyword,@RequestParam(name = "paymentAmount") int paymentAmount ){
public CommonResponse<?> homeChat(@AuthenticationPrincipal UserAccount userAccount, @RequestParam(name = "keyword") String keyword, @RequestParam(name = "paymentAmount") int paymentAmount) {

return ResponseEntity.ok(ResponseDto.response(1000,true,"요청에 성공하였습니다.",homeService.getHomeChat(userAccount.getUsers(),keyword,paymentAmount)));
return new CommonResponse<>(ResponseCode.SUCCESS, homeService.getHomeChat(userAccount.getUsers(), keyword, paymentAmount));
}

// [Get] 홈 화면 기본 정보 조회
@GetMapping("/basic")
public ResponseEntity<ResponseDto<Object>> home (@AuthenticationPrincipal UserAccount userAccount){
return ResponseEntity.ok(ResponseDto.response(1000,true,"요청에 성공하였습니다.",homeService.getHome(userAccount.getUsers())));
public CommonResponse<?> home(@AuthenticationPrincipal UserAccount userAccount) {
return new CommonResponse<>(ResponseCode.SUCCESS, homeService.getHome(userAccount.getUsers()));
}
@PatchMapping ("/{chat_id}")
public ResponseEntity<ResponseDto<Object>> payCardHistory (@AuthenticationPrincipal UserAccount userAccount, @PathVariable Long chat_id){
homeService.getPayCardHistory(userAccount.getUsers(),chat_id);
return ResponseEntity.ok(ResponseDto.response(1000,true,"요청에 성공하였습니다."));

// [Patch] 결제 여부 변경
@PatchMapping("/{chat_id}")
public CommonResponse<?> payCardHistory(@AuthenticationPrincipal UserAccount userAccount, @PathVariable Long chat_id) {
homeService.getPayCardHistory(userAccount.getUsers(), chat_id);
return new CommonResponse<>(ResponseCode.SUCCESS);
}
@GetMapping ("/announcement")
public ResponseEntity<ResponseDto<Object>> announce (@AuthenticationPrincipal UserAccount userAccount){
return ResponseEntity.ok(ResponseDto.response(1000,true,"요청에 성공하였습니다.",homeService.getAnnounce(userAccount.getUsers())));

// [Get] 알림 list 조회
@GetMapping("/announcement")
public CommonResponse<?> announce(@AuthenticationPrincipal UserAccount userAccount) {
return new CommonResponse<>(ResponseCode.SUCCESS, homeService.getAnnounce(userAccount.getUsers()));
}

@GetMapping ("/announcement/{announceId}")
public ResponseEntity<ResponseDto<Object>> announcedetail (@PathVariable Long announceId){
return ResponseEntity.ok(ResponseDto.response(1000,true,"요청에 성공하였습니다.",homeService.getAnnounceDetail(announceId)));
// [Get] 알림 상세 조회
@GetMapping("/announcement/{announceId}")
public CommonResponse<?> announcedetail(@PathVariable Long announceId) {
return new CommonResponse<>(ResponseCode.SUCCESS, homeService.getAnnounceDetail(announceId));
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,17 @@
import ewha.lux.once.domain.user.dto.SignInRequestDto;
import ewha.lux.once.domain.user.dto.SignupRequestDto;
import ewha.lux.once.domain.user.dto.postSearchCardListRequestDto;
import ewha.lux.once.global.common.UserAccount;
import ewha.lux.once.domain.user.entity.Users;
import ewha.lux.once.domain.user.service.UserService;
import ewha.lux.once.global.common.ResponseDto;
import ewha.lux.once.global.common.CommonResponse;
import ewha.lux.once.global.common.CustomException;
import ewha.lux.once.global.common.ResponseCode;
import ewha.lux.once.global.common.UserAccount;
import ewha.lux.once.global.security.JwtProvider;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.data.repository.query.Param;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
Expand All @@ -27,69 +28,78 @@
@RequiredArgsConstructor
@RequestMapping("user")
public class UserController {

private final UserService userService;
private final JwtProvider jwtProvider;

@PostMapping("/signup") // 회원가입
public ResponseEntity<ResponseDto<Object>> signup(@RequestBody SignupRequestDto request) throws ParseException {
try{
// [Post] 회원가입
@PostMapping("/signup")
public CommonResponse<?> signup(@RequestBody SignupRequestDto request) throws ParseException {
try {
Users users = userService.signup(request);

String accessToken = jwtProvider.generateAccessToken(users.getLoginId());
String refreshToken = jwtProvider.generateRefreshToken(users.getLoginId());

LoginResponseDto loginResponseDto = new LoginResponseDto(users.getId(),accessToken,refreshToken);
return ResponseEntity.ok(ResponseDto.response(1000,true, "요청에 성공하였습니다.",loginResponseDto));
} catch (Exception e){
return ResponseEntity.ok(ResponseDto.response(2000,false, "요청에 성공하였습니다."));
LoginResponseDto loginResponseDto = new LoginResponseDto(users.getId(), accessToken, refreshToken);
return new CommonResponse<>(ResponseCode.SUCCESS, loginResponseDto);
} catch (Exception e) {
return new CommonResponse<>(ResponseCode.SUCCESS); // ** 예외 처리 필요 **
}
}

@PostMapping("/login") // 로그인
public ResponseEntity<ResponseDto<Object>> signin(@RequestBody SignInRequestDto request) {
try{
// [Post] 로그인
@PostMapping("/login")
public CommonResponse<?> signin(@RequestBody SignInRequestDto request) {
try {
Users user = userService.authenticate(request);

String accessToken = jwtProvider.generateAccessToken(user.getLoginId());
String refreshToken = jwtProvider.generateRefreshToken(user.getLoginId());

LoginResponseDto loginResponseDto = new LoginResponseDto(user.getId(),accessToken,refreshToken);
return ResponseEntity.ok(ResponseDto.response(1000,true, "요청에 성공하였습니다.",loginResponseDto));
} catch (Exception e){
return ResponseEntity.ok(ResponseDto.response(2000,false, "요청에 실패하였습니다."));
LoginResponseDto loginResponseDto = new LoginResponseDto(user.getId(), accessToken, refreshToken);

return new CommonResponse<>(ResponseCode.SUCCESS, loginResponseDto);
} catch (CustomException e) {
return new CommonResponse<>(e.getStatus());
}
}

@DeleteMapping ("/quit")
// [Delete] 회원 탈퇴
@DeleteMapping("/quit")
@ResponseBody
public ResponseEntity<ResponseDto<Object>> quitUsers (@AuthenticationPrincipal UserAccount userAccount) {
public CommonResponse<?> quitUsers(@AuthenticationPrincipal UserAccount userAccount) {
userService.deleteUsers(userAccount.getUsers());
return ResponseEntity.ok(ResponseDto.response(1000,true,"요청에 성공하였습니다."));
return new CommonResponse<>(ResponseCode.SUCCESS);
}

// [Get] 회원 정보 조회
@GetMapping("/edit")
@ResponseBody
public ResponseEntity<ResponseDto<Object>> userEdit (@AuthenticationPrincipal UserAccount userAccount) {
return ResponseEntity.ok(ResponseDto.response(1000,true,"요청에 성공하였습니다.",userService.getUserEdit(userAccount.getUsers())));
public CommonResponse<?> userEdit(@AuthenticationPrincipal UserAccount userAccount) {
return new CommonResponse<>(ResponseCode.SUCCESS, userService.getUserEdit(userAccount.getUsers()));
}

// [Get] 카드사별 카드 검색
@GetMapping("/card/search")
@ResponseBody
public ResponseEntity<ResponseDto<Object>> searchCard (@Param("code")String code) {
return ResponseEntity.ok(ResponseDto.response(1000,true,"요청에 성공하였습니다.",userService.getSearchCard(code)));
public CommonResponse<?> searchCard(@Param("code") String code) {
return new CommonResponse<>(ResponseCode.SUCCESS, userService.getSearchCard(code));
}

// [Post] 카드 등록
@PostMapping("/card")
@ResponseBody
public ResponseEntity<ResponseDto<Object>> postSearchCard (@AuthenticationPrincipal UserAccount userAccount,@RequestBody postSearchCardListRequestDto request) {
userService.postSearchCard(userAccount.getUsers(),request);
return ResponseEntity.ok(ResponseDto.response(1000,true,"요청에 성공하였습니다."));
public CommonResponse<?> postSearchCard(@AuthenticationPrincipal UserAccount userAccount, @RequestBody postSearchCardListRequestDto request) {
userService.postSearchCard(userAccount.getUsers(), request);
return new CommonResponse<>(ResponseCode.SUCCESS);
}

@PatchMapping(value="/edit/profile",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
// [Patch] 프로필 등록
@PatchMapping(value = "/edit/profile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody
public ResponseEntity<ResponseDto<Object>> editProfile (@AuthenticationPrincipal UserAccount userAccount, HttpServletRequest request, @RequestParam(value="userProfileImg") MultipartFile userProfileImg) throws IOException {
return ResponseEntity.ok(ResponseDto.response(1000,true,"요청에 성공하였습니다.",userService.patchEditProfile(userAccount.getUsers(),userProfileImg)));
public CommonResponse<?> editProfile(@AuthenticationPrincipal UserAccount userAccount, HttpServletRequest request, @RequestParam(value = "userProfileImg") MultipartFile userProfileImg) throws IOException {
return new CommonResponse<>(ResponseCode.SUCCESS, userService.patchEditProfile(userAccount.getUsers(), userProfileImg));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import ewha.lux.once.domain.card.entity.Card;
import ewha.lux.once.domain.card.entity.CardCompany;
import ewha.lux.once.domain.card.entity.OwnedCard;
import ewha.lux.once.global.common.CustomException;
import ewha.lux.once.global.common.ResponseCode;
import ewha.lux.once.global.repository.CardCompanyRepository;
import ewha.lux.once.global.repository.CardRepository;
import ewha.lux.once.global.repository.OwnedCardRepository;
Expand Down Expand Up @@ -76,14 +78,14 @@ public Users signup(SignupRequestDto request) throws ParseException {
return usersRepository.save(usersBuilder.benefitGoal(100000).build());
}

public Users authenticate(SignInRequestDto request) {
public Users authenticate(SignInRequestDto request) throws CustomException {
String loginId = request.getLoginId();
String password = request.getPassword();

Users users = usersRepository.findByLoginId(loginId);

if (!passwordEncoder.matches(password, users.getPassword())){
throw new RuntimeException("비밀번호가 일치하지 않습니다.");
throw new CustomException(ResponseCode.FAILED_TO_LOGIN);
}

users.setLastLogin();
Expand Down
36 changes: 36 additions & 0 deletions src/main/java/ewha/lux/once/global/common/CommonResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package ewha.lux.once.global.common;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;

@Getter
@AllArgsConstructor
@Builder
public class CommonResponse<T> {

private int code;
private boolean inSuccess;
private String message;
private T result;

// 요청에 성공한 경우
@Builder
public CommonResponse(ResponseCode status, T result) {
this.code = status.getCode();
this.inSuccess = status.isInSuccess();
this.message = status.getMessage();

this.result = result;
}

// 요청에 실패한 경우
@Builder
public CommonResponse(ResponseCode status) {
this.code = status.getCode();
this.inSuccess = status.isInSuccess();
this.message = status.getMessage();
}

}

12 changes: 12 additions & 0 deletions src/main/java/ewha/lux/once/global/common/CustomException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package ewha.lux.once.global.common;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Getter
public class CustomException extends Exception {
public ResponseCode status;
}
57 changes: 57 additions & 0 deletions src/main/java/ewha/lux/once/global/common/ResponseCode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package ewha.lux.once.global.common;

import lombok.Getter;

@Getter
public enum ResponseCode {
/*
1000 : Request 성공
*/
SUCCESS(1000, true, "요청에 성공하였습니다."),


/*
2000~ : Request 오류
*/



// =====================================
/*
3000~ : Response 오류
*/
// 3000~ : user 관련 오류
RESPONSE_ERROR(3000, false, "값을 불러오는데 실패하였습니다."),
INVALID_USER_ID(3001, false, "아이디가 존재하지 않습니다."),
FAILED_TO_LOGIN(3002, false, "비밀번호가 일치하지 않습니다."),

// 3100~ :

// 3200~ :


// =====================================

// 그 외 오류
INTERNAL_SERVER_ERROR(9000, false, "서버 오류가 발생했습니다.");


// =====================================
private int code;
private boolean inSuccess;
private String message;


/*
해당되는 코드 매핑
@param code
@param inSuccess
@param message
*/
ResponseCode(int code, boolean inSuccess, String message) {
this.inSuccess = inSuccess;
this.code = code;
this.message = message;
}
}

0 comments on commit fdd47e3

Please sign in to comment.