-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: PresignedUrl을 사용하여 이미지 업로드 기능 구현 #106
Changes from 19 commits
d50d0ec
3d431ae
a19d76a
80c0352
483c514
b515665
1975f39
b359a3a
8ead3bc
656ce44
668b7d3
452a25f
7d7f513
536ee49
cfbc205
ee79c30
903082f
89889b9
d7b58a9
adba0ed
c0f2905
4b03da5
eda01ec
cb9cfa3
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
package com.depromeet.domain.image.api; | ||
|
||
import com.depromeet.domain.image.application.ImageService; | ||
import com.depromeet.domain.image.dto.request.MissionRecordImageCreateRequest; | ||
import com.depromeet.domain.image.dto.request.MissionRecordImageUploadCompleteRequest; | ||
import com.depromeet.domain.image.dto.response.PresignedUrlResponse; | ||
import io.swagger.v3.oas.annotations.Operation; | ||
import io.swagger.v3.oas.annotations.tags.Tag; | ||
import jakarta.validation.Valid; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.web.bind.annotation.PostMapping; | ||
import org.springframework.web.bind.annotation.RequestBody; | ||
import org.springframework.web.bind.annotation.RestController; | ||
|
||
@Tag(name = "4. [이미지]", description = "이미지 관련 API입니다.") | ||
@RestController | ||
@RequiredArgsConstructor | ||
public class ImageController { | ||
private final ImageService imageService; | ||
|
||
@Operation( | ||
summary = "미션 기록 이미지 Presigned URL 생성", | ||
description = "미션 기록 이미지 Presigned URL를 생성합니다.") | ||
@PostMapping("/records/upload-url") | ||
public PresignedUrlResponse missionRecordPresignedUrlCreate( | ||
@Valid @RequestBody MissionRecordImageCreateRequest request) { | ||
return imageService.createMissionRecordPresignedUrl(request); | ||
} | ||
|
||
@Operation(summary = "미션 기록 이미지 업로드 완료처리", description = "미션 기록 이미지 업로드 완료 시 호출하시면 됩니다.") | ||
@PostMapping("/records/upload-complete") | ||
public void missionRecordUploaded( | ||
@Valid @RequestBody MissionRecordImageUploadCompleteRequest request) { | ||
imageService.uploadCompleteMissionRecord(request); | ||
} | ||
} |
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 클래스 전체를 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 오 이부분 놓쳤네용 감사함니다 |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
package com.depromeet.domain.image.application; | ||
|
||
import com.amazonaws.HttpMethod; | ||
import com.amazonaws.services.s3.AmazonS3; | ||
import com.amazonaws.services.s3.Headers; | ||
import com.amazonaws.services.s3.model.CannedAccessControlList; | ||
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest; | ||
import com.depromeet.domain.image.domain.ImageFileExtension; | ||
import com.depromeet.domain.image.domain.ImageType; | ||
import com.depromeet.domain.image.dto.request.MissionRecordImageCreateRequest; | ||
import com.depromeet.domain.image.dto.request.MissionRecordImageUploadCompleteRequest; | ||
import com.depromeet.domain.image.dto.response.PresignedUrlResponse; | ||
import com.depromeet.domain.member.domain.Member; | ||
import com.depromeet.domain.mission.domain.Mission; | ||
import com.depromeet.domain.missionRecord.dao.MissionRecordRepository; | ||
import com.depromeet.domain.missionRecord.domain.MissionRecord; | ||
import com.depromeet.global.error.exception.CustomException; | ||
import com.depromeet.global.error.exception.ErrorCode; | ||
import com.depromeet.global.util.MemberUtil; | ||
import com.depromeet.global.util.SpringEnvironmentUtil; | ||
import com.depromeet.infra.config.storage.StorageProperties; | ||
import java.util.Date; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.stereotype.Service; | ||
import org.springframework.transaction.annotation.Transactional; | ||
|
||
@Service | ||
@RequiredArgsConstructor | ||
@Transactional | ||
public class ImageService { | ||
private final MemberUtil memberUtil; | ||
private final SpringEnvironmentUtil springEnvironmentUtil; | ||
private final StorageProperties storageProperties; | ||
private final AmazonS3 amazonS3; | ||
private final MissionRecordRepository missionRecordRepository; | ||
|
||
public PresignedUrlResponse createMissionRecordPresignedUrl( | ||
MissionRecordImageCreateRequest request) { | ||
final Member currentMember = memberUtil.getCurrentMember(); | ||
|
||
MissionRecord missionRecord = findMissionRecordByMissionRecordId(request.missionRecordId()); | ||
|
||
Mission mission = missionRecord.getMission(); | ||
mission.validateUserMismatch(currentMember); | ||
|
||
String fileName = | ||
createFileName( | ||
ImageType.MISSION_RECORD, | ||
request.missionRecordId(), | ||
request.imageFileExtension()); | ||
GeneratePresignedUrlRequest generatePresignedUrlRequest = | ||
createGeneratePreSignedUrlRequest( | ||
storageProperties.bucket(), | ||
fileName, | ||
request.imageFileExtension().getUploadExtension()); | ||
|
||
String presignedUrl = amazonS3.generatePresignedUrl(generatePresignedUrlRequest).toString(); | ||
|
||
missionRecord.updateUploadStatusPending(); | ||
return PresignedUrlResponse.from(presignedUrl); | ||
} | ||
|
||
private MissionRecord findMissionRecordByMissionRecordId(Long request) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 쿼리 메서드 네이밍 규칙과 비슷하게 |
||
return missionRecordRepository | ||
.findById(request) | ||
.orElseThrow(() -> new CustomException(ErrorCode.MISSION_RECORD_NOT_FOUND)); | ||
} | ||
|
||
public void uploadCompleteMissionRecord(MissionRecordImageUploadCompleteRequest request) { | ||
final Member currentMember = memberUtil.getCurrentMember(); | ||
MissionRecord missionRecord = findMissionRecordByMissionRecordId(request.missionRecordId()); | ||
|
||
Mission mission = missionRecord.getMission(); | ||
mission.validateUserMismatch(currentMember); | ||
|
||
String imageUrl = | ||
storageProperties.endpoint() | ||
+ "/" | ||
+ storageProperties.bucket() | ||
+ "/" | ||
+ springEnvironmentUtil.getCurrentProfile() | ||
+ "/" | ||
+ ImageType.MISSION_RECORD.getValue() | ||
+ "/" | ||
+ request.missionRecordId() | ||
+ "/image." | ||
+ request.imageFileExtension().getUploadExtension(); | ||
missionRecord.updateUploadStatusComplete(request.remark(), imageUrl); | ||
} | ||
|
||
private String createFileName( | ||
ImageType imageType, Long targetId, ImageFileExtension imageFileExtension) { | ||
return springEnvironmentUtil.getCurrentProfile() | ||
+ "/" | ||
+ imageType.getValue() | ||
+ "/" | ||
+ targetId | ||
+ "/image." | ||
+ imageFileExtension.getUploadExtension(); | ||
} | ||
|
||
private GeneratePresignedUrlRequest createGeneratePreSignedUrlRequest( | ||
String bucket, String fileName, String fileExtension) { | ||
GeneratePresignedUrlRequest generatePresignedUrlRequest = | ||
new GeneratePresignedUrlRequest(bucket, fileName, HttpMethod.PUT) | ||
.withKey(fileName) | ||
.withContentType("image/" + fileExtension) | ||
.withExpiration(getPreSignedUrlExpiration()); | ||
|
||
generatePresignedUrlRequest.addRequestParameter( | ||
Headers.S3_CANNED_ACL, CannedAccessControlList.PublicRead.toString()); | ||
|
||
return generatePresignedUrlRequest; | ||
} | ||
|
||
private Date getPreSignedUrlExpiration() { | ||
Date expiration = new Date(); | ||
var expTimeMillis = expiration.getTime(); | ||
expTimeMillis += 1000 * 60 * 30; | ||
expiration.setTime(expTimeMillis); | ||
return expiration; | ||
} | ||
} |
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 만약 Request 받은 이미지의 확장자가 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 프론트와 이미지 확장자 스펙 논의 필요 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
package com.depromeet.domain.image.domain; | ||
|
||
import lombok.AllArgsConstructor; | ||
import lombok.Getter; | ||
|
||
@Getter | ||
@AllArgsConstructor | ||
public enum ImageFileExtension { | ||
JPEG("jpeg"), | ||
JPG("jpg"), | ||
PNG("png"), | ||
; | ||
|
||
private final String uploadExtension; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
package com.depromeet.domain.image.domain; | ||
|
||
import lombok.AllArgsConstructor; | ||
import lombok.Getter; | ||
|
||
@Getter | ||
@AllArgsConstructor | ||
public enum ImageType { | ||
MISSION_RECORD("mission_record"), | ||
MEMBER_PROFILE("member_profile"), | ||
MEMBER_BACKGROUND("member_background"), | ||
; | ||
private final String value; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package com.depromeet.domain.image.dto.request; | ||
|
||
import com.depromeet.domain.image.domain.ImageFileExtension; | ||
import io.swagger.v3.oas.annotations.media.Schema; | ||
import jakarta.validation.constraints.NotNull; | ||
|
||
public record MissionRecordImageCreateRequest( | ||
@NotNull(message = "미션 기록 ID는 비워둘 수 없습니다.") | ||
@Schema(description = "미션 기록 ID", defaultValue = "1") | ||
Long missionRecordId, | ||
@NotNull(message = "이미지 파일의 확장자는 비워둘 수 없습니다.") | ||
@Schema(description = "이미지 파일의 확장자", defaultValue = "JPEG") | ||
ImageFileExtension imageFileExtension) {} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
package com.depromeet.domain.image.dto.request; | ||
|
||
import com.depromeet.domain.image.domain.ImageFileExtension; | ||
import io.swagger.v3.oas.annotations.media.Schema; | ||
import jakarta.validation.constraints.NotNull; | ||
import jakarta.validation.constraints.Size; | ||
|
||
public record MissionRecordImageUploadCompleteRequest( | ||
@NotNull(message = "미션 기록 ID는 비워둘 수 없습니다.") | ||
@Schema(description = "미션 기록 ID", defaultValue = "1") | ||
Long missionRecordId, | ||
@NotNull(message = "이미지 파일의 확장자는 비워둘 수 없습니다.") | ||
@Schema(description = "이미지 파일의 확장자", defaultValue = "JPEG") | ||
ImageFileExtension imageFileExtension, | ||
@Size(max = 200, message = "미션 일지는 20자 이하까지만 입력 가능합니다.") String remark) {} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
package com.depromeet.domain.image.dto.response; | ||
|
||
import io.swagger.v3.oas.annotations.media.Schema; | ||
|
||
public record PresignedUrlResponse(@Schema(description = "Presigned URL") String presignedUrl) { | ||
public static PresignedUrlResponse from(String presignedUrl) { | ||
return new PresignedUrlResponse(presignedUrl); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,6 +2,8 @@ | |
|
||
import com.depromeet.domain.common.model.BaseTimeEntity; | ||
import com.depromeet.domain.mission.domain.Mission; | ||
import com.depromeet.global.error.exception.CustomException; | ||
import com.depromeet.global.error.exception.ErrorCode; | ||
import jakarta.persistence.Column; | ||
import jakarta.persistence.Entity; | ||
import jakarta.persistence.EnumType; | ||
|
@@ -77,4 +79,20 @@ public static MissionRecord createMissionRecord( | |
.mission(mission) | ||
.build(); | ||
} | ||
|
||
public void updateUploadStatusPending() { | ||
if (this.uploadStatus != ImageUploadStatus.NONE) { | ||
throw new CustomException(ErrorCode.MISSION_RECORD_UPLOAD_STATUS_IS_NOT_NONE); | ||
} | ||
this.uploadStatus = ImageUploadStatus.PENDING; | ||
} | ||
|
||
public void updateUploadStatusComplete(String remark, String imageUrl) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이미 |
||
if (this.uploadStatus != ImageUploadStatus.PENDING) { | ||
throw new CustomException(ErrorCode.MISSION_RECORD_UPLOAD_STATUS_IS_NOT_PENDING); | ||
} | ||
this.uploadStatus = ImageUploadStatus.COMPLETE; | ||
this.remark = remark; | ||
this.imageUrl = imageUrl; | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -23,13 +23,13 @@ public class MissionRecordService { | |
private final MissionRecordRepository missionRecordRepository; | ||
|
||
public Long createMissionRecord(MissionRecordCreateRequest request) { | ||
final Mission mission = findMission(request); | ||
final Mission mission = findMissionByMissionId(request.missionId()); | ||
final Member member = memberUtil.getCurrentMember(); | ||
|
||
Duration duration = | ||
Duration.ofMinutes(request.durationMin()).plusSeconds(request.durationSec()); | ||
|
||
validateMissionRecordUserMismatch(mission, member); | ||
mission.validateUserMismatch(member); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 현재 로그인한 멤버와 미션을 만든 멤버가 일치하는지까지는 비교할 수 있다고 보지만, 예외를 터트리는 건 미션 엔티티의 책임이 아니라고 보는데 어떻게 생각하시나요? 미션 엔티티는 자신의 상태를 논리적 모순 없이 잘 들고있기만 하면 되는 것이고 그걸 어기게 되는 경우(가령 미션을 만든 멤버가 null인 경우)에만 예외를 발생시켜야 하지 외부 상태에 대해서 예외를 발생시키는 것은 서비스 레이어에서 책임져야할 것 같아요. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ImageService와 MissionRecordService 에서 중복으로 사용되서 Mission으로 빼두었는데, |
||
validateMissionRecordDuration(duration); | ||
|
||
MissionRecord missionRecord = | ||
|
@@ -38,18 +38,12 @@ public Long createMissionRecord(MissionRecordCreateRequest request) { | |
return missionRecordRepository.save(missionRecord).getId(); | ||
} | ||
|
||
private Mission findMission(MissionRecordCreateRequest request) { | ||
private Mission findMissionByMissionId(Long missionId) { | ||
return missionRepository | ||
.findByMissionId(request.missionId()) | ||
.findByMissionId(missionId) | ||
.orElseThrow(() -> new CustomException(ErrorCode.MISSION_NOT_FOUND)); | ||
} | ||
|
||
private void validateMissionRecordUserMismatch(Mission mission, Member member) { | ||
if (!member.getId().equals(mission.getMember().getId())) { | ||
throw new CustomException(ErrorCode.MISSION_RECORD_USER_MISMATCH); | ||
} | ||
} | ||
|
||
private void validateMissionRecordDuration(Duration duration) { | ||
if (duration.getSeconds() > 3600L) { | ||
throw new CustomException(ErrorCode.MISSION_RECORD_DURATION_OVERBALANCE); | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Tag 값에 이미지 Numbering 4로 변경 가능하실까요??
아니면 나중에
응원하기
,팔로우
와 같이 도메인이 계속 생길 때 순서도 다같이 얘기 해보면 좋을 거 같아요~그리고 API 엔드포인트가 {도메인}/image이 아닌 image/{도메인} 으로 되어있어서 이렇게 하신 이유가 궁금해요!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
넘버링 해놓을게용, endpoint는 images제거 하도록 하겠슴니당