Skip to content

Commit

Permalink
Merge pull request #33 from najakgil/feature/#32
Browse files Browse the repository at this point in the history
[Refactor]: response type 변경
  • Loading branch information
hw130 committed Feb 24, 2024
2 parents a761702 + 2126237 commit 68fb808
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 108 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,4 @@ out/
### yml secret ###
/src/main/resources/application-local.yml


Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
package com.example.developjeans.controller;
import com.example.developjeans.dto.PhotoDto;
import com.example.developjeans.exception.BusinessLogicException;
import com.example.developjeans.exception.ExceptionCode;
import com.example.developjeans.global.config.aws.S3Service;
import com.example.developjeans.global.config.response.BaseResponse;
import com.example.developjeans.service.PhotoService;
import com.fasterxml.jackson.databind.ser.Serializers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -33,75 +38,64 @@ public class PhotoController {

private final PhotoService photoService;

@Operation(summary = "사진 저장하기(다운로드x)", description = "디비에 유저가 만든 사진을 저장합니다.")
@Operation(summary = "사진 저장하기(다운로드x)", description = "디비에 유저가 만든 사진을 저장합니다.", responses = {
@ApiResponse(responseCode = "200", description = "default response", content = @Content(schema = @Schema(implementation = PhotoDto.PhotoSaveResponseDto.class))),
@ApiResponse(responseCode = "404", description = "존재하지 않는 리소스 접근")
})
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> uploadFile(@RequestParam("userId") Long userId, @RequestPart(value = "image", required = false) MultipartFile image) {
public BaseResponse<?> uploadFile(@RequestParam("userId") Long userId, @RequestPart(value = "image", required = false) MultipartFile image) {

return ResponseEntity.ok("photoId=" + photoService.uploadFile(image, userId));
return new BaseResponse<>("photoId=" + photoService.uploadFile(image, userId));

}

@Operation(summary = "사진 조회하기", description = "마이페이지에서 사진 조회 기능입니다.")
@Operation(summary = "사진 조회하기", description = "마이페이지에서 사진 조회 기능입니다.", responses = {
@ApiResponse(responseCode = "200", description = "default response", content = @Content(schema = @Schema(implementation = PhotoDto.PhotoResponseDto.class))),
})
@GetMapping()
public ResponseEntity<?> getAllPhoto(@RequestParam("userId") Long userId){
public BaseResponse<?> getAllPhoto(@RequestParam("userId") Long userId){

return ResponseEntity.ok("photoId=" + photoService.getAllImages(userId));
return new BaseResponse<>(photoService.getAllImages(userId));


}

@Operation(summary = "좋아요", description = "사진에 좋아요를 누를 수 있는 기능입니다.")
@Operation(summary = "좋아요", description = "사진에 좋아요를 누를 수 있는 기능입니다.", responses = {
@ApiResponse(responseCode = "200", description = "default response", content = @Content(schema = @Schema(implementation = PhotoDto.PhotoLikeDto.class))),
})
@PostMapping("/likes")
public ResponseEntity<?> postLike(@RequestParam("photoId") Long photoId, @RequestParam("userId") Long userId) {
return ResponseEntity.ok(photoService.likePhoto(photoId, userId));
// Authentication principal = SecurityContextHolder.getContext().getAuthentication();
// String user = principal.getName();
//
// Long id = Long.parseLong(user);
//
// try{
// if (!id.equals(userId)) {
// return new BaseResponse<>(INVALID_JWT);
// }
// return new BaseResponse<>(photoService.likePhoto(photoId, userId));
// } catch(Exception e){
// e.printStackTrace();
// return new BaseResponse<>(DATABASE_ERROR);
// }
public BaseResponse<?> postLike(@RequestParam("photoId") Long photoId, @RequestParam("userId") Long userId) {

return new BaseResponse<>(photoService.likePhoto(photoId, userId));

}
// @Operation(summary = "사진 차트", description = "홈에 있는 사진 차트 기능입니다.")
// @GetMapping("/chart")
// public ResponseEntity<?> getChartLikes(@RequestParam String standard,
// @RequestParam(name = "size") int size){
//
// return ResponseEntity.ok(photoService.getChart(standard, size));
//
// }

@Operation(summary = "사진 차트", description = "likes: 인기순, latest: 최신순")
@Operation(summary = "사진 차트", description = "likes: 인기순, latest: 최신순", responses = {
@ApiResponse(responseCode = "200", description = "default response", content = @Content(schema = @Schema(implementation = PhotoDto.PhotoChartDto.class))),
})
@GetMapping("/chart")
public ResponseEntity<?> getChartLikes(@RequestParam String sort,
public BaseResponse<?> getChartLikes(@RequestParam String sort,
@RequestParam(name = "size") int size,
@RequestParam Long lastPhotoId){

return ResponseEntity.ok(photoService.getChart(sort, size, lastPhotoId));
return new BaseResponse<>(photoService.getChart(sort, size, lastPhotoId));

}



@Operation(summary = "사진 상세 조회")
@Operation(summary = "사진 상세 조회", responses = {
@ApiResponse(responseCode = "200", description = "default response", content = @Content(schema = @Schema(implementation = PhotoDto.PhotoResponseDto.class)))
})
@GetMapping("/detail")
public ResponseEntity<?> getPhotoDetail(@RequestParam Long photoId){
return ResponseEntity.ok(photoService.getDetail(photoId));
public BaseResponse<?> getPhotoDetail(@RequestParam Long photoId){
return new BaseResponse<>(photoService.getDetail(photoId));
}

@Operation(summary = "사진 다운로드")
@GetMapping("/download")
public ResponseEntity<?> downloadImage(@RequestParam Long photoId) throws IOException {
return ResponseEntity.ok(photoService.downloadImage(photoId));
public BaseResponse<?> downloadImage(@RequestParam Long photoId) throws IOException {
return new BaseResponse<>(photoService.downloadImage(photoId));
}


Expand Down
2 changes: 2 additions & 0 deletions src/main/java/com/example/developjeans/dto/PhotoDto.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package com.example.developjeans.dto;

import com.example.developjeans.entity.Photo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import org.springframework.data.domain.Page;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Schema(description = "사진 Response")
public class PhotoDto {

@Getter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static org.springframework.web.servlet.function.RequestPredicates.contentType;


@Slf4j
@Service
@Transactional
Expand Down Expand Up @@ -115,17 +117,23 @@ public String getFile(String fileName) {

public ResponseEntity<byte[]> download(String fileUrl) throws IOException { // 객체 다운 fileUrl : 폴더명/파일네임.파일확장자

S3Object s3Object = amazonS3.getObject(new GetObjectRequest(bucket, fileUrl));
// 파일의 경로와 파일명을 추출
String[] urlParts = fileUrl.split("/");
String key = String.join("/", Arrays.copyOfRange(urlParts, 3, urlParts.length)); // 버킷명 다음의 경로부터가 키
log.info("key = " + key);

S3Object s3Object = amazonS3.getObject(new GetObjectRequest(bucket, key));
S3ObjectInputStream objectInputStream = s3Object.getObjectContent();
byte[] bytes = IOUtils.toByteArray(objectInputStream);

HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(contentType(fileUrl));
httpHeaders.setContentLength(bytes.length);

String[] arr = fileUrl.split("/");
String type = arr[arr.length - 1];
String fileName = URLEncoder.encode(type, "UTF-8").replaceAll("\\+", "%20");
// 파일명 추출 및 인코딩
String fileName = urlParts[urlParts.length - 1];
fileName = URLEncoder.encode(fileName, "UTF-8");
log.info("fileName = " + fileName);
httpHeaders.setContentDispositionFormData("attachment", fileName); // 파일이름 지정

return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
Expand All @@ -134,6 +142,7 @@ public ResponseEntity<byte[]> download(String fileUrl) throws IOException { //
private MediaType contentType(String keyname) {
String[] arr = keyname.split("\\.");
String type = arr[arr.length - 1];
log.info("type = " + type);
switch (type) {
case "txt":
return MediaType.TEXT_PLAIN;
Expand All @@ -145,6 +154,7 @@ private MediaType contentType(String keyname) {
return MediaType.APPLICATION_OCTET_STREAM;
}
}

}
/*
@Service
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import com.example.developjeans.entity.res.GetChartResponse;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.*;
Expand All @@ -40,6 +41,7 @@
@Service
@Transactional
@RequiredArgsConstructor
@Slf4j
public class PhotoService {

private final PhotoRepository photoRepository;
Expand Down Expand Up @@ -262,6 +264,8 @@ public PhotoDto.PhotoResponseDto getDetail(Long photoId){
public ResponseEntity<byte[]> downloadImage(Long photoId) throws IOException {
Photo photo = photoRepository.findById(photoId)
.orElseThrow(() -> new EntityNotFoundException("존재하지 않은 사진 ID: " + photoId));
log.info("사진 url: " + photo.getImgUrl());

return s3Service.download(photo.getImgUrl());
}
// @Transactional(readOnly = true)
Expand Down
65 changes: 0 additions & 65 deletions src/main/resources/application.yml

This file was deleted.

0 comments on commit 68fb808

Please sign in to comment.