프로필 관련 내용은 기존에 만들어진 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 |