Skip to content

Commit d0ce1df

Browse files
committed
refactor: 프로필 이미지 업로드 시 기존 이미지 즉시 삭제
1 parent 8e9f664 commit d0ce1df

1 file changed

Lines changed: 32 additions & 3 deletions

File tree

src/main/java/com/back/web7_9_codecrete_be/domain/users/service/UserService.java

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import com.back.web7_9_codecrete_be.global.error.exception.BusinessException;
1414
import com.back.web7_9_codecrete_be.global.storage.FileStorageService;
1515
import lombok.RequiredArgsConstructor;
16+
import lombok.extern.slf4j.Slf4j;
1617
import org.springframework.security.crypto.password.PasswordEncoder;
1718
import org.springframework.stereotype.Service;
1819
import org.springframework.transaction.annotation.Transactional;
@@ -21,6 +22,7 @@
2122
import java.time.LocalDateTime;
2223
import java.util.UUID;
2324

25+
@Slf4j
2426
@Service
2527
@RequiredArgsConstructor
2628
@Transactional
@@ -32,6 +34,8 @@ public class UserService {
3234
private final UserRestoreTokenRedisRepository userRestoreTokenRedisRepository;
3335
private final EmailService emailService;
3436

37+
private static final long MAX_PROFILE_IMAGE_SIZE = 10 * 1024 * 1024; // 10MB
38+
3539
// 내 정보 조회
3640
@Transactional(readOnly = true)
3741
public UserResponse getMyInfo(User user) {
@@ -75,14 +79,39 @@ public String updateProfileImage(User user, MultipartFile file) {
7579
throw new BusinessException(UserErrorCode.INVALID_PROFILE_IMAGE);
7680
}
7781

78-
String imageUrl = fileStorageService.upload(file);
82+
if (file.getSize() > MAX_PROFILE_IMAGE_SIZE) {
83+
throw new BusinessException(UserErrorCode.PROFILE_IMAGE_SIZE_EXCEEDED);
84+
}
85+
86+
// 기존 이미지 URL 보관
87+
String oldImageUrl = user.getProfileImage();
88+
89+
// 새 이미지 업로드
90+
String newImageUrl = fileStorageService.upload(file, "users/profile");
7991

80-
user.updateProfileImage(imageUrl);
92+
// DB 업데이트
93+
user.updateProfileImage(newImageUrl);
8194
userRepository.save(user);
8295

83-
return imageUrl;
96+
// 기존 이미지 즉시 삭제
97+
// TODO: 추후 지연 삭제 스케줄러로 리팩토링
98+
if (oldImageUrl != null) {
99+
try {
100+
fileStorageService.delete(oldImageUrl);
101+
} catch (Exception e) {
102+
log.warn(
103+
"기존 프로필 이미지 삭제 실패 userId={}, url={}",
104+
user.getId(),
105+
oldImageUrl,
106+
e
107+
);
108+
}
109+
}
110+
111+
return newImageUrl;
84112
}
85113

114+
86115
// 활성 사용자 검증
87116
private void validateActiveUser(User user) {
88117
if (user.getIsDeleted()) {

0 commit comments

Comments
 (0)