feat: habit api#6
Conversation
4961721 to
6a8e9ad
Compare
| .and().csrf().disable() | ||
| .addFilterBefore(new JwtFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); | ||
|
|
||
| log.info("security config!"); |
There was a problem hiding this comment.
이부분에서 테스트 확인 끝났으면 지워도 되지 않을까요?
| log.info("security config!"); |
| httpSecurity.authorizeRequests().mvcMatchers("/api/login").permitAll() | ||
| .mvcMatchers("/api/**").hasRole("USER") |
There was a problem hiding this comment.
로그인 뿐만 아니라 회원가입도 권한 전체 허용이 필요하지 않을까요?
| private final Long accessTokenValid = 60 * 60 * 24 * 1000L; // 24 hour | ||
| private final Long refreshTokenValid = 14 * 24 * 60 * 60 * 1000L; // 14 day |
There was a problem hiding this comment.
이 설정은 직접 관리하기보다는 application.yaml 에 정의하시면 좋을 것 같아요
|
|
||
| //User 객체를 만들어서 Authentication 리턴 | ||
| User principal = new User(claims.getSubject(), "",authorities); | ||
| User principal = new User(claims.get("email",String.class), "",authorities); |
There was a problem hiding this comment.
클레임에서 값을 가져오는 작업을 별도 메서드로 관리하면 좀더 깔끔했을 것 같아요
Claims 객체에서 User 객체로 전환하게끔요
| return ResponseEntity.ok("습관이 인증되었습니다."); | ||
| } catch (NotFoundException e){ | ||
| return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); |
There was a problem hiding this comment.
StatusCode는 저런식으로 이미 정의된 값으로 사용하는데 이런 메시지도 문자열로 선언하기 보다는 공통적으로 사용하는 데이타 클래스를 구성해서 정의하면 중복해서 사용할 일이 줄어들 것 같구요
나중에 타 언어를 지원할 때 메시지 인스턴스만 바꿔치기만 해서 적용할 수 있을 것 같습니다
| HabitEntity habit = HabitEntity.builder() | ||
| .title(habitDto.getTitle()) //습관명 저장 | ||
| .duration(habitDto.getDuration()) //습관 기간 저장 | ||
| .visible(habitDto.isVisible()) //공개여부 저장 //!!다시 확인하기 | ||
| .createdDate(LocalDateTime.now()) //생성일 저장 | ||
| .lastModifiedDate(LocalDateTime.now()) //변경일 저장 | ||
| .achievementRate(0) //달성률 저장 | ||
| .achievementCount(0) //달성횟수 저장 | ||
| .totalAchievementCount(0) //누적달성횟수 저장 | ||
| .comboCount(0) //콤보횟수 저장 | ||
| .stopDate(null) //중지일 저장 | ||
| .deleteYn(false) //삭제여부 저장 | ||
| .userId(byEmail) | ||
| .build(); |
There was a problem hiding this comment.
dto에서 dao 전환될 떄 dto에 메서드가 존재하면 깔끔하게 표현될 수 있을 것 같아요
var DAO = DTO.toEntity() 형식으로요
| @PostMapping("habit") //습관 생성 | ||
| ResponseEntity<?> createHabit(@RequestBody HabitDto habitDto){ | ||
|
|
||
| UserEntity byEmail = userService.findByEmail(habitDto.getEmail()); | ||
| log.info("byEmail.getEmail(): {}",byEmail.getEmail()); | ||
|
|
||
| HabitEntity habit = HabitEntity.builder() | ||
| .title(habitDto.getTitle()) //습관명 저장 | ||
| .duration(habitDto.getDuration()) //습관 기간 저장 | ||
| .visible(habitDto.isVisible()) //공개여부 저장 //!!다시 확인하기 | ||
| .createdDate(LocalDateTime.now()) //생성일 저장 | ||
| .lastModifiedDate(LocalDateTime.now()) //변경일 저장 | ||
| .achievementRate(0) //달성률 저장 | ||
| .achievementCount(0) //달성횟수 저장 | ||
| .totalAchievementCount(0) //누적달성횟수 저장 | ||
| .comboCount(0) //콤보횟수 저장 | ||
| .stopDate(null) //중지일 저장 | ||
| .deleteYn(false) //삭제여부 저장 | ||
| .userId(byEmail) | ||
| .build(); | ||
|
|
||
| habitService.saveHabit(habit); | ||
| log.info("habit entity: {}",habit); | ||
| log.info("{}의 습관: 습관명-{}, 습관기간-{}, 공개여부-{}", | ||
| byEmail.getNickname(),habit.getTitle(),habit.getDuration(),habit.isVisible()); | ||
|
|
||
| return new ResponseEntity<>(HttpStatus.OK); | ||
| } | ||
|
|
||
| @GetMapping("habits") //습관목록 조회(메인페이지) | ||
| ResponseEntity<List<HabitResponseDto>> getHabitList(@RequestParam("email") String email) throws Exception { | ||
| List<HabitEntity> habits = habitService.findUndeletedAndActiveHabits(email); | ||
| log.info("habits: {}",habits); | ||
| List<HabitResponseDto> habitResponseDtos = habits.stream() | ||
| .map(habit -> { | ||
| HabitResponseDto responseDto = new HabitResponseDto(); | ||
| responseDto.setId(habit.getId()); | ||
| responseDto.setTitle(habit.getTitle()); | ||
| responseDto.setVisible(habit.isVisible()); | ||
| responseDto.setComboCount(habit.getComboCount()); | ||
| responseDto.setAchievementRate(habit.getAchievementRate()); | ||
| responseDto.setAchievementCount(habit.getAchievementCount()); | ||
| return responseDto; | ||
| }) | ||
| .collect(Collectors.toList()); | ||
| return ResponseEntity.ok(habitResponseDtos); | ||
| } | ||
|
|
||
| @GetMapping("habits/edit-list") //편집시 습관목록조회(중지일 포함) | ||
| ResponseEntity<List<HabitEditResponseDto>> getHabitEditList(@RequestParam("email") String email) throws Exception{ | ||
| List<HabitEntity> habits = habitService.findUndeletedAndAllHabits(email); | ||
| log.info("undeletedAndAllHabits: {}",habits); | ||
| List<HabitEditResponseDto> habitEditListDto = habits.stream() | ||
| .map(habitEntity -> { | ||
| HabitEditResponseDto editResponseDto = new HabitEditResponseDto(); | ||
| editResponseDto.setId(habitEntity.getId()); | ||
| editResponseDto.setTitle(habitEntity.getTitle()); | ||
| editResponseDto.setDuration(habitEntity.getDuration()); | ||
| editResponseDto.setVisible(habitEntity.isVisible()); | ||
| editResponseDto.setComboCount(habitEntity.getComboCount()); | ||
| editResponseDto.setAchievementRate(habitEntity.getAchievementRate()); | ||
| editResponseDto.setAchievementCount(habitEntity.getAchievementCount()); | ||
| editResponseDto.setStopDate(habitEntity.getStopDate()); //중지일 | ||
| return editResponseDto; | ||
| }) | ||
| .collect(Collectors.toList()); | ||
| return ResponseEntity.ok(habitEditListDto) | ||
| } | ||
|
|
||
|
|
||
|
|
||
| @PutMapping("habits/{habitId}/edit") //습관수정(이름, 기간, 공개여부) | ||
| ResponseEntity<HabitResponseDto> updateHabit(@PathVariable("habitId") Long habitId, | ||
| @RequestBody HabitUpdateRequestDto habitUpdateDto) throws Exception { | ||
| HabitResponseDto updatedHabit = habitService.updateHabit(habitId, habitUpdateDto); | ||
|
|
||
| return ResponseEntity.ok(updatedHabit); | ||
|
|
||
| } | ||
|
|
||
| @DeleteMapping("habits/{habitId}") //습관삭제 | ||
| ResponseEntity<?> deleteHabit(@PathVariable("habitId") Long habitId){ | ||
| habitService.deleteHabit(habitId); | ||
|
|
||
| return ResponseEntity.ok("Habit deleted successfully."); | ||
|
|
||
| } | ||
|
|
||
| @PutMapping("habits/{habitId}/stop") //습관 중지 | ||
| ResponseEntity<String> stopHabit(@PathVariable("habitId") Long habitId){ | ||
| try { | ||
| habitService.stopHabit(habitId); | ||
| return ResponseEntity.ok("Habit stopped successfully."); | ||
| } catch (NoSuchElementException e) { | ||
| return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Habit not found."); | ||
| } catch (IllegalStateException e) { | ||
| return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage()); | ||
| } catch (Exception e) { | ||
| return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred."); | ||
| } | ||
|
|
||
| } | ||
|
|
||
| //습관 편집시 목록 | ||
|
|
||
|
|
||
| @GetMapping("habits/{habitId}/reset") //매주마다 달성횟수 리셋 | ||
| ResponseEntity<String> resetAchievement(@PathVariable("habitId") Long habitId){ | ||
| habitService.resetAchievement(habitId); | ||
| return ResponseEntity.ok("Resetting the achievement count was successful."); | ||
| } |
There was a problem hiding this comment.
이미 모든 REST API의 PATH가 habits로 시작하면
전체 클래스에 habits를 매핑해놓았으면 더 좋았을 것 같아요
✔ PR 타입(하나 이상의 PR 타입을 선택해주세요)
📄 개요
✍🏻 변경 사항