[인스타그램 클론코딩] 11. 프로필 수정 기능 구현(Back-End)

2023. 2. 7. 13:20·Web/인스타 클론 코딩

프로필 관련 내용은 기존에 만들어진 Entity를 활용하는 것이므로 따로 만들 Entity는 없다.

먼저 사용할 Dto부터 생성한다.

 

1. Profile 관련 Dto 생성

@Data
public class ProfileCountResponseDto {

    private Long board;
    private Long follower;
    private Long follow;

    @Builder
    public ProfileCountResponseDto(Long board, Long follower, Long follow) {
        this.board = board;
        this.follower = follower;
        this.follow = follow;
    }
}

@Data
public class ProfileUpdateRequestDto {
    private String nickname;
    private String introduce;

    @NotBlank(message = "빈 항목이 존재합니다.")
    @Pattern(regexp = "^\\d{3}-\\d{4}-\\d{4}", message = "핸드폰 번호 형식이 잘못 되었습니다.")
    private String phone;

    private String gender;
}

@Data
public class UpdatePasswordRequestDto {
    private String prevPw;
    private String changePw;
}

 

- ProfileCountResponseDto는 사용자의 게시글, 팔로워, 팔로잉 수를 반환해주기 위해 사용할 Dto이다.

- ProfileUpdateRequestDto는 사용자 정보 세부사항 수정 요청을 받기위한 Dto이다.

- UpdatePasswordRequestDto는 비밀번호 변경을 위해, 현재비밀번호와 바꿀 비밀번호를 받을 Dto이다.

 

2. ProfileService 생성

@Service
@Slf4j
@RequiredArgsConstructor
public class ProfileService {

    private final FollowRepository followRepository;
    private final PostRepository postRepository;
    private final FileUploader fileUploader;
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    @Transactional
    public UserDetailResponseDto getProfile(User user) {
        return UserDetailResponseDto.builder()
                .email(user.getEmail())
                .nickname(user.getNickname())
                .profileUrl(user.getProfileImgUrl())
                .phone(user.getPhone())
                .introduce(user.getIntroduce())
                .gender(user.getGender())
                .build();
    }

    @Transactional
    public ProfileCountResponseDto getProfileCount(User user) {

        return ProfileCountResponseDto.builder()
                .board(postRepository.countByUser(user))
                .follower(followRepository.countByFollowing(user))
                .follow(followRepository.countByFollower(user))
                .build();
    }

    @Transactional
    public UserDetailResponseDto updateProfileThumbnail(User user, MultipartFile file) {

        String dbPathLocation = "/static/profileImage/" + user.getEmail() + "/"  + file.getOriginalFilename();

        user.setProfileImgUrl(dbPathLocation);
        userRepository.save(user);
        fileUploader.saveFile(user.getEmail(), "profileImage", file);

        return this.getProfile(user);
    }

    @Transactional
    public UserDetailResponseDto updateProfiles(User user, ProfileUpdateRequestDto requestDto) {

        user.setNickname(requestDto.getNickname());
        user.setIntroduce(requestDto.getIntroduce());
        user.setPhone(requestDto.getPhone());
        user.setGender(requestDto.getGender());

        userRepository.save(user);

        return this.getProfile(user);
    }

    @Transactional
    public void updateUserPassword(User user, UpdatePasswordRequestDto requestDto) throws Exception {
        if(passwordEncoder.matches(requestDto.getPrevPw(), user.getPassword())) {
            user.setPassword(passwordEncoder.encode(requestDto.getChangePw()));
            userRepository.save(user);
        }
        else {
            throw new Exception("현재 비밀번호가 올바르지 않습니다.");
        }
    }
}

 

- getProfile : 프로필 정보를 반환해주는 로직이다.

- getProfileCount : 해당 유저의 게시글, 팔로워, 팔로잉 수를 반환해주는 로직이다.

- updateProfileThumbnail : 유저의 프로필 사진을 업데이트해주는 로직이다.

- updateProfiles : 유저의 프로필 세부사항을 수정하기 위한 로직이다.

- updateUserPassword : 유저의 비밀번호를 수정하기 위한 로직이다.

 

3. ProfileController 작성

@RestController
@Slf4j
@RequiredArgsConstructor
public class ProfileController {

    private final ProfileService profileService;

    @GetMapping("/profile")
    public ResponseEntity getProfile(@CurrentUser User user) {
        try {
            return ResponseEntity.ok().body(profileService.getProfile(user));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("요청에 오류가 발생하였습니다.");
        }
    }

    @GetMapping("/profiles/count")
    public ResponseEntity getProfileCount(@CurrentUser User user) {
        try {
            return ResponseEntity.ok().body(profileService.getProfileCount(user));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PostMapping("/profiles/thumbnail")
    public ResponseEntity updateProfileThumbnail(@CurrentUser User user, @RequestPart MultipartFile file) {
        try {
            return ResponseEntity.ok().body(profileService.updateProfileThumbnail(user, file));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PostMapping("/profiles/profile")
    public ResponseEntity updateProfiles(@CurrentUser User user, @Valid @RequestBody ProfileUpdateRequestDto requestDto, BindingResult bindingResult) {
        if(bindingResult.hasErrors()) {
            String errorMsg = bindingResult.getFieldError().getDefaultMessage();

            return ResponseEntity.badRequest().body(errorMsg);
        }

        try {
            return ResponseEntity.ok().body(profileService.updateProfiles(user, requestDto));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PostMapping("/password")
    public ResponseEntity updatePassword(@CurrentUser User user, @RequestBody UpdatePasswordRequestDto requestDto) {
        try {
            profileService.updateUserPassword(user, requestDto);
            return ResponseEntity.ok().body("비밀번호가 성공적으로 변경되었습니다.");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}

 

- 해당 url에 맞게 profileService를 연결해준다.

저작자표시 비영리 변경금지 (새창열림)

'Web > 인스타 클론 코딩' 카테고리의 다른 글

[인스타그램 클론코딩] 12. 메신저 기능 구현(Back-End)  (0) 2023.02.16
[인스타그램 클론코딩] 11. 프로필 수정 기능 구현(Front-End)  (0) 2023.02.07
[인스타그램 클론코딩] 10. 게시물 댓글 기능 구현(Front-End)  (0) 2023.02.07
[인스타그램 클론코딩] 10. 게시물 댓글 기능 구현(Back-End)  (0) 2023.02.07
[인스타그램 클론코딩] 09. 게시물 좋아요 기능 구현(Front-End)  (0) 2023.02.04
'Web/인스타 클론 코딩' 카테고리의 다른 글
  • [인스타그램 클론코딩] 12. 메신저 기능 구현(Back-End)
  • [인스타그램 클론코딩] 11. 프로필 수정 기능 구현(Front-End)
  • [인스타그램 클론코딩] 10. 게시물 댓글 기능 구현(Front-End)
  • [인스타그램 클론코딩] 10. 게시물 댓글 기능 구현(Back-End)
뚝딱뚝딱2
뚝딱뚝딱2
  • 뚝딱뚝딱2
    개발도상국
    뚝딱뚝딱2
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 공부
        • Java
        • Spring Boot
        • LORA
      • Web
        • 인스타 클론 코딩
        • GPT 응답 API 서버
        • Spring Boot 예외 처리
        • 코테 준비용 서비스 만들기
      • DevOps
        • 쿠버네티스
        • 서버 만들기
      • 코딩테스트
        • 알고리즘
      • 교육
        • 스파르타코딩클럽 - 내일배움단
        • 혼자 공부하는 컴퓨터 구조 운영체제
      • 잡다한것
  • 블로그 메뉴

    • 홈
  • 링크

    • GITHUB
  • 공지사항

  • 인기 글

  • 태그

    예외
    클론코딩
    티스토리챌린지
    spring boot
    OpenAI API
    클러스터
    인스타그램
    REST API
    mapstruct
    react
    스프링 부트
    백준
    리액트
    Entity
    MSA
    스프링부트
    오블완
    chat GPT
    Java
    쿠버네티스
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
뚝딱뚝딱2
[인스타그램 클론코딩] 11. 프로필 수정 기능 구현(Back-End)
상단으로

티스토리툴바