diff --git a/.github/workflows/test-task.yml b/.github/workflows/test-task.yml new file mode 100644 index 00000000..9534fa80 --- /dev/null +++ b/.github/workflows/test-task.yml @@ -0,0 +1,50 @@ +name: Build test about test codes + +on: + push: + branches: [ "refactor/162-file-system-structure" ] ## 테스트하고자하는 브랜치 작성 + pull_request: + branches: [ "refactor/162-file-system-structure" ] + +jobs: + deploy: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@v4 + + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + + - name: make application.yml + run: | + mkdir -p ./src/main/resources + cd ./src/main/resources + touch ./application.yml + touch ./application-common.yml + touch ./application-prod.yml + echo "${{ secrets.APPLICATION }}" > ./application.yml + echo "${{ secrets.COMMON }}" > ./application-common.yml + echo "${{ secrets.PROD }}" > ./application-prod.yml + + - name: make test application.yml + run: | + mkdir -p ./src/test/resources + cd ./src/test/resources + touch ./application.yml + touch ./application-test.yml + echo "${{ secrets.APPLICATION_TEST }}" > ./application.yml + echo "${{ secrets.TEST }}" > ./application-test.yml + + - name: Grant execute permission for gradlew + run: chmod +x ./gradlew + shell: bash + + - name: Build and Test + run: ./gradlew clean build test + diff --git a/src/main/java/com/genius/gitget/admin/topic/controller/TopicController.java b/src/main/java/com/genius/gitget/admin/topic/controller/TopicController.java index e86f0bc5..9fe968ae 100644 --- a/src/main/java/com/genius/gitget/admin/topic/controller/TopicController.java +++ b/src/main/java/com/genius/gitget/admin/topic/controller/TopicController.java @@ -1,15 +1,17 @@ package com.genius.gitget.admin.topic.controller; +import static com.genius.gitget.global.util.exception.SuccessCode.CREATED; +import static com.genius.gitget.global.util.exception.SuccessCode.SUCCESS; + import com.genius.gitget.admin.topic.dto.TopicCreateRequest; import com.genius.gitget.admin.topic.dto.TopicDetailResponse; +import com.genius.gitget.admin.topic.dto.TopicIndexResponse; import com.genius.gitget.admin.topic.dto.TopicPagingResponse; import com.genius.gitget.admin.topic.dto.TopicUpdateRequest; import com.genius.gitget.admin.topic.service.TopicService; -import com.genius.gitget.global.util.exception.SuccessCode; import com.genius.gitget.global.util.response.dto.CommonResponse; import com.genius.gitget.global.util.response.dto.PagingResponse; import com.genius.gitget.global.util.response.dto.SingleResponse; -import java.io.IOException; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -21,10 +23,9 @@ import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; @RestController @RequiredArgsConstructor @@ -40,40 +41,42 @@ public ResponseEntity> getAllTopics( Page allTopics = topicService.getAllTopics(pageable); return ResponseEntity.ok().body( - new PagingResponse<>(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage(), allTopics) + new PagingResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), allTopics) ); } // 토픽 상세 정보 요청 @GetMapping("/{id}") - public ResponseEntity> getTopicById(@PathVariable Long id) throws IOException { + public ResponseEntity> getTopicById(@PathVariable Long id) { TopicDetailResponse topicDetail = topicService.getTopicById(id); return ResponseEntity.ok().body( - new SingleResponse<>(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage(), topicDetail) + new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), topicDetail) ); } // 토픽 생성 요청 @PostMapping - public ResponseEntity createTopic( - @RequestPart(value = "data") TopicCreateRequest topicCreateRequest, - @RequestPart(value = "files", required = false) MultipartFile multipartFile, - @RequestPart(value = "type") String type) { - topicService.createTopic(topicCreateRequest, multipartFile, type); + public ResponseEntity> createTopic( + @RequestBody TopicCreateRequest topicCreateRequest) { + Long topicId = topicService.createTopic(topicCreateRequest); + TopicIndexResponse topicUpdateResponse = new TopicIndexResponse(topicId); + return ResponseEntity.ok().body( - new CommonResponse(SuccessCode.CREATED.getStatus(), SuccessCode.CREATED.getMessage()) + new SingleResponse<>( + CREATED.getStatus(), CREATED.getMessage(), topicUpdateResponse) ); } // 토픽 수정 요청 @PatchMapping("/{id}") - public ResponseEntity updateTopic(@PathVariable Long id, - @RequestPart(value = "data") TopicUpdateRequest topicUpdateRequest, - @RequestPart(value = "files", required = false) MultipartFile multipartFile, - @RequestPart(value = "type") String type) { - topicService.updateTopic(id, topicUpdateRequest, multipartFile, type); + public ResponseEntity> updateTopic( + @PathVariable Long id, + @RequestBody TopicUpdateRequest topicUpdateRequest) { + Long topicId = topicService.updateTopic(id, topicUpdateRequest); + TopicIndexResponse topicUpdateResponse = new TopicIndexResponse(topicId); + return ResponseEntity.ok().body( - new CommonResponse(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage()) + new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), topicUpdateResponse) ); } @@ -82,7 +85,7 @@ public ResponseEntity updateTopic(@PathVariable Long id, public ResponseEntity deleteTopic(@PathVariable Long id) { topicService.deleteTopic(id); return ResponseEntity.ok().body( - new CommonResponse(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage()) + new CommonResponse(SUCCESS.getStatus(), SUCCESS.getMessage()) ); } } \ No newline at end of file diff --git a/src/main/java/com/genius/gitget/admin/topic/domain/Topic.java b/src/main/java/com/genius/gitget/admin/topic/domain/Topic.java index 64ba5ca3..9f419fe2 100644 --- a/src/main/java/com/genius/gitget/admin/topic/domain/Topic.java +++ b/src/main/java/com/genius/gitget/admin/topic/domain/Topic.java @@ -1,6 +1,7 @@ package com.genius.gitget.admin.topic.domain; import com.genius.gitget.challenge.instance.domain.Instance; +import com.genius.gitget.global.file.domain.FileHolder; import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.util.domain.BaseTimeEntity; import jakarta.persistence.CascadeType; @@ -26,7 +27,7 @@ @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @Table(name = "topic") -public class Topic extends BaseTimeEntity { +public class Topic extends BaseTimeEntity implements FileHolder { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "topic_id") @@ -73,10 +74,12 @@ public void updateNotExistInstance(String title, String description, String tags this.pointPerPerson = pointPerPerson; } + @Override public Optional getFiles() { return Optional.ofNullable(this.files); } + @Override public void setFiles(Files files) { this.files = files; } diff --git a/src/main/java/com/genius/gitget/admin/topic/dto/TopicDetailResponse.java b/src/main/java/com/genius/gitget/admin/topic/dto/TopicDetailResponse.java index 77f66661..f74be401 100644 --- a/src/main/java/com/genius/gitget/admin/topic/dto/TopicDetailResponse.java +++ b/src/main/java/com/genius/gitget/admin/topic/dto/TopicDetailResponse.java @@ -1,16 +1,19 @@ package com.genius.gitget.admin.topic.dto; import com.genius.gitget.admin.topic.domain.Topic; -import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.file.dto.FileResponse; -import java.io.IOException; -import java.util.Optional; import lombok.Builder; @Builder -public record TopicDetailResponse(Long topicId, String title, String tags, - String description, String notice, int pointPerPerson, FileResponse fileResponse) { - public static TopicDetailResponse createByEntity(Topic topic, Optional files) throws IOException { +public record TopicDetailResponse( + Long topicId, + String title, + String tags, + String description, + String notice, + int pointPerPerson, + FileResponse fileResponse) { + public static TopicDetailResponse createByEntity(Topic topic, FileResponse fileResponse) { return TopicDetailResponse.builder() .topicId(topic.getId()) .title(topic.getTitle()) @@ -18,7 +21,7 @@ public static TopicDetailResponse createByEntity(Topic topic, Optional fi .description(topic.getDescription()) .notice(topic.getNotice()) .pointPerPerson(topic.getPointPerPerson()) - .fileResponse(FileResponse.create(files)) + .fileResponse(fileResponse) .build(); } } diff --git a/src/main/java/com/genius/gitget/admin/topic/dto/TopicIndexResponse.java b/src/main/java/com/genius/gitget/admin/topic/dto/TopicIndexResponse.java new file mode 100644 index 00000000..6e525cd3 --- /dev/null +++ b/src/main/java/com/genius/gitget/admin/topic/dto/TopicIndexResponse.java @@ -0,0 +1,6 @@ +package com.genius.gitget.admin.topic.dto; + +public record TopicIndexResponse( + Long topicId +) { +} diff --git a/src/main/java/com/genius/gitget/admin/topic/dto/TopicPagingResponse.java b/src/main/java/com/genius/gitget/admin/topic/dto/TopicPagingResponse.java index a81e012f..a4e091ba 100644 --- a/src/main/java/com/genius/gitget/admin/topic/dto/TopicPagingResponse.java +++ b/src/main/java/com/genius/gitget/admin/topic/dto/TopicPagingResponse.java @@ -1,20 +1,17 @@ package com.genius.gitget.admin.topic.dto; import com.genius.gitget.admin.topic.domain.Topic; -import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.file.dto.FileResponse; -import java.io.IOException; -import java.util.Optional; import lombok.Builder; @Builder public record TopicPagingResponse(Long topicId, String title, FileResponse fileResponse) { - public static TopicPagingResponse createByEntity(Topic topic, Optional files) throws IOException { + public static TopicPagingResponse createByEntity(Topic topic, FileResponse fileResponse) { return TopicPagingResponse.builder() .topicId(topic.getId()) .title(topic.getTitle()) - .fileResponse(FileResponse.create(files)) + .fileResponse(fileResponse) .build(); } } diff --git a/src/main/java/com/genius/gitget/admin/topic/service/TopicService.java b/src/main/java/com/genius/gitget/admin/topic/service/TopicService.java index bcbfdbd7..6b22a5d8 100644 --- a/src/main/java/com/genius/gitget/admin/topic/service/TopicService.java +++ b/src/main/java/com/genius/gitget/admin/topic/service/TopicService.java @@ -6,19 +6,16 @@ import com.genius.gitget.admin.topic.dto.TopicPagingResponse; import com.genius.gitget.admin.topic.dto.TopicUpdateRequest; import com.genius.gitget.admin.topic.repository.TopicRepository; -import com.genius.gitget.global.file.domain.Files; +import com.genius.gitget.global.file.dto.FileResponse; import com.genius.gitget.global.file.service.FilesService; import com.genius.gitget.global.util.exception.BusinessException; import com.genius.gitget.global.util.exception.ErrorCode; -import java.io.IOException; -import java.util.Optional; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.multipart.MultipartFile; @Service @RequiredArgsConstructor @@ -35,28 +32,21 @@ public Page getAllTopics(Pageable pageable) { } private TopicPagingResponse mapToTopicPagingResponse(Topic topic) { - try { - return TopicPagingResponse.createByEntity(topic, topic.getFiles()); - } catch (IOException e) { - throw new BusinessException(e); - } + FileResponse fileResponse = filesService.convertToFileResponse(topic.getFiles()); + return TopicPagingResponse.createByEntity(topic, fileResponse); } // 토픽 상세정보 요청 - public TopicDetailResponse getTopicById(Long id) throws IOException { - Topic topic = topicRepository.findById(id).orElseThrow(() -> new BusinessException(ErrorCode.TOPIC_NOT_FOUND)); - return TopicDetailResponse.createByEntity(topic, topic.getFiles()); + public TopicDetailResponse getTopicById(Long id) { + Topic topic = topicRepository.findById(id) + .orElseThrow(() -> new BusinessException(ErrorCode.TOPIC_NOT_FOUND)); + FileResponse fileResponse = filesService.convertToFileResponse(topic.getFiles()); + return TopicDetailResponse.createByEntity(topic, fileResponse); } // 토픽 생성 요청 @Transactional - public Long createTopic(TopicCreateRequest topicCreateRequest, MultipartFile multipartFile, String type) { - System.out.println("토픽 생성 요청"); - System.out.println(topicCreateRequest.title()); - System.out.println(multipartFile.getOriginalFilename()); - System.out.println(type); - Files uploadedFile = filesService.uploadFile(multipartFile, type); - + public Long createTopic(TopicCreateRequest topicCreateRequest) { Topic topic = Topic.builder() .title(topicCreateRequest.title()) .description(topicCreateRequest.description()) @@ -65,8 +55,6 @@ public Long createTopic(TopicCreateRequest topicCreateRequest, MultipartFile mul .notice(topicCreateRequest.notice()) .build(); - topic.setFiles(uploadedFile); - Topic savedTopic = topicRepository.save(topic); return savedTopic.getId(); @@ -74,13 +62,9 @@ public Long createTopic(TopicCreateRequest topicCreateRequest, MultipartFile mul // 토픽 업데이트 요청 @Transactional - public void updateTopic(Long id, TopicUpdateRequest topicUpdateRequest, MultipartFile multipartFile, String type) { - Topic topic = topicRepository.findById(id).orElseThrow(() -> new BusinessException(ErrorCode.TOPIC_NOT_FOUND)); - - Optional findTopicFile = topic.getFiles(); - Long findTopicFileId = findTopicFile.get().getId(); - - filesService.updateFile(findTopicFileId, multipartFile); + public Long updateTopic(Long id, TopicUpdateRequest topicUpdateRequest) { + Topic topic = topicRepository.findById(id) + .orElseThrow(() -> new BusinessException(ErrorCode.TOPIC_NOT_FOUND)); // 서버에서 한번 더 검사 boolean hasInstance = !topic.getInstanceList().isEmpty(); @@ -90,7 +74,7 @@ public void updateTopic(Long id, TopicUpdateRequest topicUpdateRequest, Multipar topic.updateNotExistInstance(topicUpdateRequest.title(), topicUpdateRequest.description(), topicUpdateRequest.tags(), topicUpdateRequest.notice(), topicUpdateRequest.pointPerPerson()); } - topicRepository.save(topic); + return topicRepository.save(topic).getId(); } // 토픽 삭제 요청 diff --git a/src/main/java/com/genius/gitget/challenge/certification/controller/CertificationController.java b/src/main/java/com/genius/gitget/challenge/certification/controller/CertificationController.java index e4ef1cd4..d29452c0 100644 --- a/src/main/java/com/genius/gitget/challenge/certification/controller/CertificationController.java +++ b/src/main/java/com/genius/gitget/challenge/certification/controller/CertificationController.java @@ -92,11 +92,11 @@ public ResponseEntity> getWeekCertification( @PathVariable Long instanceId ) { Participant participant = participantProvider.findByJoinInfo(userPrincipal.getUser().getId(), instanceId); - WeekResponse weekCertification = certificationService.getMyWeekCertifications( + WeekResponse weekResponse = certificationService.getMyWeekCertifications( participant.getId(), LocalDate.now()); return ResponseEntity.ok().body( - new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), weekCertification) + new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), weekResponse) ); } diff --git a/src/main/java/com/genius/gitget/challenge/certification/service/CertificationService.java b/src/main/java/com/genius/gitget/challenge/certification/service/CertificationService.java index 1dc94e46..d0e6cb40 100644 --- a/src/main/java/com/genius/gitget/challenge/certification/service/CertificationService.java +++ b/src/main/java/com/genius/gitget/challenge/certification/service/CertificationService.java @@ -177,8 +177,10 @@ public ActivatedResponse passCertification(Long userId, CertificationRequest cer return passed; }); - return ActivatedResponse.create(instance, certification.getCertificationStatus(), 0, - participant.getRepositoryName()); + FileResponse fileResponse = filesService.convertToFileResponse(instance.getFiles()); + //TODO: pass 했기 때문에 pass item이 필요없어 numOfPassItem을 0으로 전달하는 것 같음. but, 가독성이 떨어지기 때문에 수정 필요 + return ActivatedResponse.create(instance, certification.getCertificationStatus(), + 0, participant.getRepositoryName(), fileResponse); } private void validatePassCondition(Optional optional) { @@ -245,7 +247,7 @@ private void validCertificationCondition(Instance instance, LocalDate targetDate public InstancePreviewResponse getInstancePreview(Long instanceId) { Instance instance = instanceProvider.findById(instanceId); - FileResponse fileResponse = filesService.getEncodedFile(instance.getFiles()); + FileResponse fileResponse = filesService.convertToFileResponse(instance.getFiles()); return InstancePreviewResponse.createByEntity(instance, fileResponse); } diff --git a/src/main/java/com/genius/gitget/challenge/instance/controller/InstanceController.java b/src/main/java/com/genius/gitget/challenge/instance/controller/InstanceController.java index ff46756e..e0f6da8c 100644 --- a/src/main/java/com/genius/gitget/challenge/instance/controller/InstanceController.java +++ b/src/main/java/com/genius/gitget/challenge/instance/controller/InstanceController.java @@ -1,11 +1,14 @@ package com.genius.gitget.challenge.instance.controller; +import static com.genius.gitget.global.util.exception.SuccessCode.CREATED; +import static com.genius.gitget.global.util.exception.SuccessCode.SUCCESS; + import com.genius.gitget.challenge.instance.dto.crud.InstanceCreateRequest; import com.genius.gitget.challenge.instance.dto.crud.InstanceDetailResponse; +import com.genius.gitget.challenge.instance.dto.crud.InstanceIndexResponse; import com.genius.gitget.challenge.instance.dto.crud.InstancePagingResponse; import com.genius.gitget.challenge.instance.dto.crud.InstanceUpdateRequest; import com.genius.gitget.challenge.instance.service.InstanceService; -import com.genius.gitget.global.util.exception.SuccessCode; import com.genius.gitget.global.util.response.dto.CommonResponse; import com.genius.gitget.global.util.response.dto.PagingResponse; import com.genius.gitget.global.util.response.dto.SingleResponse; @@ -22,10 +25,9 @@ import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; @RestController @RequestMapping("/api/admin") @@ -40,7 +42,7 @@ public ResponseEntity> getAllInstances( Page instances = instanceService.getAllInstances(pageable); return ResponseEntity.ok().body( - new PagingResponse<>(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage(), instances) + new PagingResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), instances) ); } @@ -54,7 +56,7 @@ public ResponseEntity> getAllInstancesOfS pageRequest, id); return ResponseEntity.ok().body( - new PagingResponse<>(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage(), + new PagingResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), allInstancesOfSpecificTopic) ); } @@ -65,32 +67,32 @@ public ResponseEntity> getAllInstancesOfS public ResponseEntity> getInstanceById(@PathVariable Long id) { InstanceDetailResponse instanceDetails = instanceService.getInstanceById(id); return ResponseEntity.ok().body( - new SingleResponse<>(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage(), instanceDetails) + new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), instanceDetails) ); } // 인스턴스 생성 @PostMapping("/instance") - public ResponseEntity createInstance( - @RequestPart(value = "data") InstanceCreateRequest instanceCreateRequest, - @RequestPart(value = "files", required = false) MultipartFile multipartFile, - @RequestPart(value = "type", required = false) String type) { - instanceService.createInstance(instanceCreateRequest, multipartFile, type, LocalDate.now()); + public ResponseEntity> createInstance( + @RequestBody InstanceCreateRequest instanceCreateRequest) { + Long instanceId = instanceService.createInstance(instanceCreateRequest, LocalDate.now()); + InstanceIndexResponse instanceIndexResponse = new InstanceIndexResponse(instanceId); + return ResponseEntity.ok().body( - new CommonResponse(SuccessCode.CREATED.getStatus(), SuccessCode.CREATED.getMessage()) + new SingleResponse<>(CREATED.getStatus(), CREATED.getMessage(), instanceIndexResponse) ); } // 인스턴스 수정 @PatchMapping("/instance/{id}") - public ResponseEntity updateInstance(@PathVariable Long id, - @RequestPart(value = "data") InstanceUpdateRequest instanceUpdateRequest, - @RequestPart(value = "files", required = false) MultipartFile multipartFile, - @RequestPart(value = "type") String type) { + public ResponseEntity> updateInstance( + @PathVariable Long id, + @RequestBody InstanceUpdateRequest instanceUpdateRequest) { - instanceService.updateInstance(id, instanceUpdateRequest, multipartFile, type); + Long instanceId = instanceService.updateInstance(id, instanceUpdateRequest); + InstanceIndexResponse instanceIndexResponse = new InstanceIndexResponse(instanceId); return ResponseEntity.ok().body( - new CommonResponse(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage()) + new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), instanceIndexResponse) ); } @@ -99,7 +101,7 @@ public ResponseEntity updateInstance(@PathVariable Long id, public ResponseEntity deleteInstance(@PathVariable Long id) { instanceService.deleteInstance(id); return ResponseEntity.ok().body( - new CommonResponse(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage()) + new CommonResponse(SUCCESS.getStatus(), SUCCESS.getMessage()) ); } } \ No newline at end of file diff --git a/src/main/java/com/genius/gitget/challenge/instance/domain/Instance.java b/src/main/java/com/genius/gitget/challenge/instance/domain/Instance.java index 2b0bf744..996bd8f3 100644 --- a/src/main/java/com/genius/gitget/challenge/instance/domain/Instance.java +++ b/src/main/java/com/genius/gitget/challenge/instance/domain/Instance.java @@ -6,6 +6,7 @@ import com.genius.gitget.challenge.instance.dto.crud.InstanceCreateRequest; import com.genius.gitget.challenge.likes.domain.Likes; import com.genius.gitget.challenge.participant.domain.Participant; +import com.genius.gitget.global.file.domain.FileHolder; import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.util.exception.BusinessException; import com.genius.gitget.global.util.exception.ErrorCode; @@ -40,7 +41,7 @@ @NoArgsConstructor(access = AccessLevel.PROTECTED) @DynamicInsert @Table(name = "instance") -public class Instance { +public class Instance implements FileHolder { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "instance_id") @@ -157,13 +158,12 @@ public int getLikesCount() { return this.likesList.size(); } - /* - * 파일 조회 - * */ + @Override public Optional getFiles() { return Optional.ofNullable(this.files); } + @Override public void setFiles(Files files) { this.files = files; } diff --git a/src/main/java/com/genius/gitget/challenge/instance/dto/crud/InstanceDetailResponse.java b/src/main/java/com/genius/gitget/challenge/instance/dto/crud/InstanceDetailResponse.java index 0779d056..3850a936 100644 --- a/src/main/java/com/genius/gitget/challenge/instance/dto/crud/InstanceDetailResponse.java +++ b/src/main/java/com/genius/gitget/challenge/instance/dto/crud/InstanceDetailResponse.java @@ -1,10 +1,8 @@ package com.genius.gitget.challenge.instance.dto.crud; import com.genius.gitget.challenge.instance.domain.Instance; -import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.file.dto.FileResponse; import java.time.LocalDateTime; -import java.util.Optional; import lombok.Builder; @Builder @@ -13,7 +11,7 @@ public record InstanceDetailResponse(Long topicId, Long instanceId, String title String tags, String notice, LocalDateTime startedAt, LocalDateTime completedAt, String certificationMethod, FileResponse fileResponse) { - public static InstanceDetailResponse createByEntity(Instance instance, Optional files) { + public static InstanceDetailResponse createByEntity(Instance instance, FileResponse fileResponse) { return InstanceDetailResponse.builder() .topicId(instance.getTopic().getId()) .instanceId(instance.getId()) @@ -25,7 +23,7 @@ public static InstanceDetailResponse createByEntity(Instance instance, Optional< .startedAt(instance.getStartedDate()) .completedAt(instance.getCompletedDate()) .certificationMethod(instance.getCertificationMethod()) - .fileResponse(FileResponse.create(files)) + .fileResponse(fileResponse) .build(); } } diff --git a/src/main/java/com/genius/gitget/challenge/instance/dto/crud/InstanceIndexResponse.java b/src/main/java/com/genius/gitget/challenge/instance/dto/crud/InstanceIndexResponse.java new file mode 100644 index 00000000..0deaa84c --- /dev/null +++ b/src/main/java/com/genius/gitget/challenge/instance/dto/crud/InstanceIndexResponse.java @@ -0,0 +1,6 @@ +package com.genius.gitget.challenge.instance.dto.crud; + +public record InstanceIndexResponse( + Long instanceId +) { +} diff --git a/src/main/java/com/genius/gitget/challenge/instance/dto/crud/InstancePagingResponse.java b/src/main/java/com/genius/gitget/challenge/instance/dto/crud/InstancePagingResponse.java index 9ffa1d31..26bfbbd8 100644 --- a/src/main/java/com/genius/gitget/challenge/instance/dto/crud/InstancePagingResponse.java +++ b/src/main/java/com/genius/gitget/challenge/instance/dto/crud/InstancePagingResponse.java @@ -1,24 +1,26 @@ package com.genius.gitget.challenge.instance.dto.crud; import com.genius.gitget.challenge.instance.domain.Instance; -import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.file.dto.FileResponse; -import java.io.IOException; import java.time.LocalDateTime; -import java.util.Optional; import lombok.Builder; @Builder -public record InstancePagingResponse(Long topicId, Long instanceId, String title, - LocalDateTime startedAt, LocalDateTime completedAt, FileResponse fileResponse) { - public static InstancePagingResponse createByEntity(Instance instance, Optional files) throws IOException { +public record InstancePagingResponse( + Long topicId, + Long instanceId, + String title, + LocalDateTime startedAt, + LocalDateTime completedAt, + FileResponse fileResponse) { + public static InstancePagingResponse createByEntity(Instance instance, FileResponse fileResponse) { return InstancePagingResponse.builder() .topicId(instance.getTopic().getId()) .instanceId(instance.getId()) .title(instance.getTitle()) .startedAt(instance.getStartedDate()) .completedAt(instance.getCompletedDate()) - .fileResponse(FileResponse.create(files)) + .fileResponse(fileResponse) .build(); } } diff --git a/src/main/java/com/genius/gitget/challenge/instance/dto/detail/InstanceResponse.java b/src/main/java/com/genius/gitget/challenge/instance/dto/detail/InstanceResponse.java index 925e4de6..de2e1fcb 100644 --- a/src/main/java/com/genius/gitget/challenge/instance/dto/detail/InstanceResponse.java +++ b/src/main/java/com/genius/gitget/challenge/instance/dto/detail/InstanceResponse.java @@ -26,7 +26,8 @@ public record InstanceResponse( FileResponse fileResponse ) { - public static InstanceResponse createByEntity(Instance instance, LikesInfo likesInfo, JoinStatus joinStatus) { + public static InstanceResponse createByEntity(Instance instance, LikesInfo likesInfo, + JoinStatus joinStatus, FileResponse fileResponse) { LocalDate startedLocalDate = instance.getStartedDate().toLocalDate(); LocalDate completedLocalDate = instance.getCompletedDate().toLocalDate(); return InstanceResponse.builder() @@ -43,7 +44,7 @@ public static InstanceResponse createByEntity(Instance instance, LikesInfo likes .certificationMethod(instance.getCertificationMethod()) .joinStatus(joinStatus) .likesInfo(likesInfo) - .fileResponse(FileResponse.create(instance.getFiles())) + .fileResponse(fileResponse) .build(); } } diff --git a/src/main/java/com/genius/gitget/challenge/instance/dto/home/HomeInstanceResponse.java b/src/main/java/com/genius/gitget/challenge/instance/dto/home/HomeInstanceResponse.java index 479d12c3..b0235412 100644 --- a/src/main/java/com/genius/gitget/challenge/instance/dto/home/HomeInstanceResponse.java +++ b/src/main/java/com/genius/gitget/challenge/instance/dto/home/HomeInstanceResponse.java @@ -1,10 +1,7 @@ package com.genius.gitget.challenge.instance.dto.home; import com.genius.gitget.challenge.instance.domain.Instance; -import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.file.dto.FileResponse; -import java.io.IOException; -import java.util.Optional; import lombok.Builder; @Builder @@ -15,13 +12,13 @@ public record HomeInstanceResponse( int pointPerPerson, FileResponse fileResponse ) { - public static HomeInstanceResponse createByEntity(Instance instance, Optional files) throws IOException { + public static HomeInstanceResponse createByEntity(Instance instance, FileResponse fileResponse) { return HomeInstanceResponse.builder() .instanceId(instance.getId()) .title(instance.getTitle()) .participantCnt(instance.getParticipantCount()) .pointPerPerson(instance.getPointPerPerson()) - .fileResponse(FileResponse.create(files)) + .fileResponse(fileResponse) .build(); } } diff --git a/src/main/java/com/genius/gitget/challenge/instance/dto/search/InstanceSearchResponse.java b/src/main/java/com/genius/gitget/challenge/instance/dto/search/InstanceSearchResponse.java index 6dcd98b5..a618cb8f 100644 --- a/src/main/java/com/genius/gitget/challenge/instance/dto/search/InstanceSearchResponse.java +++ b/src/main/java/com/genius/gitget/challenge/instance/dto/search/InstanceSearchResponse.java @@ -1,9 +1,6 @@ package com.genius.gitget.challenge.instance.dto.search; -import com.genius.gitget.global.file.domain.Files; -import com.genius.gitget.global.file.dto.FileResponse; import com.querydsl.core.annotations.QueryProjection; -import java.util.Optional; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @@ -16,17 +13,15 @@ public class InstanceSearchResponse { private String keyword; private int pointPerPerson; private int participantCount; - private FileResponse fileResponse; @Builder @QueryProjection public InstanceSearchResponse(Long topicId, Long instanceId, String keyword, int pointPerPerson, - int participantCount, Files files) { + int participantCount) { this.topicId = topicId; this.instanceId = instanceId; this.keyword = keyword; this.pointPerPerson = pointPerPerson; this.participantCount = participantCount; - this.fileResponse = FileResponse.create(Optional.of(files)); } } \ No newline at end of file diff --git a/src/main/java/com/genius/gitget/challenge/instance/repository/SearchRepositoryImpl.java b/src/main/java/com/genius/gitget/challenge/instance/repository/SearchRepositoryImpl.java index 0fcd8671..d147362c 100644 --- a/src/main/java/com/genius/gitget/challenge/instance/repository/SearchRepositoryImpl.java +++ b/src/main/java/com/genius/gitget/challenge/instance/repository/SearchRepositoryImpl.java @@ -1,7 +1,6 @@ package com.genius.gitget.challenge.instance.repository; import static com.genius.gitget.challenge.instance.domain.QInstance.instance; -import static com.genius.gitget.global.file.domain.QFiles.files; import com.genius.gitget.challenge.instance.domain.Progress; import com.genius.gitget.challenge.instance.dto.search.InstanceSearchResponse; @@ -37,11 +36,8 @@ public Page search(Progress progressCond, String titleCo List content = queryFactory .select(new QInstanceSearchResponse( instance.topic.id, instance.id, instance.title, instance.pointPerPerson, - instance.participantCount, - instance.files)) + instance.participantCount)) .from(instance) - .leftJoin(instance.files, files) - .on(instance.files.id.eq(files.id)) .where(builder) .orderBy(instance.startedDate.desc()) .offset(pageable.getOffset()) @@ -51,7 +47,6 @@ public Page search(Progress progressCond, String titleCo JPAQuery countQuery = queryFactory .select(instance.count()) .from(instance) - .leftJoin(instance.files, files) .where(builder); return PageableExecutionUtils.getPage(content, pageable, countQuery::fetchOne); diff --git a/src/main/java/com/genius/gitget/challenge/instance/service/InstanceDetailService.java b/src/main/java/com/genius/gitget/challenge/instance/service/InstanceDetailService.java index 085cf009..a270009f 100644 --- a/src/main/java/com/genius/gitget/challenge/instance/service/InstanceDetailService.java +++ b/src/main/java/com/genius/gitget/challenge/instance/service/InstanceDetailService.java @@ -17,6 +17,8 @@ import com.genius.gitget.challenge.participant.service.ParticipantProvider; import com.genius.gitget.challenge.user.domain.User; import com.genius.gitget.challenge.user.service.UserService; +import com.genius.gitget.global.file.dto.FileResponse; +import com.genius.gitget.global.file.service.FilesService; import com.genius.gitget.global.util.exception.BusinessException; import java.util.Optional; import lombok.RequiredArgsConstructor; @@ -31,6 +33,7 @@ @RequiredArgsConstructor public class InstanceDetailService { private final UserService userService; + private final FilesService filesService; private final InstanceProvider instanceProvider; private final ParticipantProvider participantProvider; private final GithubProvider githubProvider; @@ -39,13 +42,14 @@ public class InstanceDetailService { public InstanceResponse getInstanceDetailInformation(User user, Long instanceId) { Instance instance = instanceProvider.findById(instanceId); + FileResponse fileResponse = filesService.convertToFileResponse(instance.getFiles()); LikesInfo likesInfo = getLikesInfo(user.getId(), instance); if (participantProvider.hasParticipant(user.getId(), instanceId)) { - return InstanceResponse.createByEntity(instance, likesInfo, JoinStatus.YES); + return InstanceResponse.createByEntity(instance, likesInfo, JoinStatus.YES, fileResponse); } - return InstanceResponse.createByEntity(instance, likesInfo, JoinStatus.NO); + return InstanceResponse.createByEntity(instance, likesInfo, JoinStatus.NO, fileResponse); } private LikesInfo getLikesInfo(Long userId, Instance instance) { diff --git a/src/main/java/com/genius/gitget/challenge/instance/service/InstanceHomeService.java b/src/main/java/com/genius/gitget/challenge/instance/service/InstanceHomeService.java index a5694c07..9d361b97 100644 --- a/src/main/java/com/genius/gitget/challenge/instance/service/InstanceHomeService.java +++ b/src/main/java/com/genius/gitget/challenge/instance/service/InstanceHomeService.java @@ -6,8 +6,8 @@ import com.genius.gitget.challenge.instance.dto.home.HomeInstanceResponse; import com.genius.gitget.challenge.instance.repository.InstanceRepository; import com.genius.gitget.challenge.user.domain.User; -import com.genius.gitget.global.util.exception.BusinessException; -import java.io.IOException; +import com.genius.gitget.global.file.dto.FileResponse; +import com.genius.gitget.global.file.service.FilesService; import java.util.Arrays; import java.util.List; import lombok.RequiredArgsConstructor; @@ -22,6 +22,7 @@ @Transactional(readOnly = true) @RequiredArgsConstructor public class InstanceHomeService { + private final FilesService filesService; private final InstanceRepository instanceRepository; public Slice getRecommendations(User user, Pageable pageable) { @@ -40,10 +41,7 @@ public Slice getInstancesByCondition(Pageable pageable) { } private HomeInstanceResponse mapToHomeInstanceResponse(Instance instance) { - try { - return HomeInstanceResponse.createByEntity(instance, instance.getFiles()); - } catch (IOException e) { - throw new BusinessException(e); - } + FileResponse fileResponse = filesService.convertToFileResponse(instance.getFiles()); + return HomeInstanceResponse.createByEntity(instance, fileResponse); } } diff --git a/src/main/java/com/genius/gitget/challenge/instance/service/InstanceService.java b/src/main/java/com/genius/gitget/challenge/instance/service/InstanceService.java index 428bfc8c..54b06415 100644 --- a/src/main/java/com/genius/gitget/challenge/instance/service/InstanceService.java +++ b/src/main/java/com/genius/gitget/challenge/instance/service/InstanceService.java @@ -13,19 +13,17 @@ import com.genius.gitget.challenge.instance.dto.crud.InstanceUpdateRequest; import com.genius.gitget.challenge.instance.repository.InstanceRepository; import com.genius.gitget.global.file.domain.Files; +import com.genius.gitget.global.file.dto.FileResponse; import com.genius.gitget.global.file.service.FilesService; import com.genius.gitget.global.util.exception.BusinessException; import com.genius.gitget.global.util.exception.ErrorCode; -import java.io.IOException; import java.time.LocalDate; -import java.util.Optional; import java.util.UUID; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.multipart.MultipartFile; @Service @RequiredArgsConstructor @@ -38,15 +36,11 @@ public class InstanceService { // 인스턴스 생성 @Transactional public Long createInstance(InstanceCreateRequest instanceCreateRequest, - MultipartFile multipartFile, String type, LocalDate currentDate) { // 토픽 조회 Topic topic = topicRepository.findById(instanceCreateRequest.topicId()) .orElseThrow(() -> new BusinessException(TOPIC_NOT_FOUND)); - // 파일 업로드 - Files uploadedFile = filesService.uploadFile(topic.getFiles(), multipartFile, type); - // 인스턴스 생성 일자 검증 validatePeriod(instanceCreateRequest, currentDate); @@ -60,7 +54,6 @@ public Long createInstance(InstanceCreateRequest instanceCreateRequest, // 연관 관계 설정 instance.setTopic(topic); - instance.setFiles(uploadedFile); return instanceRepository.save(instance).getId(); } @@ -83,7 +76,8 @@ public Page getAllInstances(Pageable pageable) { // 특정 토픽에 대한 리스트 조회 public Page getAllInstancesOfSpecificTopic(Pageable pageable, Long id) { - Topic topic = topicRepository.findById(id).orElseThrow(() -> new BusinessException(ErrorCode.MEMBER_NOT_FOUND)); + Topic topic = topicRepository.findById(id) + .orElseThrow(() -> new BusinessException(ErrorCode.MEMBER_NOT_FOUND)); Page instancesByTopicId = instanceRepository.findInstancesByTopicId(pageable, topic.getId()); return instancesByTopicId.map(this::mapToInstancePagingResponse); } @@ -93,7 +87,8 @@ public Page getAllInstancesOfSpecificTopic(Pageable page public InstanceDetailResponse getInstanceById(Long id) { Instance instanceDetails = instanceRepository.findById(id) .orElseThrow(() -> new BusinessException(INSTANCE_NOT_FOUND)); - return InstanceDetailResponse.createByEntity(instanceDetails, instanceDetails.getFiles()); + FileResponse fileResponse = filesService.convertToFileResponse(instanceDetails.getFiles()); + return InstanceDetailResponse.createByEntity(instanceDetails, fileResponse); } @@ -116,15 +111,10 @@ public void deleteInstance(Long id) { // 인스턴스 수정 @Transactional - public Long updateInstance(Long id, InstanceUpdateRequest instanceUpdateRequest, MultipartFile multipartFile, - String type) { + public Long updateInstance(Long id, InstanceUpdateRequest instanceUpdateRequest) { Instance existingInstance = instanceRepository.findById(id) .orElseThrow(() -> new BusinessException(INSTANCE_NOT_FOUND)); - Optional findInstanceFile = existingInstance.getFiles(); - Long findInstanceFileId = findInstanceFile.get().getId(); - filesService.updateFile(findInstanceFileId, multipartFile); - existingInstance.updateInstance(instanceUpdateRequest.description(), instanceUpdateRequest.notice(), instanceUpdateRequest.pointPerPerson(), instanceUpdateRequest.startedAt(), instanceUpdateRequest.completedAt(), instanceUpdateRequest.certificationMethod()); @@ -135,10 +125,7 @@ public Long updateInstance(Long id, InstanceUpdateRequest instanceUpdateRequest, } private InstancePagingResponse mapToInstancePagingResponse(Instance instance) { - try { - return InstancePagingResponse.createByEntity(instance, instance.getFiles()); - } catch (IOException e) { - throw new BusinessException(e); - } + FileResponse fileResponse = filesService.convertToFileResponse(instance.getFiles()); + return InstancePagingResponse.createByEntity(instance, fileResponse); } } diff --git a/src/main/java/com/genius/gitget/challenge/likes/controller/LikesController.java b/src/main/java/com/genius/gitget/challenge/likes/controller/LikesController.java index 652f7727..ce8a35d2 100644 --- a/src/main/java/com/genius/gitget/challenge/likes/controller/LikesController.java +++ b/src/main/java/com/genius/gitget/challenge/likes/controller/LikesController.java @@ -33,8 +33,9 @@ public class LikesController { // 좋아요 목록 조회 @GetMapping("/likes") - public ResponseEntity> getLikesListOfUser(Pageable pageable, - @AuthenticationPrincipal UserPrincipal userPrincipal) { + public ResponseEntity> getLikesListOfUser( + Pageable pageable, + @AuthenticationPrincipal UserPrincipal userPrincipal) { PageRequest pageRequest = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize()); Page likesResponses = likesService.getLikesList(userPrincipal.getUser(), pageRequest); diff --git a/src/main/java/com/genius/gitget/challenge/likes/dto/UserLikesResponse.java b/src/main/java/com/genius/gitget/challenge/likes/dto/UserLikesResponse.java index 41c708a2..bb32f3af 100644 --- a/src/main/java/com/genius/gitget/challenge/likes/dto/UserLikesResponse.java +++ b/src/main/java/com/genius/gitget/challenge/likes/dto/UserLikesResponse.java @@ -13,8 +13,8 @@ public class UserLikesResponse { private FileResponse fileResponse; @Builder - public UserLikesResponse(Long likesId, Long instanceId, String title, int pointPerPerson, - FileResponse fileResponse) { + public UserLikesResponse(Long likesId, Long instanceId, String title, + int pointPerPerson, FileResponse fileResponse) { this.likesId = likesId; this.instanceId = instanceId; this.title = title; diff --git a/src/main/java/com/genius/gitget/challenge/likes/service/LikesService.java b/src/main/java/com/genius/gitget/challenge/likes/service/LikesService.java index 36ddb912..df3c6030 100644 --- a/src/main/java/com/genius/gitget/challenge/likes/service/LikesService.java +++ b/src/main/java/com/genius/gitget/challenge/likes/service/LikesService.java @@ -9,6 +9,7 @@ import com.genius.gitget.challenge.user.domain.User; import com.genius.gitget.challenge.user.repository.UserRepository; import com.genius.gitget.global.file.dto.FileResponse; +import com.genius.gitget.global.file.service.FilesService; import com.genius.gitget.global.util.exception.BusinessException; import com.genius.gitget.global.util.exception.ErrorCode; import java.util.ArrayList; @@ -26,6 +27,7 @@ @Slf4j @Service public class LikesService { + private final FilesService filesService; private final UserRepository userRepository; private final InstanceRepository instanceRepository; private final LikesRepository likesRepository; @@ -43,12 +45,14 @@ public Page getLikesList(User user, Pageable pageable) { for (Likes like : likes) { Instance instance = like.getInstance(); + FileResponse fileResponse = filesService.convertToFileResponse(instance.getFiles()); + UserLikesResponse userLikesResponse = UserLikesResponse.builder() .likesId(like.getId()) .instanceId(instance.getId()) .title(instance.getTitle()) .pointPerPerson(instance.getPointPerPerson()) - .fileResponse(FileResponse.create(instance.getFiles())) + .fileResponse(fileResponse) .build(); userLikesResponses.add(userLikesResponse); @@ -64,7 +68,6 @@ public UserLikesAddResponse addLikes(User user, String identifier, Long instance User findUser = null; for (User userObject : userList) { - System.out.println("!!!!!!!!!" + userObject.getIdentifier() + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); if (userObject.getIdentifier().equals(identifier)) { findUser = userObject; } @@ -85,16 +88,6 @@ public void deleteLikes(User user, Long likesId) { likesRepository.deleteById(findLikes.getId()); } -// @Transactional -// public void deleteLikesLazy(User user, Long likesId) { -// try { -// likesRepository.deleteById(likesId); -// } catch (Exception e) { -// e.getStackTrace(); -// } -// } - - private List verifyUser(User user) { return userRepository.findAllByIdentifier(user.getIdentifier()); } diff --git a/src/main/java/com/genius/gitget/challenge/myChallenge/dto/ActivatedResponse.java b/src/main/java/com/genius/gitget/challenge/myChallenge/dto/ActivatedResponse.java index ce1ce8da..185d9545 100644 --- a/src/main/java/com/genius/gitget/challenge/myChallenge/dto/ActivatedResponse.java +++ b/src/main/java/com/genius/gitget/challenge/myChallenge/dto/ActivatedResponse.java @@ -22,7 +22,7 @@ public class ActivatedResponse extends ItemUseResponse { @Builder public ActivatedResponse(Long instanceId, String title, int pointPerPerson, String repository, - String certificateStatus, Long itemId, + String certificateStatus, int numOfPassItem, boolean canUsePassItem, FileResponse fileResponse) { this.instanceId = instanceId; this.title = title; @@ -35,7 +35,7 @@ public ActivatedResponse(Long instanceId, String title, int pointPerPerson, Stri } public static ActivatedResponse create(Instance instance, CertificateStatus certificateStatus, - int numOfPassItem, String repository) { + int numOfPassItem, String repository, FileResponse fileResponse) { boolean canUseItem = checkItemCondition(certificateStatus, numOfPassItem); return ActivatedResponse.builder() @@ -46,7 +46,7 @@ public static ActivatedResponse create(Instance instance, CertificateStatus cert .certificateStatus(certificateStatus.getTag()) .canUsePassItem(canUseItem) .numOfPassItem(canUseItem ? numOfPassItem : 0) - .fileResponse(FileResponse.create(instance.getFiles())) + .fileResponse(fileResponse) .build(); } diff --git a/src/main/java/com/genius/gitget/challenge/myChallenge/dto/DoneResponse.java b/src/main/java/com/genius/gitget/challenge/myChallenge/dto/DoneResponse.java index bd52bcd0..ac8a5788 100644 --- a/src/main/java/com/genius/gitget/challenge/myChallenge/dto/DoneResponse.java +++ b/src/main/java/com/genius/gitget/challenge/myChallenge/dto/DoneResponse.java @@ -40,7 +40,7 @@ public DoneResponse(Long instanceId, String title, int pointPerPerson, JoinResul public static DoneResponse createNotRewarded(Instance instance, Participant participant, - int numOfPointItem) { + int numOfPointItem, FileResponse fileResponse) { return DoneResponse.builder() .title(instance.getTitle()) .instanceId(instance.getId()) @@ -48,12 +48,12 @@ public static DoneResponse createNotRewarded(Instance instance, .joinResult(participant.getJoinResult()) .canGetReward(canGetReward(participant)) .numOfPointItem(numOfPointItem) - .fileResponse(FileResponse.create(instance.getFiles())) + .fileResponse(fileResponse) .build(); } public static DoneResponse createRewarded(Instance instance, Participant participant, - double achievementRate) { + double achievementRate, FileResponse fileResponse) { return DoneResponse.builder() .title(instance.getTitle()) .instanceId(instance.getId()) @@ -62,7 +62,7 @@ public static DoneResponse createRewarded(Instance instance, Participant partici .canGetReward(false) .rewardedPoints(participant.getRewardPoints()) .achievementRate(achievementRate) - .fileResponse(FileResponse.create(instance.getFiles())) + .fileResponse(fileResponse) .build(); } diff --git a/src/main/java/com/genius/gitget/challenge/myChallenge/service/MyChallengeService.java b/src/main/java/com/genius/gitget/challenge/myChallenge/service/MyChallengeService.java index c7d6ff10..88210647 100644 --- a/src/main/java/com/genius/gitget/challenge/myChallenge/service/MyChallengeService.java +++ b/src/main/java/com/genius/gitget/challenge/myChallenge/service/MyChallengeService.java @@ -1,11 +1,11 @@ package com.genius.gitget.challenge.myChallenge.service; import static com.genius.gitget.challenge.certification.domain.CertificateStatus.CERTIFICATED; -import static com.genius.gitget.store.item.domain.ItemCategory.CERTIFICATION_PASSER; -import static com.genius.gitget.store.item.domain.ItemCategory.POINT_MULTIPLIER; import static com.genius.gitget.challenge.participant.domain.JoinResult.SUCCESS; import static com.genius.gitget.challenge.participant.domain.RewardStatus.NO; import static com.genius.gitget.challenge.participant.domain.RewardStatus.YES; +import static com.genius.gitget.store.item.domain.ItemCategory.CERTIFICATION_PASSER; +import static com.genius.gitget.store.item.domain.ItemCategory.POINT_MULTIPLIER; import com.genius.gitget.challenge.certification.domain.CertificateStatus; import com.genius.gitget.challenge.certification.domain.Certification; @@ -13,9 +13,6 @@ import com.genius.gitget.challenge.certification.util.DateUtil; import com.genius.gitget.challenge.instance.domain.Instance; import com.genius.gitget.challenge.instance.domain.Progress; -import com.genius.gitget.store.item.domain.Item; -import com.genius.gitget.store.item.service.ItemProvider; -import com.genius.gitget.store.item.service.OrdersProvider; import com.genius.gitget.challenge.myChallenge.dto.ActivatedResponse; import com.genius.gitget.challenge.myChallenge.dto.DoneResponse; import com.genius.gitget.challenge.myChallenge.dto.PreActivityResponse; @@ -25,8 +22,12 @@ import com.genius.gitget.challenge.user.domain.User; import com.genius.gitget.challenge.user.service.UserService; import com.genius.gitget.global.file.dto.FileResponse; +import com.genius.gitget.global.file.service.FilesService; import com.genius.gitget.global.util.exception.BusinessException; import com.genius.gitget.global.util.exception.ErrorCode; +import com.genius.gitget.store.item.domain.Item; +import com.genius.gitget.store.item.service.ItemProvider; +import com.genius.gitget.store.item.service.OrdersProvider; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @@ -39,6 +40,7 @@ @RequiredArgsConstructor public class MyChallengeService { private final UserService userService; + private final FilesService filesService; private final ParticipantProvider participantProvider; private final CertificationProvider certificationProvider; private final ItemProvider itemProvider; @@ -51,6 +53,7 @@ public List getPreActivityInstances(User user, LocalDate ta for (Participant participant : participants) { Instance instance = participant.getInstance(); + FileResponse fileResponse = filesService.convertToFileResponse(instance.getFiles()); PreActivityResponse preActivityResponse = PreActivityResponse.builder() .instanceId(instance.getId()) @@ -58,7 +61,7 @@ public List getPreActivityInstances(User user, LocalDate ta .participantCount(instance.getParticipantCount()) .pointPerPerson(instance.getPointPerPerson()) .remainDays(DateUtil.getRemainDaysToStart(participant.getStartedDate(), targetDate)) - .fileResponse(FileResponse.create(instance.getFiles())) + .fileResponse(fileResponse) .build(); preActivity.add(preActivityResponse); } @@ -72,12 +75,14 @@ public List getDoneInstances(User user, LocalDate targetDate) { for (Participant participant : participants) { Instance instance = participant.getInstance(); + FileResponse fileResponse = filesService.convertToFileResponse(instance.getFiles()); // 포인트를 아직 수령하지 않았을 때 if (participant.getRewardStatus() == NO) { Item item = itemProvider.findAllByCategory(POINT_MULTIPLIER).get(0); int numOfPassItem = ordersProvider.countNumOfItem(user, item.getId()); - DoneResponse doneResponse = DoneResponse.createNotRewarded(instance, participant, numOfPassItem); + DoneResponse doneResponse = DoneResponse.createNotRewarded( + instance, participant, numOfPassItem, fileResponse); doneResponse.setItemId(item.getId()); done.add(doneResponse); continue; @@ -85,7 +90,8 @@ public List getDoneInstances(User user, LocalDate targetDate) { // 포인트를 수령했을 때 double achievementRate = getAchievementRate(instance, participant.getId(), targetDate); - DoneResponse doneResponse = DoneResponse.createRewarded(instance, participant, achievementRate); + DoneResponse doneResponse = DoneResponse.createRewarded( + instance, participant, achievementRate, fileResponse); done.add(doneResponse); } @@ -107,6 +113,7 @@ public List getActivatedInstances(User user, LocalDate target for (Participant participant : participants) { Instance instance = participant.getInstance(); + FileResponse fileResponse = filesService.convertToFileResponse(instance.getFiles()); Certification certification = certificationProvider.findByDate(targetDate, participant.getId()) .orElse(getDummyCertification()); @@ -116,7 +123,7 @@ public List getActivatedInstances(User user, LocalDate target ActivatedResponse activatedResponse = ActivatedResponse.create( instance, certification.getCertificationStatus(), - numOfPassItem, participant.getRepositoryName() + numOfPassItem, participant.getRepositoryName(), fileResponse ); activatedResponse.setItemId(item.getId()); activated.add(activatedResponse); @@ -139,6 +146,8 @@ public DoneResponse getRewards(RewardRequest rewardRequest, boolean useItem) { Participant participant = participantProvider.findByJoinInfo(user.getId(), rewardRequest.instanceId()); Instance instance = participant.getInstance(); + FileResponse fileResponse = filesService.convertToFileResponse(instance.getFiles()); + validRewardCondition(participant); int rewardPoints = instance.getPointPerPerson(); @@ -150,7 +159,7 @@ public DoneResponse getRewards(RewardRequest rewardRequest, boolean useItem) { double achievementRate = getAchievementRate(instance, participant.getId(), rewardRequest.targetDate()); participant.getRewards(rewardPoints); - return DoneResponse.createRewarded(instance, participant, achievementRate); + return DoneResponse.createRewarded(instance, participant, achievementRate, fileResponse); } private void validRewardCondition(Participant participant) { diff --git a/src/main/java/com/genius/gitget/challenge/user/controller/UserController.java b/src/main/java/com/genius/gitget/challenge/user/controller/UserController.java index 262c7a80..3c6eac51 100644 --- a/src/main/java/com/genius/gitget/challenge/user/controller/UserController.java +++ b/src/main/java/com/genius/gitget/challenge/user/controller/UserController.java @@ -12,11 +12,10 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; @RestController @RequiredArgsConstructor @@ -34,13 +33,13 @@ public ResponseEntity checkNicknameDuplicate(@RequestParam(value @PostMapping("/auth/signup") public ResponseEntity> signup( - @RequestPart(value = "data") SignupRequest signupRequest, - @RequestPart(value = "files") MultipartFile multipartFile) { - Long signupUserId = userService.signup(signupRequest, multipartFile); - String identifier = userService.findUserById(signupUserId).getIdentifier(); + @RequestBody SignupRequest signupRequest) { + Long userId = userService.signup(signupRequest); + String identifier = userService.findUserById(userId).getIdentifier(); + SignupResponse signupResponse = new SignupResponse(userId, identifier); return ResponseEntity.ok().body( - new SingleResponse<>(CREATED.getStatus(), CREATED.getMessage(), new SignupResponse(identifier)) + new SingleResponse<>(CREATED.getStatus(), CREATED.getMessage(), signupResponse) ); } } diff --git a/src/main/java/com/genius/gitget/challenge/user/domain/User.java b/src/main/java/com/genius/gitget/challenge/user/domain/User.java index 8ca1f675..aefd1ec9 100644 --- a/src/main/java/com/genius/gitget/challenge/user/domain/User.java +++ b/src/main/java/com/genius/gitget/challenge/user/domain/User.java @@ -2,6 +2,7 @@ import com.genius.gitget.challenge.likes.domain.Likes; import com.genius.gitget.challenge.participant.domain.Participant; +import com.genius.gitget.global.file.domain.FileHolder; import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.security.constants.ProviderInfo; import com.genius.gitget.global.util.domain.BaseTimeEntity; @@ -34,7 +35,7 @@ @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @Table(name = "users") -public class User extends BaseTimeEntity { +public class User extends BaseTimeEntity implements FileHolder { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "user_id") @@ -115,25 +116,24 @@ public long updatePoints(Long amount) { return this.point; } + @Override public Optional getFiles() { return Optional.ofNullable(this.files); } - //=== 연관관계 편의 메서드 ===// + @Override public void setFiles(Files files) { this.files = files; } + //=== 연관관계 편의 메서드 ===// + public void updateUser(String nickname, String information, String tags) { this.nickname = nickname; this.information = information; this.tags = tags; } - public void setPoint(Long point) { - this.point += point; - } - public void deleteLikesList() { this.likesList.clear(); } diff --git a/src/main/java/com/genius/gitget/challenge/user/dto/UserProfileInfo.java b/src/main/java/com/genius/gitget/challenge/user/dto/UserProfileInfo.java index 1bb36ba4..4c213c81 100644 --- a/src/main/java/com/genius/gitget/challenge/user/dto/UserProfileInfo.java +++ b/src/main/java/com/genius/gitget/challenge/user/dto/UserProfileInfo.java @@ -9,7 +9,7 @@ public record UserProfileInfo( Long frameId, FileResponse fileResponse ) { - public static UserProfileInfo createByEntity(User user, Long frameId) { - return new UserProfileInfo(user.getId(), user.getNickname(), frameId, FileResponse.create(user.getFiles())); + public static UserProfileInfo createByEntity(User user, Long frameId, FileResponse fileResponse) { + return new UserProfileInfo(user.getId(), user.getNickname(), frameId, fileResponse); } } diff --git a/src/main/java/com/genius/gitget/challenge/user/service/UserService.java b/src/main/java/com/genius/gitget/challenge/user/service/UserService.java index 0e786d41..5fee73c8 100644 --- a/src/main/java/com/genius/gitget/challenge/user/service/UserService.java +++ b/src/main/java/com/genius/gitget/challenge/user/service/UserService.java @@ -11,7 +11,7 @@ import com.genius.gitget.challenge.user.dto.SignupRequest; import com.genius.gitget.challenge.user.dto.UserProfileInfo; import com.genius.gitget.challenge.user.repository.UserRepository; -import com.genius.gitget.global.file.domain.Files; +import com.genius.gitget.global.file.dto.FileResponse; import com.genius.gitget.global.file.service.FilesService; import com.genius.gitget.global.security.dto.AuthResponse; import com.genius.gitget.global.util.exception.BusinessException; @@ -23,7 +23,6 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.multipart.MultipartFile; @Service @Slf4j @@ -55,7 +54,7 @@ public Long save(User user) { } @Transactional - public Long signup(SignupRequest requestUser, MultipartFile multipartFile) { + public Long signup(SignupRequest requestUser) { User user = findUserByIdentifier(requestUser.identifier()); isAlreadyRegistered(user); @@ -65,9 +64,6 @@ public Long signup(SignupRequest requestUser, MultipartFile multipartFile) { interest); updateRole(user); - Files files = filesService.uploadFile(multipartFile, "profile"); - user.setFiles(files); - return user.getId(); } @@ -108,6 +104,8 @@ public AuthResponse getUserAuthInfo(String identifier) { public UserProfileInfo getUserProfileInfo(User user) { Long frameId = ordersProvider.getUsingFrameItem(user.getId()).getId(); - return UserProfileInfo.createByEntity(user, frameId); + FileResponse fileResponse = filesService.convertToFileResponse(user.getFiles()); + + return UserProfileInfo.createByEntity(user, frameId, fileResponse); } } \ No newline at end of file diff --git a/src/main/java/com/genius/gitget/global/file/controller/FileTestController.java b/src/main/java/com/genius/gitget/global/file/controller/FileTestController.java new file mode 100644 index 00000000..8c7e2089 --- /dev/null +++ b/src/main/java/com/genius/gitget/global/file/controller/FileTestController.java @@ -0,0 +1,103 @@ +package com.genius.gitget.global.file.controller; + +import static com.genius.gitget.global.util.exception.SuccessCode.SUCCESS; + +import com.genius.gitget.global.file.domain.FileType; +import com.genius.gitget.global.file.domain.Files; +import com.genius.gitget.global.file.dto.FileResponse; +import com.genius.gitget.global.file.service.FileManager; +import com.genius.gitget.global.file.service.FilesService; +import com.genius.gitget.global.util.response.dto.CommonResponse; +import com.genius.gitget.global.util.response.dto.SingleResponse; +import java.util.Optional; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +/** + * FileManager의 기능을 별도로 테스트하기 위해 생성한 컨트롤러입니다. + */ +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/file/test") +public class FileTestController { + private final FilesService filesService; + private final FileManager fileManager; + + + @GetMapping("/{fileId}") + public ResponseEntity> download( + @PathVariable Long fileId + ) { + Files files = filesService.findById(fileId); + FileResponse fileResponse = filesService.convertToFileResponse(Optional.ofNullable(files)); + + return ResponseEntity.ok().body( + new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), fileResponse) + ); + } + + @PostMapping + public ResponseEntity> upload( + @RequestParam("files") MultipartFile multipartFile, + @RequestParam("type") String type + ) { + FileType fileType = FileType.findType(type); + Files files = filesService.uploadFile(multipartFile, fileType); + String encodedImage = fileManager.getEncodedImage(files); + FileResponse fileResponse = FileResponse.createExistFile(files.getId(), encodedImage); + + return ResponseEntity.ok().body( + new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), fileResponse) + ); + } + + @PatchMapping("/{fileId}") + public ResponseEntity> update( + @PathVariable Long fileId, + @RequestParam("files") MultipartFile multipartFile) { + Files files = filesService.updateFile(fileId, multipartFile); + String encodedImage = fileManager.getEncodedImage(files); + FileResponse fileResponse = FileResponse.createExistFile(files.getId(), encodedImage); + + return ResponseEntity.ok().body( + new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), fileResponse) + ); + } + + @PostMapping("/{fileId}") + public ResponseEntity> copy( + @PathVariable Long fileId, + @RequestParam("type") String type) { + + FileType fileType = FileType.findType(type); + Files files = filesService.findById(fileId); + Files copiedFile = filesService.copyFile(files, fileType); + + String encodedImage = fileManager.getEncodedImage(copiedFile); + FileResponse fileResponse = FileResponse.createExistFile(copiedFile.getId(), encodedImage); + + return ResponseEntity.ok().body( + new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), fileResponse) + ); + } + + @DeleteMapping("/{fileId}") + public ResponseEntity delete( + @PathVariable Long fileId + ) { + filesService.deleteFile(fileId); + + return ResponseEntity.ok().body( + new CommonResponse(SUCCESS.getStatus(), SUCCESS.getMessage()) + ); + } +} diff --git a/src/main/java/com/genius/gitget/global/file/controller/FilesController.java b/src/main/java/com/genius/gitget/global/file/controller/FilesController.java index 8048d856..71e270c0 100644 --- a/src/main/java/com/genius/gitget/global/file/controller/FilesController.java +++ b/src/main/java/com/genius/gitget/global/file/controller/FilesController.java @@ -1,24 +1,23 @@ package com.genius.gitget.global.file.controller; -import static com.genius.gitget.global.util.exception.SuccessCode.CREATED; import static com.genius.gitget.global.util.exception.SuccessCode.SUCCESS; -import com.genius.gitget.challenge.instance.dto.crud.InstanceCreateRequest; +import com.genius.gitget.global.file.domain.FileHolder; +import com.genius.gitget.global.file.domain.FileType; import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.file.dto.FileResponse; +import com.genius.gitget.global.file.service.FileHolderFinder; import com.genius.gitget.global.file.service.FilesService; -import com.genius.gitget.global.util.response.dto.CommonResponse; import com.genius.gitget.global.util.response.dto.SingleResponse; -import java.io.IOException; +import java.util.Optional; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @@ -27,52 +26,46 @@ @RequiredArgsConstructor @RequestMapping("/api/file") public class FilesController { + private final FileHolderFinder finder; private final FilesService filesService; - @PostMapping - public ResponseEntity> uploadImage( - @RequestPart(value = "data") InstanceCreateRequest instanceCreateRequest, - @RequestPart(value = "files") MultipartFile multipartFile, - @RequestPart(value = "type") String type) throws IOException { - Files files = filesService.uploadFile(multipartFile, type); - FileResponse fileResponse = FileResponse.createExistFile(files); + @PostMapping("/{id}") + public ResponseEntity> uploadFile( + @PathVariable Long id, + @RequestParam("type") String type, + @RequestParam(value = "files", required = false) MultipartFile multipartFile + ) { + FileType fileType = FileType.findType(type); + FileHolder fileHolder = finder.findByInfo(id, fileType); + Files files; - return ResponseEntity.ok().body( - new SingleResponse<>(CREATED.getStatus(), CREATED.getMessage(), fileResponse) - ); - } - - @GetMapping(value = {"/{fileId}"}) - public ResponseEntity> getImage(@PathVariable(name = "fileId") Long fileId) - throws IOException { - - FileResponse encodedFile = filesService.getEncodedFile(fileId); - - return ResponseEntity.ok().body( - new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), encodedFile) - ); - } + if (multipartFile == null && fileType == FileType.INSTANCE) { + files = filesService.copyTopicToInstance(fileHolder); + } else { + files = filesService.uploadFile(fileHolder, multipartFile, fileType); + } - @PostMapping("/{fileId}") - public ResponseEntity> updateImage( - @RequestPart(value = "files") MultipartFile multipartFile, - @PathVariable Long fileId - ) throws IOException { - Files files = filesService.updateFile(fileId, multipartFile); + FileResponse fileResponse = filesService.convertToFileResponse(Optional.ofNullable(files)); return ResponseEntity.ok().body( - new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), - FileResponse.createExistFile(files)) + new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), fileResponse) ); } - @DeleteMapping("/{fileId}") - public ResponseEntity deleteImage(@PathVariable Long fileId) throws IOException { - filesService.deleteFile(fileId); + @PatchMapping("/{id}") + public ResponseEntity> updateFile( + @PathVariable Long id, + @RequestParam("type") String type, + @RequestParam("files") MultipartFile multipartFile + ) { + FileType fileType = FileType.findType(type); + FileHolder fileHolder = finder.findByInfo(id, fileType); + Files files = filesService.updateFile(fileHolder.getFiles(), multipartFile); + FileResponse fileResponse = filesService.convertToFileResponse(Optional.ofNullable(files)); return ResponseEntity.ok().body( - new CommonResponse(SUCCESS.getStatus(), SUCCESS.getMessage()) + new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), fileResponse) ); } } \ No newline at end of file diff --git a/src/main/java/com/genius/gitget/global/file/domain/FileHolder.java b/src/main/java/com/genius/gitget/global/file/domain/FileHolder.java new file mode 100644 index 00000000..3618a67f --- /dev/null +++ b/src/main/java/com/genius/gitget/global/file/domain/FileHolder.java @@ -0,0 +1,9 @@ +package com.genius.gitget.global.file.domain; + +import java.util.Optional; + +public interface FileHolder { + Optional getFiles(); + + void setFiles(Files files); +} diff --git a/src/main/java/com/genius/gitget/global/file/domain/Files.java b/src/main/java/com/genius/gitget/global/file/domain/Files.java index f9e65331..b988603b 100644 --- a/src/main/java/com/genius/gitget/global/file/domain/Files.java +++ b/src/main/java/com/genius/gitget/global/file/domain/Files.java @@ -1,5 +1,6 @@ package com.genius.gitget.global.file.domain; +import com.genius.gitget.global.file.dto.FileDTO; import com.genius.gitget.global.file.dto.UpdateDTO; import com.genius.gitget.global.util.domain.BaseTimeEntity; import jakarta.persistence.Column; @@ -40,6 +41,15 @@ public Files(FileType fileType, String originalFilename, String savedFilename, S this.fileURI = fileURI; } + public static Files create(FileDTO fileDTO) { + return Files.builder() + .originalFilename(fileDTO.originalFilename()) + .savedFilename(fileDTO.savedFilename()) + .fileType(fileDTO.fileType()) + .fileURI(fileDTO.fileURI()) + .build(); + } + //== 비지니스 로직 ==// public void updateFiles(UpdateDTO updateDTO) { this.originalFilename = updateDTO.originalFilename(); diff --git a/src/main/java/com/genius/gitget/global/file/dto/FileDTO.java b/src/main/java/com/genius/gitget/global/file/dto/FileDTO.java new file mode 100644 index 00000000..c73d4f6c --- /dev/null +++ b/src/main/java/com/genius/gitget/global/file/dto/FileDTO.java @@ -0,0 +1,23 @@ +package com.genius.gitget.global.file.dto; + +import com.genius.gitget.global.file.domain.FileType; +import lombok.Builder; + +/** + * FileDTO는 Files 객체 생성에 필요한 값들을 담어서 전달하는 역할을 합니다. + * + * @param fileType 저장하고자하는 이미지의 타입 + * (TOPIC, INSTANCE, PROFILE 중 택1) + * @param originalFilename 사용자로부터 받은 이미지의 이름 + * (ex: sky.jpeg) + * @param savedFilename 각 이미지를 식별하기 위해 UUID를 부여하여 만든 이미지의 이름 + * (ex:10ab2c6f-77d7-435e-96f0-e75b67213528.jpeg) + * @param fileURI 이미지가 저장되는 경로 + * (ex: /Users/seonghuiyeon/GitGet/images/topic/10ab2c6f-77d7-435e-96f0-e75b67213528.jpeg) + */ +@Builder +public record FileDTO(FileType fileType, + String originalFilename, + String savedFilename, + String fileURI) { +} diff --git a/src/main/java/com/genius/gitget/global/file/dto/FileResponse.java b/src/main/java/com/genius/gitget/global/file/dto/FileResponse.java index 650dbc41..ec485146 100644 --- a/src/main/java/com/genius/gitget/global/file/dto/FileResponse.java +++ b/src/main/java/com/genius/gitget/global/file/dto/FileResponse.java @@ -1,22 +1,11 @@ package com.genius.gitget.global.file.dto; -import com.genius.gitget.global.file.domain.Files; -import com.genius.gitget.global.file.service.FileUtil; -import java.util.Optional; - public record FileResponse( Long fileId, String encodedFile) { - public static FileResponse create(Optional optionalFiles) { - if (optionalFiles.isEmpty()) { - return FileResponse.createNotExistFile(); - } - return FileResponse.createExistFile(optionalFiles.get()); - } - - public static FileResponse createExistFile(Files files) { - return new FileResponse(files.getId(), FileUtil.encodedImage(files)); + public static FileResponse createExistFile(Long filesId, String encodedFile) { + return new FileResponse(filesId, encodedFile); } public static FileResponse createNotExistFile() { diff --git a/src/main/java/com/genius/gitget/global/file/dto/UpdateDTO.java b/src/main/java/com/genius/gitget/global/file/dto/UpdateDTO.java index 99ad7c40..adbbe011 100644 --- a/src/main/java/com/genius/gitget/global/file/dto/UpdateDTO.java +++ b/src/main/java/com/genius/gitget/global/file/dto/UpdateDTO.java @@ -2,10 +2,28 @@ import lombok.Builder; +/** + * UpdateDTO는 Files 객체의 갱신에 필요한 값들을 담는 객체입니다. + * + * @param originalFilename 사용자로부터 받은 이미지의 이름 + * (ex: sky.jpeg) + * @param savedFilename 각 이미지를 식별하기 위해 UUID를 부여하여 만든 이미지의 이름 + * (ex:10ab2c6f-77d7-435e-96f0-e75b67213528.jpeg) + * @param fileURI 이미지가 저장되는 경로 + * (ex: /Users/seonghuiyeon/GitGet/images/topic/10ab2c6f-77d7-435e-96f0-e75b67213528.jpeg) + */ @Builder public record UpdateDTO( String originalFilename, String savedFilename, String fileURI ) { + + public static UpdateDTO of(FileDTO fileDTO) { + return UpdateDTO.builder() + .originalFilename(fileDTO.originalFilename()) + .savedFilename(fileDTO.savedFilename()) + .fileURI(fileDTO.fileURI()) + .build(); + } } diff --git a/src/main/java/com/genius/gitget/global/file/dto/UploadDTO.java b/src/main/java/com/genius/gitget/global/file/dto/UploadDTO.java deleted file mode 100644 index e2890f6b..00000000 --- a/src/main/java/com/genius/gitget/global/file/dto/UploadDTO.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.genius.gitget.global.file.dto; - -import com.genius.gitget.global.file.domain.FileType; -import lombok.Builder; - -@Builder -public record UploadDTO(FileType fileType, - String originalFilename, - String savedFilename, - String fileURI) { -} diff --git a/src/main/java/com/genius/gitget/global/file/service/FileHolderFinder.java b/src/main/java/com/genius/gitget/global/file/service/FileHolderFinder.java new file mode 100644 index 00000000..5055e753 --- /dev/null +++ b/src/main/java/com/genius/gitget/global/file/service/FileHolderFinder.java @@ -0,0 +1,42 @@ +package com.genius.gitget.global.file.service; + +import static com.genius.gitget.global.util.exception.ErrorCode.INSTANCE_NOT_FOUND; +import static com.genius.gitget.global.util.exception.ErrorCode.MEMBER_NOT_FOUND; +import static com.genius.gitget.global.util.exception.ErrorCode.TOPIC_NOT_FOUND; + +import com.genius.gitget.admin.topic.repository.TopicRepository; +import com.genius.gitget.challenge.instance.repository.InstanceRepository; +import com.genius.gitget.challenge.user.repository.UserRepository; +import com.genius.gitget.global.file.domain.FileHolder; +import com.genius.gitget.global.file.domain.FileType; +import com.genius.gitget.global.util.exception.BusinessException; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional(readOnly = true) +@RequiredArgsConstructor +public class FileHolderFinder { + private final UserRepository userRepository; + private final TopicRepository topicRepository; + private final InstanceRepository instanceRepository; + + public FileHolder findByInfo(Long id, FileType fileType) { + switch (fileType) { + case TOPIC -> { + return topicRepository.findById(id) + .orElseThrow(() -> new BusinessException(TOPIC_NOT_FOUND)); + } + case INSTANCE -> { + return instanceRepository.findById(id) + .orElseThrow(() -> new BusinessException(INSTANCE_NOT_FOUND)); + } + case PROFILE -> { + return userRepository.findById(id) + .orElseThrow(() -> new BusinessException(MEMBER_NOT_FOUND)); + } + } + throw new BusinessException(); + } +} diff --git a/src/main/java/com/genius/gitget/global/file/service/FileManager.java b/src/main/java/com/genius/gitget/global/file/service/FileManager.java new file mode 100644 index 00000000..1fb41eeb --- /dev/null +++ b/src/main/java/com/genius/gitget/global/file/service/FileManager.java @@ -0,0 +1,58 @@ +package com.genius.gitget.global.file.service; + +import com.genius.gitget.global.file.domain.FileType; +import com.genius.gitget.global.file.domain.Files; +import com.genius.gitget.global.file.dto.FileDTO; +import com.genius.gitget.global.file.dto.UpdateDTO; +import com.genius.gitget.global.util.exception.BusinessException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +@Service +@Transactional(readOnly = true) +public interface FileManager { + + /** + * Files 내에 저장된 값들을 통해 UrlResource 등으로 다운받은 후, base64로 인코딩한 결과 반환 + * + * @param files 얻기 원하는 파일의 정보를 담고 있는 Files 객체 + * @return base64로 encode한 결과 값(문자열) + */ + String getEncodedImage(Files files); + + /** + * 전달한 파일 저장 후, Files 객체 형성에 필요한 정보를 담은 객체 반환 + * + * @param multipartFile 저장하고자 전달한 파일 + * @param fileType 저장하고자하는 파일의 종류 (Topic, Instance, Profile 중 1) + * @return Files 객체 생성에 필요한 정보(UploadDTO) 반환 + */ + FileDTO upload(MultipartFile multipartFile, FileType fileType); + + /** + * 기존에 저장소에 저장되어 있던 파일을 특정 타입에 복사 후, Files 객체 생성에 필요한 정보들을 반환 + * + * @param files 복사하고자하는 파일의 정보를 담고 있는 Files 객체 + * @param fileType 복사해서 적용하고 싶은 대상의 파일 타입(TOPIC/INSTANCE/PROFILE 중 택 1) + * @return Files 객체 생성에 필요한 정보(UploadDTO) 반환 + */ + FileDTO copy(Files files, FileType fileType); + + /** + * Files에 해당하는 이미지를 찾아서 삭제 및 새로운 이미지 저장 후, Files 내용 갱신에 필요한 정보들을 반환 + * + * @param files 대체 하고자하는 대상 객체 + * @param multipartFile 저장하고자하는 파일 + * @return Files 내용 갱신에 필요한 정보(UpdateDTO) 반환 + */ + UpdateDTO update(Files files, MultipartFile multipartFile); + + /** + * Files 객체 내의 정보를 활용하여 저장소(Local/S3)에서 해당 파일 삭제. + * + * @param files 삭제하고자하는 Files 객체 + * @throws BusinessException 삭제에 실패했을 때 발생 + */ + void deleteInStorage(Files files); +} diff --git a/src/main/java/com/genius/gitget/global/file/service/FileUtil.java b/src/main/java/com/genius/gitget/global/file/service/FileUtil.java index 6d16ad2d..d6a3309d 100644 --- a/src/main/java/com/genius/gitget/global/file/service/FileUtil.java +++ b/src/main/java/com/genius/gitget/global/file/service/FileUtil.java @@ -1,33 +1,31 @@ package com.genius.gitget.global.file.service; -import static com.genius.gitget.global.util.exception.ErrorCode.FILE_NOT_COPIED; import static com.genius.gitget.global.util.exception.ErrorCode.FILE_NOT_EXIST; -import static com.genius.gitget.global.util.exception.ErrorCode.FILE_NOT_SAVED; import static com.genius.gitget.global.util.exception.ErrorCode.IMAGE_NOT_ENCODED; import static com.genius.gitget.global.util.exception.ErrorCode.NOT_SUPPORTED_EXTENSION; import com.genius.gitget.global.file.domain.FileType; import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.file.dto.CopyDTO; -import com.genius.gitget.global.file.dto.UpdateDTO; -import com.genius.gitget.global.file.dto.UploadDTO; +import com.genius.gitget.global.file.dto.FileDTO; import com.genius.gitget.global.util.exception.BusinessException; -import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.nio.file.StandardCopyOption; import java.util.Base64; import java.util.List; import java.util.Objects; import java.util.UUID; import org.springframework.core.io.UrlResource; +import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; +@Component public class FileUtil { - private static final List validExtensions = List.of("jpg", "jpeg", "png", "gif"); + private final List validExtensions = List.of("jpg", "jpeg", "png", "gif"); public static String encodedImage(Files files) { try { + //TODO: local 환경에 종속된 메서드이므로 종속되지 않게 수정 필요 UrlResource urlResource = new UrlResource("file:" + files.getFileURI()); byte[] encode = Base64.getEncoder().encode(urlResource.getContentAsByteArray()); @@ -37,12 +35,11 @@ public static String encodedImage(Files files) { } } - public static UploadDTO getUploadInfo(MultipartFile file, String typeStr, final String UPLOAD_PATH) { + public FileDTO getFileDTO(MultipartFile file, FileType fileType, final String UPLOAD_PATH) { String originalFilename = file.getOriginalFilename(); String savedFilename = getSavedFilename(originalFilename); - FileType fileType = FileType.findType(typeStr); - return UploadDTO.builder() + return FileDTO.builder() .fileType(fileType) .originalFilename(originalFilename) .savedFilename(savedFilename) @@ -50,28 +47,7 @@ public static UploadDTO getUploadInfo(MultipartFile file, String typeStr, final .build(); } - public static UpdateDTO getUpdateInfo(MultipartFile file, FileType fileType, final String UPLOAD_PATH) { - String originalFilename = file.getOriginalFilename(); - String savedFilename = getSavedFilename(originalFilename); - - return UpdateDTO.builder() - .originalFilename(originalFilename) - .savedFilename(savedFilename) - .fileURI(UPLOAD_PATH + fileType.getPath() + savedFilename) - .build(); - } - - public static void saveFile(MultipartFile file, String fileURI) { - try { - File targetFile = new File(fileURI); - createPath(fileURI); - file.transferTo(targetFile); - } catch (IOException e) { - throw new BusinessException(FILE_NOT_SAVED); - } - } - - public static CopyDTO getCopyInfo(Files files, FileType fileType, final String UPLOAD_PATH) { + public CopyDTO getCopyInfo(Files files, FileType fileType, final String UPLOAD_PATH) { String originalFilename = files.getOriginalFilename(); String savedFilename = getSavedFilename(originalFilename); @@ -84,20 +60,7 @@ public static CopyDTO getCopyInfo(Files files, FileType fileType, final String U .build(); } - public static void copyImage(String originFilePath, CopyDTO copyDTO) { - File originFile = new File(originFilePath); - File copyFile = new File(copyDTO.fileURI()); - - try { - createPath(copyDTO.folderURI()); - java.nio.file.Files.copy(originFile.toPath(), copyFile.toPath(), - StandardCopyOption.COPY_ATTRIBUTES); - } catch (IOException e) { - throw new BusinessException(FILE_NOT_COPIED); - } - } - - public static void validateFile(MultipartFile file) { + public void validateFile(MultipartFile file) { String originalFilename = file.getOriginalFilename(); if (originalFilename == null || Objects.equals(originalFilename, "")) { @@ -111,22 +74,15 @@ public static void validateFile(MultipartFile file) { } } - public static String getSavedFilename(String originalFilename) { + public String getSavedFilename(String originalFilename) { String uuid = UUID.randomUUID().toString(); String extension = extractExtension(originalFilename); return uuid + "." + extension; } - private static String extractExtension(String filename) { + private String extractExtension(String filename) { int index = filename.lastIndexOf("."); return filename.substring(index + 1).toLowerCase(); } - - private static void createPath(String uri) { - File file = new File(uri); - if (!file.exists()) { - file.mkdirs(); - } - } } diff --git a/src/main/java/com/genius/gitget/global/file/service/FilesService.java b/src/main/java/com/genius/gitget/global/file/service/FilesService.java index 5e08c123..42e8a4c5 100644 --- a/src/main/java/com/genius/gitget/global/file/service/FilesService.java +++ b/src/main/java/com/genius/gitget/global/file/service/FilesService.java @@ -1,20 +1,20 @@ package com.genius.gitget.global.file.service; -import static com.genius.gitget.global.file.domain.FileType.INSTANCE; -import static com.genius.gitget.global.util.exception.ErrorCode.FILE_NOT_DELETED; import static com.genius.gitget.global.util.exception.ErrorCode.FILE_NOT_EXIST; +import static com.genius.gitget.global.util.exception.ErrorCode.MULTIPART_FILE_NOT_EXIST; +import com.genius.gitget.challenge.instance.domain.Instance; +import com.genius.gitget.global.file.domain.FileHolder; +import com.genius.gitget.global.file.domain.FileType; import com.genius.gitget.global.file.domain.Files; -import com.genius.gitget.global.file.dto.CopyDTO; +import com.genius.gitget.global.file.dto.FileDTO; import com.genius.gitget.global.file.dto.FileResponse; import com.genius.gitget.global.file.dto.UpdateDTO; -import com.genius.gitget.global.file.dto.UploadDTO; import com.genius.gitget.global.file.repository.FilesRepository; import com.genius.gitget.global.util.exception.BusinessException; -import java.io.File; import java.util.Optional; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; @@ -22,65 +22,84 @@ @Slf4j @Service @Transactional(readOnly = true) +@RequiredArgsConstructor public class FilesService { - private final String UPLOAD_PATH; + private final FileManager fileManager; private final FilesRepository filesRepository; - public FilesService(@Value("${file.upload.path}") String UPLOAD_PATH, FilesRepository filesRepository) { - this.UPLOAD_PATH = UPLOAD_PATH; - this.filesRepository = filesRepository; + + @Transactional + public Files uploadFile(MultipartFile multipartFile, FileType fileType) { + FileDTO fileDTO = fileManager.upload(multipartFile, fileType); + + Files file = Files.builder() + .originalFilename(fileDTO.originalFilename()) + .savedFilename(fileDTO.savedFilename()) + .fileType(fileDTO.fileType()) + .fileURI(fileDTO.fileURI()) + .build(); + return filesRepository.save(file); } @Transactional - public Files uploadFile(Optional optionalFiles, MultipartFile receivedFile, String typeStr) { - if (receivedFile != null) { - return uploadFile(receivedFile, typeStr); + public Files uploadFile(FileHolder fileHolder, MultipartFile multipartFile, FileType fileType) { + if (multipartFile == null) { + throw new BusinessException(MULTIPART_FILE_NOT_EXIST); } + FileDTO fileDTO = fileManager.upload(multipartFile, fileType); - Files files = optionalFiles.orElseThrow(() -> new BusinessException(FILE_NOT_EXIST)); - CopyDTO copyDTO = FileUtil.getCopyInfo(files, INSTANCE, UPLOAD_PATH); - //REFACTOR: 정적 팩토리 메서드로 처리하면 깔끔할 듯! - Files copyFiles = Files.builder() - .originalFilename(copyDTO.originalFilename()) - .savedFilename(copyDTO.savedFilename()) - .fileType(copyDTO.fileType()) - .fileURI(copyDTO.fileURI()) + Files file = Files.builder() + .originalFilename(fileDTO.originalFilename()) + .savedFilename(fileDTO.savedFilename()) + .fileType(fileDTO.fileType()) + .fileURI(fileDTO.fileURI()) .build(); + fileHolder.setFiles(file); + return filesRepository.save(file); + } - FileUtil.copyImage(files.getFileURI(), copyDTO); + @Transactional + public Files copyTopicToInstance(FileHolder fileHolder) { + Instance instance = (Instance) fileHolder; + Files topicFiles = instance.getTopic().getFiles() + .orElseThrow(() -> new BusinessException(FILE_NOT_EXIST)); - return filesRepository.save(copyFiles); + Files instanceFiles = copyFile(topicFiles, FileType.INSTANCE); + instance.setFiles(instanceFiles); + + return instanceFiles; } @Transactional - public Files uploadFile(MultipartFile receivedFile, String typeStr) { - FileUtil.validateFile(receivedFile); - UploadDTO uploadDTO = FileUtil.getUploadInfo(receivedFile, typeStr, UPLOAD_PATH); - FileUtil.saveFile(receivedFile, uploadDTO.fileURI()); - - Files file = Files.builder() - .originalFilename(uploadDTO.originalFilename()) - .savedFilename(uploadDTO.savedFilename()) - .fileType(uploadDTO.fileType()) - .fileURI(uploadDTO.fileURI()) - .build(); + public Files copyFile(Files files, FileType fileType) { + FileDTO fileDTO = fileManager.copy(files, fileType); - return filesRepository.save(file); + Files copyFiles = Files.create(fileDTO); + return filesRepository.save(copyFiles); } @Transactional - public Files updateFile(Long fileId, MultipartFile file) { + public Files updateFile(Long fileId, MultipartFile multipartFile) { Files files = filesRepository.findById(fileId) .orElseThrow(() -> new BusinessException(FILE_NOT_EXIST)); - if (file == null) { + if (multipartFile == null) { return files; } - deleteFilesInStorage(files); + UpdateDTO updateDTO = fileManager.update(files, multipartFile); + files.updateFiles(updateDTO); + return files; + } - UpdateDTO updateDTO = FileUtil.getUpdateInfo(file, files.getFileType(), UPLOAD_PATH); - FileUtil.saveFile(file, updateDTO.fileURI()); + @Transactional + public Files updateFile(Optional optionalFiles, MultipartFile multipartFile) { + Files files = optionalFiles.orElseThrow(() -> new BusinessException(FILE_NOT_EXIST)); + if (multipartFile == null) { + return files; + } + + UpdateDTO updateDTO = fileManager.update(files, multipartFile); files.updateFiles(updateDTO); return files; } @@ -95,29 +114,32 @@ public void deleteFile(Long fileId) { Files files = filesRepository.findById(fileId) .orElseThrow(() -> new BusinessException(FILE_NOT_EXIST)); - deleteFilesInStorage(files); + fileManager.deleteInStorage(files); filesRepository.delete(files); } - private void deleteFilesInStorage(Files files) { - String fileURI = files.getFileURI(); - File targetFile = new File(fileURI); - if (!targetFile.delete()) { - throw new BusinessException(FILE_NOT_DELETED); + @Transactional + public void deleteFile(Optional optionalFiles) { + if (optionalFiles.isEmpty()) { + return; } - } + Files files = optionalFiles.get(); - public FileResponse getEncodedFile(Long fileId) { - Optional optionalFiles = filesRepository.findById(fileId); - return optionalFiles - .map(FileResponse::createExistFile) - .orElseGet(FileResponse::createNotExistFile); + fileManager.deleteInStorage(files); + filesRepository.delete(files); + } + public Files findById(Long fileId) { + return filesRepository.findById(fileId) + .orElseThrow(() -> new BusinessException(FILE_NOT_EXIST)); } - public FileResponse getEncodedFile(Optional optionalFiles) { + public FileResponse convertToFileResponse(Optional optionalFiles) { return optionalFiles - .map(FileResponse::createExistFile) + .map(files -> { + String encodedImage = fileManager.getEncodedImage(files); + return FileResponse.createExistFile(files.getId(), encodedImage); + }) .orElseGet(FileResponse::createNotExistFile); } } diff --git a/src/main/java/com/genius/gitget/global/file/service/LocalFileManager.java b/src/main/java/com/genius/gitget/global/file/service/LocalFileManager.java new file mode 100644 index 00000000..5a5fabec --- /dev/null +++ b/src/main/java/com/genius/gitget/global/file/service/LocalFileManager.java @@ -0,0 +1,104 @@ +package com.genius.gitget.global.file.service; + +import static com.genius.gitget.global.util.exception.ErrorCode.FILE_NOT_COPIED; +import static com.genius.gitget.global.util.exception.ErrorCode.FILE_NOT_DELETED; +import static com.genius.gitget.global.util.exception.ErrorCode.FILE_NOT_SAVED; + +import com.genius.gitget.global.file.domain.FileType; +import com.genius.gitget.global.file.domain.Files; +import com.genius.gitget.global.file.dto.CopyDTO; +import com.genius.gitget.global.file.dto.FileDTO; +import com.genius.gitget.global.file.dto.UpdateDTO; +import com.genius.gitget.global.util.exception.BusinessException; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.StandardCopyOption; +import java.util.Base64; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.UrlResource; +import org.springframework.web.multipart.MultipartFile; + +public class LocalFileManager implements FileManager { + private final String UPLOAD_PATH; + private final FileUtil fileUtil; + + + public LocalFileManager(FileUtil fileUtil, @Value("${file.upload.path}") String UPLOAD_PATH) { + this.fileUtil = fileUtil; + this.UPLOAD_PATH = UPLOAD_PATH; + } + + @Override + public FileDTO upload(MultipartFile multipartFile, FileType fileType) { + fileUtil.validateFile(multipartFile); + FileDTO fileDTO = fileUtil.getFileDTO(multipartFile, fileType, UPLOAD_PATH); + + try { + File file = new File(fileDTO.fileURI()); + createPath(fileDTO.fileURI()); + multipartFile.transferTo(file); + } catch (IOException e) { + throw new BusinessException(FILE_NOT_SAVED); + } + + return fileDTO; + } + + @Override + public String getEncodedImage(Files files) { + try { + UrlResource urlResource = new UrlResource("file:" + files.getFileURI()); + byte[] encode = Base64.getEncoder().encode(urlResource.getContentAsByteArray()); + return new String(encode, StandardCharsets.UTF_8); + } catch (IOException e) { + throw new BusinessException(e); + } + } + + @Override + public FileDTO copy(Files files, FileType fileType) { + CopyDTO copyDTO = fileUtil.getCopyInfo(files, fileType, UPLOAD_PATH); + createPath(copyDTO.folderURI()); + + File originFile = new File(files.getFileURI()); + File copyFile = new File(copyDTO.fileURI()); + + try { + java.nio.file.Files.copy(originFile.toPath(), copyFile.toPath(), + StandardCopyOption.COPY_ATTRIBUTES); + } catch (IOException e) { + throw new BusinessException(FILE_NOT_COPIED); + } + return FileDTO.builder() + .fileType(fileType) + .originalFilename(copyDTO.originalFilename()) + .savedFilename(copyDTO.savedFilename()) + .fileURI(copyDTO.fileURI()) + .build(); + } + + @Override + public UpdateDTO update(Files files, MultipartFile multipartFile) { + deleteInStorage(files); + FileDTO fileDTO = upload(multipartFile, files.getFileType()); + + return UpdateDTO.of(fileDTO); + } + + @Override + public void deleteInStorage(Files files) { + String fileURI = files.getFileURI(); + File targetFile = new File(fileURI); + if (!targetFile.delete()) { + throw new BusinessException(FILE_NOT_DELETED); + } + } + + private void createPath(String uri) { + File file = new File(uri); + if (!file.exists()) { + file.mkdirs(); + } + } +} diff --git a/src/main/java/com/genius/gitget/global/file/service/S3FileManager.java b/src/main/java/com/genius/gitget/global/file/service/S3FileManager.java new file mode 100644 index 00000000..15c28f09 --- /dev/null +++ b/src/main/java/com/genius/gitget/global/file/service/S3FileManager.java @@ -0,0 +1,46 @@ +package com.genius.gitget.global.file.service; + +import com.genius.gitget.global.file.domain.FileType; +import com.genius.gitget.global.file.domain.Files; +import com.genius.gitget.global.file.dto.FileDTO; +import com.genius.gitget.global.file.dto.UpdateDTO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.multipart.MultipartFile; + +/** + * !!!이 클래스의 모든 주석은 삭제해도 무방합니다!!! + *

+ * S3 bucket에 이미지를 업로드하는 코드를 구현하는 곳 + * 파일 시스템 구조 확장에 참고한 링크 + * https://chb2005.tistory.com/200#3.5.%20%ED%8C%8C%EC%9D%BC%20%EB%8B%A4%EC%9A%B4%EB%A1%9C%EB%93%9C%20%EA%B5%AC%ED%98%84 + * https://docs.aws.amazon.com/ko_kr/sdk-for-java/v1/developer-guide/examples-s3-objects.html#upload-object + */ +@RequiredArgsConstructor +public class S3FileManager implements FileManager { + private final FileUtil fileUtil; + + + @Override + public String getEncodedImage(Files files) { + return null; + } + + @Override + public FileDTO upload(MultipartFile multipartFile, FileType fileType) { + return null; + } + + @Override + public FileDTO copy(Files files, FileType fileType) { + return null; + } + + @Override + public UpdateDTO update(Files files, MultipartFile multipartFile) { + return null; + } + + @Override + public void deleteInStorage(Files files) { + } +} diff --git a/src/main/java/com/genius/gitget/global/security/dto/SignupResponse.java b/src/main/java/com/genius/gitget/global/security/dto/SignupResponse.java index 82439227..a420e497 100644 --- a/src/main/java/com/genius/gitget/global/security/dto/SignupResponse.java +++ b/src/main/java/com/genius/gitget/global/security/dto/SignupResponse.java @@ -1,6 +1,7 @@ package com.genius.gitget.global.security.dto; public record SignupResponse( + Long userId, String identifier ) { } diff --git a/src/main/java/com/genius/gitget/global/util/config/AppConfig.java b/src/main/java/com/genius/gitget/global/util/config/AppConfig.java index 5958b7a0..b3169b6f 100644 --- a/src/main/java/com/genius/gitget/global/util/config/AppConfig.java +++ b/src/main/java/com/genius/gitget/global/util/config/AppConfig.java @@ -1,20 +1,41 @@ package com.genius.gitget.global.util.config; +import com.genius.gitget.global.file.service.FileManager; +import com.genius.gitget.global.file.service.FileUtil; +import com.genius.gitget.global.file.service.LocalFileManager; +import com.genius.gitget.global.file.service.S3FileManager; import com.genius.gitget.global.util.formatter.LocalDateFormatter; import com.genius.gitget.global.util.formatter.LocalDateTimeFormatter; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.security.crypto.encrypt.AesBytesEncryptor; +@Slf4j @Configuration -@PropertySource("classpath:application-common.yml") @RequiredArgsConstructor public class AppConfig { private final Environment env; + @Bean + public FileUtil fileUtil() { + return new FileUtil(); + } + + @Bean + public FileManager fileManager() { + final String fileMode = env.getProperty("file.mode"); + final String UPLOAD_PATH = env.getProperty("file.upload.path"); + assert fileMode != null; + + if (fileMode.equals("local")) { + return new LocalFileManager(fileUtil(), UPLOAD_PATH); + } + return new S3FileManager(fileUtil()); + } + @Bean public AesBytesEncryptor aesBytesEncryptor() { return new AesBytesEncryptor( diff --git a/src/main/java/com/genius/gitget/challenge/config/WebConfig.java b/src/main/java/com/genius/gitget/global/util/config/WebConfig.java similarity index 90% rename from src/main/java/com/genius/gitget/challenge/config/WebConfig.java rename to src/main/java/com/genius/gitget/global/util/config/WebConfig.java index 153a8eb4..3d0de4b4 100644 --- a/src/main/java/com/genius/gitget/challenge/config/WebConfig.java +++ b/src/main/java/com/genius/gitget/global/util/config/WebConfig.java @@ -1,4 +1,4 @@ -package com.genius.gitget.challenge.config; +package com.genius.gitget.global.util.config; import com.genius.gitget.challenge.instance.service.StringToEnum; import org.springframework.context.annotation.Configuration; diff --git a/src/main/java/com/genius/gitget/global/util/exception/ErrorCode.java b/src/main/java/com/genius/gitget/global/util/exception/ErrorCode.java index 1cf5a37c..d34110cd 100644 --- a/src/main/java/com/genius/gitget/global/util/exception/ErrorCode.java +++ b/src/main/java/com/genius/gitget/global/util/exception/ErrorCode.java @@ -43,6 +43,7 @@ public enum ErrorCode { JWT_TOKEN_NOT_FOUND(HttpStatus.NOT_FOUND, "Cookie에 토큰이 존재하지 않습니다."), + MULTIPART_FILE_NOT_EXIST(HttpStatus.BAD_REQUEST, "MultipartFile이 전달되지 않았습니다."), FILE_NOT_EXIST(HttpStatus.BAD_REQUEST, "해당 파일(이미지)이 존재하지 않습니다."), NOT_SUPPORTED_EXTENSION(HttpStatus.BAD_REQUEST, "지원하지 않는 확장자입니다."), NOT_SUPPORTED_IMAGE_TYPE(HttpStatus.BAD_REQUEST, "지원하지 않는 이미지 타입입니다."), diff --git a/src/main/java/com/genius/gitget/profile/controller/ProfileController.java b/src/main/java/com/genius/gitget/profile/controller/ProfileController.java index 90178329..3b6ff110 100644 --- a/src/main/java/com/genius/gitget/profile/controller/ProfileController.java +++ b/src/main/java/com/genius/gitget/profile/controller/ProfileController.java @@ -1,11 +1,13 @@ package com.genius.gitget.profile.controller; +import static com.genius.gitget.global.util.exception.SuccessCode.SUCCESS; + import com.genius.gitget.global.security.domain.UserPrincipal; -import com.genius.gitget.global.util.exception.SuccessCode; import com.genius.gitget.global.util.response.dto.CommonResponse; import com.genius.gitget.global.util.response.dto.SingleResponse; import com.genius.gitget.profile.dto.UserChallengeResultResponse; import com.genius.gitget.profile.dto.UserDetailsInformationResponse; +import com.genius.gitget.profile.dto.UserIndexResponse; import com.genius.gitget.profile.dto.UserInformationRequest; import com.genius.gitget.profile.dto.UserInformationResponse; import com.genius.gitget.profile.dto.UserInformationUpdateRequest; @@ -22,9 +24,7 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; @RestController @RequiredArgsConstructor @@ -39,7 +39,7 @@ public ResponseEntity> getUserDet UserDetailsInformationResponse userInformation = profileService.getUserDetailsInformation( userPrincipal.getUser()); return ResponseEntity.ok() - .body(new SingleResponse<>(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage(), + .body(new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), userInformation) ); } @@ -50,22 +50,23 @@ public ResponseEntity> getUserInformatio @RequestBody UserInformationRequest userInformationRequest) { UserInformationResponse userInformation = profileService.getUserInformation(userInformationRequest.getUserId()); return ResponseEntity.ok() - .body(new SingleResponse<>(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage(), + .body(new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), userInformation) ); } // 마이페이지 - 회원 정보 수정 @PostMapping("/information") - public ResponseEntity updateUserInformation(@AuthenticationPrincipal UserPrincipal userPrincipal, - @RequestPart(value = "data") UserInformationUpdateRequest userInformationUpdateRequest, - @RequestPart(value = "files", required = false) MultipartFile multipartFile, - @RequestPart(value = "type") String type) { - profileService.updateUserInformation(userPrincipal.getUser(), userInformationUpdateRequest, multipartFile, - type); + public ResponseEntity> updateUserInformation( + @AuthenticationPrincipal UserPrincipal userPrincipal, + @RequestBody UserInformationUpdateRequest userInformationUpdateRequest) { - return ResponseEntity.ok() - .body(new CommonResponse(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage())); + Long userId = profileService.updateUserInformation(userPrincipal.getUser(), userInformationUpdateRequest); + UserIndexResponse userIndexResponse = new UserIndexResponse(userId); + + return ResponseEntity.ok().body( + new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), userIndexResponse) + ); } // 마이페이지 - 관심사 조회 @@ -75,7 +76,7 @@ public ResponseEntity> getUserInterest( UserInterestResponse userInterest = profileService.getUserInterest(userPrincipal.getUser()); return ResponseEntity.ok() - .body(new SingleResponse<>(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage(), + .body(new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), userInterest)); } @@ -87,7 +88,7 @@ public ResponseEntity updateUserTags(@AuthenticationPrincipal Us profileService.updateUserTags(userPrincipal.getUser(), userInterestUpdateRequest); return ResponseEntity.ok() - .body(new CommonResponse(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage())); + .body(new CommonResponse(SUCCESS.getStatus(), SUCCESS.getMessage())); } @@ -98,7 +99,7 @@ public ResponseEntity> getUserChalle UserChallengeResultResponse userChallengeResult = profileService.getUserChallengeResult( userPrincipal.getUser()); return ResponseEntity.ok() - .body(new SingleResponse<>(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage(), + .body(new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), userChallengeResult)); } @@ -110,7 +111,7 @@ public ResponseEntity deleteUserInformation(@AuthenticationPrinc profileService.deleteUserInformation(userPrincipal.getUser(), userSignoutRequest.getReason()); return ResponseEntity.ok() - .body(new CommonResponse(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage())); + .body(new CommonResponse(SUCCESS.getStatus(), SUCCESS.getMessage())); } @@ -121,7 +122,7 @@ public ResponseEntity> getUserPoint( UserPointResponse userPoint = profileService.getUserPoint(userPrincipal.getUser()); return ResponseEntity.ok() - .body(new SingleResponse<>(SuccessCode.SUCCESS.getStatus(), SuccessCode.SUCCESS.getMessage(), + .body(new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), userPoint)); } } diff --git a/src/main/java/com/genius/gitget/profile/dto/UserDetailsInformationResponse.java b/src/main/java/com/genius/gitget/profile/dto/UserDetailsInformationResponse.java index f3a71885..234f30e9 100644 --- a/src/main/java/com/genius/gitget/profile/dto/UserDetailsInformationResponse.java +++ b/src/main/java/com/genius/gitget/profile/dto/UserDetailsInformationResponse.java @@ -1,14 +1,13 @@ package com.genius.gitget.profile.dto; import com.genius.gitget.challenge.user.domain.User; -import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.file.dto.FileResponse; -import java.util.Optional; import lombok.Builder; import lombok.Data; @Data public class UserDetailsInformationResponse { + private Long userId; private String identifier; private String nickname; private String information; @@ -17,32 +16,27 @@ public class UserDetailsInformationResponse { private FileResponse fileResponse; @Builder - public UserDetailsInformationResponse(String identifier, String nickname, String information, Long point, - Files files, - int progressBar) { + public UserDetailsInformationResponse(Long userId, String identifier, String nickname, String information, + Long point, int progressBar, FileResponse fileResponse) { + this.userId = userId; this.identifier = identifier; this.nickname = nickname; this.information = information; this.point = point; - this.fileResponse = convertToFileResponse(Optional.ofNullable(files)); + this.fileResponse = fileResponse; this.progressBar = progressBar; } - public static UserDetailsInformationResponse createByEntity(User findUser, Files files, int participantCount) { + public static UserDetailsInformationResponse createByEntity(User findUser, int participantCount, + FileResponse fileResponse) { return UserDetailsInformationResponse.builder() + .userId(findUser.getId()) .identifier(findUser.getIdentifier()) .nickname(findUser.getNickname()) .information(findUser.getInformation()) .point(findUser.getPoint()) - .files(files) .progressBar(participantCount) + .fileResponse(fileResponse) .build(); } - - private static FileResponse convertToFileResponse(Optional files) { - if (files.isEmpty()) { - return FileResponse.createNotExistFile(); - } - return FileResponse.createExistFile(files.get()); - } } diff --git a/src/main/java/com/genius/gitget/profile/dto/UserIndexResponse.java b/src/main/java/com/genius/gitget/profile/dto/UserIndexResponse.java new file mode 100644 index 00000000..b19399c8 --- /dev/null +++ b/src/main/java/com/genius/gitget/profile/dto/UserIndexResponse.java @@ -0,0 +1,6 @@ +package com.genius.gitget.profile.dto; + +public record UserIndexResponse( + Long userId +) { +} diff --git a/src/main/java/com/genius/gitget/profile/dto/UserInformationResponse.java b/src/main/java/com/genius/gitget/profile/dto/UserInformationResponse.java index e868594a..cc7234ef 100644 --- a/src/main/java/com/genius/gitget/profile/dto/UserInformationResponse.java +++ b/src/main/java/com/genius/gitget/profile/dto/UserInformationResponse.java @@ -1,40 +1,35 @@ package com.genius.gitget.profile.dto; import com.genius.gitget.challenge.user.domain.User; -import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.file.dto.FileResponse; -import java.util.Optional; import lombok.Builder; import lombok.Data; @Data public class UserInformationResponse { + private Long userId; private String identifier; private String nickname; private Long frameId; private FileResponse fileResponse; @Builder - public UserInformationResponse(String identifier, String nickname, Long frameId, Files files) { + public UserInformationResponse(Long userId, String identifier, String nickname, Long frameId, + FileResponse fileResponse) { + this.userId = userId; this.identifier = identifier; this.nickname = nickname; this.frameId = frameId; - this.fileResponse = convertToFileResponse(Optional.ofNullable(files)); + this.fileResponse = fileResponse; } - public static UserInformationResponse createByEntity(User findUser, Long frameId, Files files) { + public static UserInformationResponse createByEntity(User findUser, Long frameId, FileResponse fileResponse) { return UserInformationResponse.builder() + .userId(findUser.getId()) .identifier(findUser.getIdentifier()) .nickname(findUser.getNickname()) .frameId(frameId) - .files(files) + .fileResponse(fileResponse) .build(); } - - private static FileResponse convertToFileResponse(Optional files) { - if (files.isEmpty()) { - return FileResponse.createNotExistFile(); - } - return FileResponse.createExistFile(files.get()); - } } diff --git a/src/main/java/com/genius/gitget/profile/service/ProfileService.java b/src/main/java/com/genius/gitget/profile/service/ProfileService.java index b67c8eb1..3e446632 100644 --- a/src/main/java/com/genius/gitget/profile/service/ProfileService.java +++ b/src/main/java/com/genius/gitget/profile/service/ProfileService.java @@ -11,9 +11,7 @@ import com.genius.gitget.challenge.participant.domain.Participant; import com.genius.gitget.challenge.user.domain.User; import com.genius.gitget.challenge.user.repository.UserRepository; -import com.genius.gitget.global.file.domain.FileType; -import com.genius.gitget.global.file.domain.Files; -import com.genius.gitget.global.file.repository.FilesRepository; +import com.genius.gitget.global.file.dto.FileResponse; import com.genius.gitget.global.file.service.FilesService; import com.genius.gitget.global.util.exception.BusinessException; import com.genius.gitget.global.util.exception.ErrorCode; @@ -33,7 +31,6 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.multipart.MultipartFile; @Service @RequiredArgsConstructor @@ -41,15 +38,10 @@ @Transactional(readOnly = true) public class ProfileService { private final UserRepository userRepository; - private final FilesRepository filesRepository; private final FilesService filesService; private final SignoutRepository signoutRepository; private final OrdersProvider ordersProvider; - private static boolean isProfileFileType(Files files) { - return files != null && files.getFileType().equals(FileType.PROFILE); - } - // 포인트 조회 public UserPointResponse getUserPoint(User user) { return UserPointResponse.builder() @@ -62,12 +54,9 @@ public UserPointResponse getUserPoint(User user) { public UserInformationResponse getUserInformation(Long userId) { User findUser = getUserById(userId); Long frameId = ordersProvider.getUsingFrameItem(userId).getId(); - Files files = getFiles(findUser); - if (isProfileFileType(files)) { - return UserInformationResponse.createByEntity(findUser, frameId, files); - } else { - return UserInformationResponse.createByEntity(findUser, frameId, null); - } + + FileResponse fileResponse = filesService.convertToFileResponse(findUser.getFiles()); + return UserInformationResponse.createByEntity(findUser, frameId, fileResponse); } // 마이페이지 - 사용자 정보 상세 조회 @@ -82,39 +71,30 @@ public UserDetailsInformationResponse getUserDetailsInformation(User user) { participantCount = (joinResult == SUCCESS) ? participantCount + 1 : participantCount - 1; } } - Files files = getFiles(findUser); - if (isProfileFileType(files)) { - return UserDetailsInformationResponse.createByEntity(findUser, files, participantCount); - } else { - return UserDetailsInformationResponse.createByEntity(findUser, null, participantCount); - } + FileResponse fileResponse = filesService.convertToFileResponse(findUser.getFiles()); + return UserDetailsInformationResponse.createByEntity(findUser, participantCount, fileResponse); } // 마이페이지 - 사용자 정보 수정 @Transactional - public void updateUserInformation(User user, UserInformationUpdateRequest userInformationUpdateRequest, - MultipartFile multipartFile, String type) { + public Long updateUserInformation(User user, UserInformationUpdateRequest userInformationUpdateRequest) { User findUser = getUserByIdentifier(user.getIdentifier()); findUser.updateUserInformation( userInformationUpdateRequest.getNickname(), userInformationUpdateRequest.getInformation()); - if (multipartFile != null) { - if (findUser.getFiles().isEmpty()) { - Files uploadedFile = filesService.uploadFile(multipartFile, type); - findUser.setFiles(uploadedFile); - } else { - filesService.updateFile(findUser.getFiles().get().getId(), multipartFile); - } - } - userRepository.save(findUser); + User updatedUser = userRepository.save(findUser); + return updatedUser.getId(); } // 마이페이지 - 회원 탈퇴 @Transactional public void deleteUserInformation(User user, String reason) { User findUser = getUserByIdentifier(user.getIdentifier()); + + filesService.deleteFile(findUser.getFiles()); findUser.setFiles(null); + findUser.deleteLikesList(); userRepository.deleteById(findUser.getId()); signoutRepository.save( @@ -191,14 +171,6 @@ private User getUserByIdentifier(String identifier) { .orElseThrow(() -> new BusinessException(ErrorCode.MEMBER_NOT_FOUND)); } - private Files getFiles(User findUser) { - if (findUser.getFiles().isPresent()) { - return filesRepository.findById(findUser.getFiles().get().getId()).orElse(null); - } else { - return null; - } - } - private User getUserById(Long userId) { return userRepository.findById(userId) .orElseThrow(() -> new BusinessException(ErrorCode.MEMBER_NOT_FOUND)); diff --git a/src/test/java/com/genius/gitget/admin/topic/controller/TopicControllerTest.java b/src/test/java/com/genius/gitget/admin/topic/controller/TopicControllerTest.java index 02a3d7d9..a85d65fd 100644 --- a/src/test/java/com/genius/gitget/admin/topic/controller/TopicControllerTest.java +++ b/src/test/java/com/genius/gitget/admin/topic/controller/TopicControllerTest.java @@ -11,11 +11,9 @@ import com.genius.gitget.admin.topic.domain.Topic; import com.genius.gitget.admin.topic.repository.TopicRepository; import com.genius.gitget.challenge.user.domain.Role; -import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.file.service.FilesService; import com.genius.gitget.util.TokenTestUtil; import com.genius.gitget.util.WithMockCustomUser; -import com.genius.gitget.util.file.FileTestUtil; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -27,7 +25,6 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.multipart.MultipartFile; @SpringBootTest @Transactional @@ -116,9 +113,6 @@ public void setup() { private Topic getSavedTopic() { - MultipartFile filename = FileTestUtil.getMultipartFile("sky"); - Files files = filesService.uploadFile(filename, "topic"); - Topic topic = topicRepository.save( Topic.builder() .title("title") @@ -128,8 +122,6 @@ private Topic getSavedTopic() { .pointPerPerson(100) .build() ); - topic.setFiles(files); - return topic; } } diff --git a/src/test/java/com/genius/gitget/admin/topic/service/TopicServiceTest.java b/src/test/java/com/genius/gitget/admin/topic/service/TopicServiceTest.java index 6309f961..1ad86ab3 100644 --- a/src/test/java/com/genius/gitget/admin/topic/service/TopicServiceTest.java +++ b/src/test/java/com/genius/gitget/admin/topic/service/TopicServiceTest.java @@ -6,7 +6,6 @@ import com.genius.gitget.admin.topic.dto.TopicUpdateRequest; import com.genius.gitget.admin.topic.repository.TopicRepository; import com.genius.gitget.global.util.exception.BusinessException; -import com.genius.gitget.util.file.FileTestUtil; import jakarta.transaction.Transactional; import java.util.Optional; import org.assertj.core.api.Assertions; @@ -51,8 +50,7 @@ public void setup() { //given TopicCreateRequest topicCreateRequest = getTopicCreateRequest(); - Long savedTopicId = topicService.createTopic(topicCreateRequest, FileTestUtil.getMultipartFile("name"), - "topic"); + Long savedTopicId = topicService.createTopic(topicCreateRequest); //when TopicDetailResponse topicById = topicService.getTopicById(savedTopicId); @@ -65,8 +63,7 @@ public void setup() { public void 토픽_수정() throws Exception { //given TopicCreateRequest topicCreateRequest = getTopicCreateRequest(); - Long savedTopicId = topicService.createTopic(topicCreateRequest, FileTestUtil.getMultipartFile("name"), - "topic"); + Long savedTopicId = topicService.createTopic(topicCreateRequest); //when TopicUpdateRequest topicUpdateRequest = TopicUpdateRequest.builder() @@ -76,7 +73,7 @@ public void setup() { .pointPerPerson(topic.getPointPerPerson()) .notice(topic.getNotice()).build(); - topicService.updateTopic(savedTopicId, topicUpdateRequest, FileTestUtil.getMultipartFile("name"), fileType); + topicService.updateTopic(savedTopicId, topicUpdateRequest); //then Optional findTopic = topicRepository.findById(savedTopicId); @@ -88,8 +85,7 @@ public void setup() { public void 토픽_삭제() throws Exception { //given TopicCreateRequest topicCreateRequest = getTopicCreateRequest(); - Long savedTopicId = topicService.createTopic(topicCreateRequest, FileTestUtil.getMultipartFile("name"), - fileType); + Long savedTopicId = topicService.createTopic(topicCreateRequest); //when topicService.deleteTopic(savedTopicId); diff --git a/src/test/java/com/genius/gitget/challenge/instance/controller/InstanceControllerTest.java b/src/test/java/com/genius/gitget/challenge/instance/controller/InstanceControllerTest.java index d050d2c2..d6bfe860 100644 --- a/src/test/java/com/genius/gitget/challenge/instance/controller/InstanceControllerTest.java +++ b/src/test/java/com/genius/gitget/challenge/instance/controller/InstanceControllerTest.java @@ -14,6 +14,7 @@ import com.genius.gitget.challenge.instance.domain.Progress; import com.genius.gitget.challenge.instance.repository.InstanceRepository; import com.genius.gitget.challenge.user.domain.Role; +import com.genius.gitget.global.file.domain.FileType; import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.file.service.FilesService; import com.genius.gitget.util.TokenTestUtil; @@ -35,12 +36,13 @@ @SpringBootTest @Transactional public class InstanceControllerTest { + private static Topic savedTopic1, savedTopic2; + private static Instance savedInstance1, savedInstance2; MockMvc mockMvc; @Autowired WebApplicationContext context; @Autowired TokenTestUtil tokenTestUtil; - @Autowired TopicRepository topicRepository; @Autowired @@ -48,9 +50,6 @@ public class InstanceControllerTest { @Autowired FilesService filesService; - private static Topic savedTopic1, savedTopic2; - private static Instance savedInstance1, savedInstance2; - @BeforeEach public void setup() { mockMvc = MockMvcBuilders @@ -147,7 +146,7 @@ public void setup() { private Topic getSavedTopic() { MultipartFile filename = FileTestUtil.getMultipartFile("sky"); - Files files = filesService.uploadFile(filename, "topic"); + Files files = filesService.uploadFile(filename, FileType.TOPIC); Topic topic = topicRepository.save( Topic.builder() diff --git a/src/test/java/com/genius/gitget/challenge/instance/repository/InstanceSearchRepositoryTest.java b/src/test/java/com/genius/gitget/challenge/instance/repository/InstanceSearchRepositoryTest.java index a940dc98..f0e11a1f 100644 --- a/src/test/java/com/genius/gitget/challenge/instance/repository/InstanceSearchRepositoryTest.java +++ b/src/test/java/com/genius/gitget/challenge/instance/repository/InstanceSearchRepositoryTest.java @@ -195,7 +195,6 @@ private void createInstance(Topic savedTopic, Instance instance, String title) { .pointPerPerson(instance.getPointPerPerson()) .startedAt(instance.getStartedDate()) .completedAt(instance.getCompletedDate()).build(), - FileTestUtil.getMultipartFile("name"), "instance", instance.getStartedDate().minusDays(3).toLocalDate()); } } diff --git a/src/test/java/com/genius/gitget/challenge/instance/service/InstanceSearchServiceTest.java b/src/test/java/com/genius/gitget/challenge/instance/service/InstanceSearchServiceTest.java index cfb6b883..2f6fb164 100644 --- a/src/test/java/com/genius/gitget/challenge/instance/service/InstanceSearchServiceTest.java +++ b/src/test/java/com/genius/gitget/challenge/instance/service/InstanceSearchServiceTest.java @@ -9,7 +9,6 @@ import com.genius.gitget.challenge.instance.dto.search.InstanceSearchResponse; import com.genius.gitget.challenge.instance.repository.InstanceRepository; import com.genius.gitget.challenge.instance.repository.SearchRepository; -import com.genius.gitget.util.file.FileTestUtil; import java.io.IOException; import java.time.LocalDateTime; import lombok.extern.slf4j.Slf4j; @@ -91,7 +90,6 @@ private void createInstance(Topic savedTopic, Instance instance, String title) t .pointPerPerson(instance.getPointPerPerson()) .startedAt(instance.getStartedDate()) .completedAt(instance.getCompletedDate()).build(), - FileTestUtil.getMultipartFile("name"), "instance", instance.getCompletedDate().minusDays(3).toLocalDate()); } } diff --git a/src/test/java/com/genius/gitget/challenge/instance/service/InstanceServiceTest.java b/src/test/java/com/genius/gitget/challenge/instance/service/InstanceServiceTest.java index ab1d1606..2e085a3a 100644 --- a/src/test/java/com/genius/gitget/challenge/instance/service/InstanceServiceTest.java +++ b/src/test/java/com/genius/gitget/challenge/instance/service/InstanceServiceTest.java @@ -17,7 +17,6 @@ import com.genius.gitget.global.file.repository.FilesRepository; import com.genius.gitget.global.file.service.FilesService; import com.genius.gitget.global.util.exception.BusinessException; -import com.genius.gitget.util.file.FileTestUtil; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; @@ -32,7 +31,6 @@ import org.springframework.data.domain.PageRequest; import org.springframework.test.annotation.Rollback; import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.multipart.MultipartFile; @SpringBootTest @Transactional @@ -51,6 +49,7 @@ public class InstanceServiceTest { private Instance instance, instance1, instance2; private Topic topic; + private Files topicFiles; private String fileType; @BeforeEach @@ -83,8 +82,7 @@ public void setup() { InstanceCreateRequest instanceCreateRequest = getInstanceCreateRequest(savedTopic, instance); //when - instanceService.createInstance(instanceCreateRequest, - FileTestUtil.getMultipartFile("name"), fileType, currentDate); + instanceService.createInstance(instanceCreateRequest, currentDate); //then List all = instanceRepository.findAll(); @@ -99,8 +97,7 @@ public void setup() { Topic savedTopic = topicRepository.save(topic); InstanceCreateRequest instanceCreateRequest = getInstanceCreateRequest(savedTopic, instance); - Long savedInstanceId = instanceService.createInstance(instanceCreateRequest, - FileTestUtil.getMultipartFile("name"), fileType, currentDate); + Long savedInstanceId = instanceService.createInstance(instanceCreateRequest, currentDate); InstanceUpdateRequest instanceUpdateRequest = InstanceUpdateRequest.builder() .topicId(savedTopic.getId()) @@ -111,8 +108,7 @@ public void setup() { .build(); //when - Long updatedInstanceId = instanceService.updateInstance(savedInstanceId, instanceUpdateRequest, - FileTestUtil.getMultipartFile("name"), fileType); + Long updatedInstanceId = instanceService.updateInstance(savedInstanceId, instanceUpdateRequest); //then Optional byId = instanceRepository.findById(updatedInstanceId); @@ -126,8 +122,7 @@ public void setup() { Topic savedTopic = topicRepository.save(topic); InstanceCreateRequest instanceCreateRequest = getInstanceCreateRequest(savedTopic, instance); - Long savedInstanceId = instanceService.createInstance(instanceCreateRequest, - FileTestUtil.getMultipartFile("name"), fileType, currentDate); + Long savedInstanceId = instanceService.createInstance(instanceCreateRequest, currentDate); //when InstanceDetailResponse instanceById = instanceService.getInstanceById(savedInstanceId); @@ -206,52 +201,6 @@ public void setup() { }); } - @Nested - public class 인스턴스_삭제할_때 { - private Topic topic; - private Instance instance1, instance2, instance3; - - @BeforeEach - public void setup() { - topic = getSavedTopic("1일 1공부", "BE, ML"); - instance1 = getSavedInstance("1일 1공부", "BE, ML", 100); - instance2 = getSavedInstance("1일 3공부", "BE, ML", 100); - instance3 = getSavedInstance("1일 3공부", "BE, ML", 100); - instance1.setTopic(topic); - instance2.setTopic(topic); - } - - @Test - public void 해당_아이디가_존재한다면_삭제할_수_있다() { - Long id = instance1.getId(); - instanceService.deleteInstance(id); - - assertThrows(BusinessException.class, () -> { - instanceService.getInstanceById(id); - }); - } - - @Test - public void 해당_아이디가_존재하지_않는다면_삭제할_수_없다() { - Long id = instance3.getId() + 1L; - assertThrows(BusinessException.class, () -> { - instanceService.deleteInstance(id); - }); - } - - @Test - public void 해당_인스턴스에_파일이_존재한다면_같이_삭제한다() { - MultipartFile filename = FileTestUtil.getMultipartFile("sky"); - Files files1 = filesService.uploadFile(filename, "instance"); - - instance1.setFiles(files1); - instanceRepository.save(instance1); - - instanceService.deleteInstance(instance1.getId()); - } - } - - private Topic getSavedTopic(String title, String tags) { Topic topic = topicRepository.save( Topic.builder() @@ -305,4 +254,38 @@ private Files getSavedFiles(String originalFilename, String savedFilename, Strin .build() ); } + + @Nested + public class 인스턴스_삭제할_때 { + private Topic topic; + private Instance instance1, instance2, instance3; + + @BeforeEach + public void setup() { + topic = getSavedTopic("1일 1공부", "BE, ML"); + instance1 = getSavedInstance("1일 1공부", "BE, ML", 100); + instance2 = getSavedInstance("1일 3공부", "BE, ML", 100); + instance3 = getSavedInstance("1일 3공부", "BE, ML", 100); + instance1.setTopic(topic); + instance2.setTopic(topic); + } + + @Test + public void 해당_아이디가_존재한다면_삭제할_수_있다() { + Long id = instance1.getId(); + instanceService.deleteInstance(id); + + assertThrows(BusinessException.class, () -> { + instanceService.getInstanceById(id); + }); + } + + @Test + public void 해당_아이디가_존재하지_않는다면_삭제할_수_없다() { + Long id = instance3.getId() + 1L; + assertThrows(BusinessException.class, () -> { + instanceService.deleteInstance(id); + }); + } + } } diff --git a/src/test/java/com/genius/gitget/challenge/item/service/ItemServiceTest.java b/src/test/java/com/genius/gitget/challenge/item/service/ItemServiceTest.java index 159a368f..c17c5d83 100644 --- a/src/test/java/com/genius/gitget/challenge/item/service/ItemServiceTest.java +++ b/src/test/java/com/genius/gitget/challenge/item/service/ItemServiceTest.java @@ -67,42 +67,6 @@ class ItemServiceTest { @Autowired private CertificationRepository certificationRepository; - @Nested - class 유저_포인트가_충분할_때 { - - @ParameterizedTest - @EnumSource(mode = Mode.EXCLUDE, names = {"PROFILE_FRAME"}) - public void 아이템을_구매할_수_있다_1(ItemCategory itemCategory) { - User user = getSavedUser(); - Item item = getSavedItem(itemCategory); - getSavedOrder(user, item, itemCategory, 0); - user.setPoint(1000L); - - ItemResponse itemResponse = itemService.orderItem(user, item.getId()); - - assertThat(itemResponse.getItemCategory()).isEqualTo(itemCategory); - } - - @ParameterizedTest - @EnumSource(mode = Mode.EXCLUDE, names = {"PROFILE_FRAME"}) - public void 아이템을_구매할_수_있다_2(ItemCategory itemCategory) { - User user = getSavedUser(); - Item item = getSavedItem(itemCategory); - getSavedOrder(user, item, itemCategory, 0); - user.setPoint(1000L); - - ItemResponse itemResponse1 = itemService.orderItem(user, item.getId()); - - assertThat(user.getPoint()).isEqualTo(900L); - assertThat(itemResponse1.getCount()).isEqualTo(1); - - ItemResponse itemResponse2 = itemService.orderItem(user, item.getId()); - - assertThat(user.getPoint()).isEqualTo(800L); - assertThat(itemResponse2.getCount()).isEqualTo(2); - } - } - @Test @DisplayName("데이터베이스에 저장되어 있는 모든 아이템 정보들을 받아올 수 있다.") public void should_getAllItems_when_itemsSaved() { @@ -489,7 +453,6 @@ public void should_throwException_when_equipStatusIsNotIS_USE() { assertThat(profileResponses.size()).isEqualTo(0); } - private User getSavedUser() { return userRepository.save( User.builder() @@ -550,7 +513,6 @@ private Participant getSavedParticipant(User user, Instance instance) { return participant; } - private Certification getSavedCertification(CertificateStatus status, LocalDate certificatedAt, Participant participant) { int attempt = DateUtil.getAttemptCount(participant.getStartedDate(), certificatedAt); @@ -563,4 +525,40 @@ private Certification getSavedCertification(CertificateStatus status, LocalDate certification.setParticipant(participant); return certificationRepository.save(certification); } + + @Nested + class 유저_포인트가_충분할_때 { + + @ParameterizedTest + @EnumSource(mode = Mode.EXCLUDE, names = {"PROFILE_FRAME"}) + public void 아이템을_구매할_수_있다_1(ItemCategory itemCategory) { + User user = getSavedUser(); + Item item = getSavedItem(itemCategory); + getSavedOrder(user, item, itemCategory, 0); + user.updatePoints(1000L); + + ItemResponse itemResponse = itemService.orderItem(user, item.getId()); + + assertThat(itemResponse.getItemCategory()).isEqualTo(itemCategory); + } + + @ParameterizedTest + @EnumSource(mode = Mode.EXCLUDE, names = {"PROFILE_FRAME"}) + public void 아이템을_구매할_수_있다_2(ItemCategory itemCategory) { + User user = getSavedUser(); + Item item = getSavedItem(itemCategory); + getSavedOrder(user, item, itemCategory, 0); + user.updatePoints(1000L); + + ItemResponse itemResponse1 = itemService.orderItem(user, item.getId()); + + assertThat(user.getPoint()).isEqualTo(900L); + assertThat(itemResponse1.getCount()).isEqualTo(1); + + ItemResponse itemResponse2 = itemService.orderItem(user, item.getId()); + + assertThat(user.getPoint()).isEqualTo(800L); + assertThat(itemResponse2.getCount()).isEqualTo(2); + } + } } \ No newline at end of file diff --git a/src/test/java/com/genius/gitget/challenge/likes/controller/LikesControllerTest.java b/src/test/java/com/genius/gitget/challenge/likes/controller/LikesControllerTest.java index ac085f68..eb9f78ed 100644 --- a/src/test/java/com/genius/gitget/challenge/likes/controller/LikesControllerTest.java +++ b/src/test/java/com/genius/gitget/challenge/likes/controller/LikesControllerTest.java @@ -21,6 +21,7 @@ import com.genius.gitget.challenge.user.domain.Role; import com.genius.gitget.challenge.user.domain.User; import com.genius.gitget.challenge.user.repository.UserRepository; +import com.genius.gitget.global.file.domain.FileType; import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.file.service.FilesService; import com.genius.gitget.global.security.constants.ProviderInfo; @@ -229,7 +230,7 @@ private User getSavedUser() { private Topic getSavedTopic() { MultipartFile filename = FileTestUtil.getMultipartFile("sky"); - Files files = filesService.uploadFile(filename, "topic"); + Files files = filesService.uploadFile(filename, FileType.TOPIC); Topic topic = topicRepository.save( Topic.builder() diff --git a/src/test/java/com/genius/gitget/challenge/user/service/UserServiceTest.java b/src/test/java/com/genius/gitget/challenge/user/service/UserServiceTest.java index e7a7b8cf..d90d857c 100644 --- a/src/test/java/com/genius/gitget/challenge/user/service/UserServiceTest.java +++ b/src/test/java/com/genius/gitget/challenge/user/service/UserServiceTest.java @@ -9,8 +9,6 @@ import com.genius.gitget.challenge.user.domain.User; import com.genius.gitget.challenge.user.dto.SignupRequest; import com.genius.gitget.challenge.user.repository.UserRepository; -import com.genius.gitget.global.file.domain.FileType; -import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.security.constants.ProviderInfo; import com.genius.gitget.global.security.dto.AuthResponse; import com.genius.gitget.global.util.exception.BusinessException; @@ -60,12 +58,11 @@ public void should_matchValues_when_signupUser() { .information("information") .interest(List.of("관심사1", "관심사2")) .build(); - MultipartFile multipartFile = FileTestUtil.getMultipartFile("profile"); //when User user = userService.findUserByIdentifier(identifier); - Long signupUserId = userService.signup(signupRequest, multipartFile); + Long signupUserId = userService.signup(signupRequest); User foundUser = userService.findUserById(signupUserId); //then @@ -75,10 +72,6 @@ public void should_matchValues_when_signupUser() { assertThat(user.getInformation()).isEqualTo(foundUser.getInformation()); assertThat(user.getTags()).isEqualTo(foundUser.getTags()); assertThat(user.getRole()).isEqualTo(Role.USER); - - Files files = user.getFiles().get(); - assertThat(files.getFileType()).isEqualTo(FileType.PROFILE); - assertThat(files.getOriginalFilename()).contains(multipartFile.getOriginalFilename()); } @Test @@ -96,7 +89,7 @@ public void should_setRoleAdmin_when_identifierMatchesWithAdmin() { MultipartFile multipartFile = FileTestUtil.getMultipartFile("profile"); //when - Long signupUserId = userService.signup(signupRequest, multipartFile); + Long signupUserId = userService.signup(signupRequest); User signupUser = userService.findUserById(signupUserId); //then @@ -119,10 +112,10 @@ public void should_throwException_when_requestRegisterAgain() { //when User user = userService.findUserByIdentifier(identifier); - Long signupUserId = userService.signup(signupRequest, multipartFile); + Long signupUserId = userService.signup(signupRequest); //then - assertThatThrownBy(() -> userService.signup(signupRequest, multipartFile)) + assertThatThrownBy(() -> userService.signup(signupRequest)) .isInstanceOf(BusinessException.class) .hasMessageContaining(ErrorCode.ALREADY_REGISTERED.getMessage()); } diff --git a/src/test/java/com/genius/gitget/global/file/service/FileUtilTest.java b/src/test/java/com/genius/gitget/global/file/service/FileUtilTest.java index 99337796..cbaf07e4 100644 --- a/src/test/java/com/genius/gitget/global/file/service/FileUtilTest.java +++ b/src/test/java/com/genius/gitget/global/file/service/FileUtilTest.java @@ -10,10 +10,8 @@ import com.genius.gitget.global.file.domain.FileType; import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.file.dto.CopyDTO; -import com.genius.gitget.global.file.dto.UpdateDTO; -import com.genius.gitget.global.file.dto.UploadDTO; +import com.genius.gitget.global.file.dto.FileDTO; import com.genius.gitget.global.util.exception.BusinessException; -import com.genius.gitget.util.file.FileTestUtil; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -32,6 +30,8 @@ @Transactional @ActiveProfiles({"file"}) class FileUtilTest { + @Autowired + private FileUtil fileUtil; @Autowired private FilesService filesService; @Value("${file.upload.path}") @@ -44,7 +44,7 @@ public void should_throwException_when_originFilenameIsNull() { MultipartFile multipartFile = getTestMultiPartFile(null); //when&then - assertThatThrownBy(() -> FileUtil.validateFile(multipartFile)) + assertThatThrownBy(() -> fileUtil.validateFile(multipartFile)) .isInstanceOf(BusinessException.class) .hasMessageContaining(FILE_NOT_EXIST.getMessage()); } @@ -56,7 +56,7 @@ public void should_throwException_when_originFilenameIsBlank() { MultipartFile multipartFile = getTestMultiPartFile(""); //when&then - assertThatThrownBy(() -> FileUtil.validateFile(multipartFile)) + assertThatThrownBy(() -> fileUtil.validateFile(multipartFile)) .isInstanceOf(BusinessException.class) .hasMessageContaining(FILE_NOT_EXIST.getMessage()); } @@ -68,7 +68,7 @@ public void should_throwException_when_notSupportedExtension() { MultipartFile multipartFile = getTestMultiPartFile("sky.pdf"); //when&then - assertThatThrownBy(() -> FileUtil.validateFile(multipartFile)) + assertThatThrownBy(() -> fileUtil.validateFile(multipartFile)) .isInstanceOf(BusinessException.class) .hasMessageContaining(NOT_SUPPORTED_EXTENSION.getMessage()); } @@ -80,27 +80,10 @@ public void should_returnTargetFileInstance_when_passValidFile() { MultipartFile multipartFile = getTestMultiPartFile("sky.png"); //when - UploadDTO uploadDTO = FileUtil.getUploadInfo(multipartFile, "profile", UPLOAD_PATH); - - //then - assertThat(uploadDTO.fileURI()).contains(UPLOAD_PATH); - } - - @Test - @DisplayName("갱신 대상인 File을 전달했을 때, 갱신해야 할 정보들을 담은 UpdateDTO를 반환받는다.") - public void should_returnUpdateDTO_when_passUpdateTargetFile() { - //given - String originalFilename = "sky.png"; - MultipartFile multipartFile = getTestMultiPartFile(originalFilename); - FileType fileType = FileType.PROFILE; - - //when - UpdateDTO updateDTO = FileUtil.getUpdateInfo(multipartFile, fileType, UPLOAD_PATH); + FileDTO fileDTO = fileUtil.getFileDTO(multipartFile, FileType.PROFILE, UPLOAD_PATH); //then - assertThat(updateDTO.originalFilename()).isEqualTo(originalFilename); - assertThat(updateDTO.fileURI()).contains(UPLOAD_PATH); - assertThat(updateDTO.fileURI()).contains(updateDTO.savedFilename()); + assertThat(fileDTO.fileURI()).contains(UPLOAD_PATH); } @Test @@ -115,27 +98,13 @@ public void should_passInformation_when_tryToCopy() { .build(); //when - CopyDTO copyDTO = FileUtil.getCopyInfo(files, INSTANCE, UPLOAD_PATH); + CopyDTO copyDTO = fileUtil.getCopyInfo(files, INSTANCE, UPLOAD_PATH); //then assertThat(copyDTO.fileType()).isEqualTo(INSTANCE); assertThat(copyDTO.fileURI()).contains(UPLOAD_PATH); } - @Test - @DisplayName("FileTestUtil을 통해 받은 MultipartFile을 통해 인코딩 파일을 받을 수 있다") - public void should_getEncodedFiles() { - //given - MultipartFile multipartFile = FileTestUtil.getMultipartFile("filename"); - Files files = filesService.uploadFile(multipartFile, "topic"); - - //when - String encoded = FileUtil.encodedImage(files); - - //then - log.info(encoded); - } - private MultipartFile getTestMultiPartFile(String originalFilename) { return new MultipartFile() { diff --git a/src/test/java/com/genius/gitget/global/security/service/JwtServiceTest.java b/src/test/java/com/genius/gitget/global/security/service/JwtServiceTest.java index 716467bb..bbc6dfc3 100644 --- a/src/test/java/com/genius/gitget/global/security/service/JwtServiceTest.java +++ b/src/test/java/com/genius/gitget/global/security/service/JwtServiceTest.java @@ -13,12 +13,14 @@ import com.genius.gitget.challenge.user.repository.UserRepository; import com.genius.gitget.global.security.constants.JwtRule; import com.genius.gitget.global.security.constants.ProviderInfo; +import com.genius.gitget.global.security.repository.TokenRepository; import com.genius.gitget.global.util.exception.BusinessException; import com.genius.gitget.global.util.exception.ErrorCode; import com.genius.gitget.util.TokenTestUtil; import com.genius.gitget.util.WithMockCustomUser; import jakarta.servlet.http.Cookie; import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -35,6 +37,8 @@ @Slf4j @ActiveProfiles({"jwt"}) class JwtServiceTest { + @Autowired + private TokenRepository tokenRepository; @Autowired private JwtService jwtService; @Autowired @@ -42,6 +46,11 @@ class JwtServiceTest { @Autowired private TokenTestUtil tokenTestUtil; + @AfterEach + void clearMongo() { + tokenRepository.deleteAll(); + } + @Test @DisplayName("사용자 정보를 받아서 access-token을 생성할 수 있다.") public void should_generateAccess_when_passUserInfo() { diff --git a/src/test/java/com/genius/gitget/global/security/service/TokenServiceTest.java b/src/test/java/com/genius/gitget/global/security/service/TokenServiceTest.java index 2ec125c8..b2cc263d 100644 --- a/src/test/java/com/genius/gitget/global/security/service/TokenServiceTest.java +++ b/src/test/java/com/genius/gitget/global/security/service/TokenServiceTest.java @@ -4,6 +4,7 @@ import com.genius.gitget.global.security.domain.Token; import com.genius.gitget.global.security.repository.TokenRepository; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -19,6 +20,11 @@ class TokenServiceTest { @Autowired private TokenRepository tokenRepository; + @AfterEach + void clearMongo() { + tokenRepository.deleteAll(); + } + @Test @DisplayName("특정 리프레시 토큰을 identifier를 통해 DB에서 값을 조회할 수 있어야 한다.") public void should_findToken_when_findByIdentifier() { diff --git a/src/test/java/com/genius/gitget/payment/service/PaymentServiceTest.java b/src/test/java/com/genius/gitget/payment/service/PaymentServiceTest.java index 293072a2..4b91807d 100644 --- a/src/test/java/com/genius/gitget/payment/service/PaymentServiceTest.java +++ b/src/test/java/com/genius/gitget/payment/service/PaymentServiceTest.java @@ -87,7 +87,7 @@ private User getSavedUser() { User user = getSavedUser(); Item item = getSavedItem(itemCategory); getSavedOrder(user, item, itemCategory, 0); - user.setPoint(1000L); + user.updatePoints(1000L); ItemResponse itemResponse = itemService.orderItem(user, item.getId()); assertThat(itemResponse.getItemCategory()).isEqualTo(itemCategory); diff --git a/src/test/java/com/genius/gitget/profile/controller/ProfileControllerTest.java b/src/test/java/com/genius/gitget/profile/controller/ProfileControllerTest.java index f668002e..c2b7b1dd 100644 --- a/src/test/java/com/genius/gitget/profile/controller/ProfileControllerTest.java +++ b/src/test/java/com/genius/gitget/profile/controller/ProfileControllerTest.java @@ -19,6 +19,7 @@ import com.genius.gitget.challenge.user.domain.Role; import com.genius.gitget.challenge.user.domain.User; import com.genius.gitget.challenge.user.repository.UserRepository; +import com.genius.gitget.global.file.domain.FileType; import com.genius.gitget.global.file.domain.Files; import com.genius.gitget.global.file.service.FilesService; import com.genius.gitget.global.security.constants.ProviderInfo; @@ -278,7 +279,7 @@ private User getSavedUser() { private Topic getSavedTopic() { MultipartFile filename = FileTestUtil.getMultipartFile("sky"); - Files files = filesService.uploadFile(filename, "topic"); + Files files = filesService.uploadFile(filename, FileType.TOPIC); Topic topic = topicRepository.save( Topic.builder() diff --git a/src/test/java/com/genius/gitget/profile/service/ProfileServiceTest.java b/src/test/java/com/genius/gitget/profile/service/ProfileServiceTest.java index 927abbc4..0e19d837 100644 --- a/src/test/java/com/genius/gitget/profile/service/ProfileServiceTest.java +++ b/src/test/java/com/genius/gitget/profile/service/ProfileServiceTest.java @@ -113,7 +113,7 @@ void setup() { UserInformationUpdateRequest.builder() .nickname("수정된 nickname") .information("수정된 information") - .build(), null, "profile"); + .build()); User user = userRepository.findByIdentifier(user1.getIdentifier()) .orElseThrow(() -> new BusinessException(ErrorCode.MEMBER_NOT_FOUND)); @@ -159,7 +159,7 @@ void setup() { void 유저_포인트_조회() { User user = userRepository.findByIdentifier(user1.getIdentifier()) .orElseThrow(() -> new BusinessException(ErrorCode.MEMBER_NOT_FOUND)); - user.setPoint(1500L); + user.updatePoints(1500L); userRepository.save(user); UserPointResponse userPoint = profileService.getUserPoint(user1); Assertions.assertThat(userPoint.getPoint()).isEqualTo(1500); diff --git a/src/test/java/com/genius/gitget/util/WithMockCustomUserSecurityContextFactory.java b/src/test/java/com/genius/gitget/util/WithMockCustomUserSecurityContextFactory.java index 6956ef01..6b76ae5c 100644 --- a/src/test/java/com/genius/gitget/util/WithMockCustomUserSecurityContextFactory.java +++ b/src/test/java/com/genius/gitget/util/WithMockCustomUserSecurityContextFactory.java @@ -6,7 +6,6 @@ import com.genius.gitget.challenge.user.repository.UserRepository; import com.genius.gitget.challenge.user.service.UserService; import com.genius.gitget.global.security.service.CustomUserDetailsService; -import com.genius.gitget.util.file.FileTestUtil; import java.util.List; import java.util.Objects; import lombok.RequiredArgsConstructor; @@ -50,8 +49,7 @@ public SecurityContext createSecurityContext(WithMockCustomUser customUser) { .build(); User savedUser = userRepository.save(user); - Long signupId = userService.signup(signupRequest, - FileTestUtil.getMultipartFile(customUser.profileName())); + Long signupId = userService.signup(signupRequest); savedUser.updateRole(customUser.role()); UserDetails principal = customUserDetailsService.loadUserByUsername(String.valueOf(signupId));