Skip to content

Commit

Permalink
이미지 조회 로직 작성 (#48)
Browse files Browse the repository at this point in the history
* fix : 공통 응답 적용

* refactor : layered architecture 준수

* fix : 이미지 조회 로직 작성

* fix : 이미지 조회 로직 작성

* chore : swagger 전역 snake case 설정
  • Loading branch information
lsh1215 authored Nov 17, 2024
1 parent 0c252ec commit 02d3bb5
Show file tree
Hide file tree
Showing 10 changed files with 148 additions and 37 deletions.
18 changes: 18 additions & 0 deletions src/main/java/com/pictalk/global/config/ModelResolverConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.pictalk.global.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import io.swagger.v3.core.jackson.ModelResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class ModelResolverConfig {

@Bean
public ModelResolver modelResolver(ObjectMapper objectMapper) {
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
return new ModelResolver(objectMapper);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@ public enum ErrorStatus implements BaseStatus {
// Message Error
MESSAGE_NOT_FOUND(HttpStatus.NOT_FOUND, "MESSAGE_2001", "메시지를 찾을 수 없습니다."),
FILE_CONVERT_FAIL(HttpStatus.INTERNAL_SERVER_ERROR, "FILE_500", "파일 변환에 실패했습니다."),
NOT_SUPPORTED_IMAGE_TYPE(HttpStatus.INTERNAL_SERVER_ERROR, "IMAGE_500", "지원하지 않는 이미지 타입입니다."),
;
NOT_SUPPORTED_IMAGE_TYPE(HttpStatus.INTERNAL_SERVER_ERROR, "IMAGE_500", "지원하지 않는 이미지 타입입니다.");

private final HttpStatus httpStatus;
private final String code;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ public enum SuccessStatus implements BaseStatus {
CREATED(HttpStatus.CREATED, "COMMON_201", "성공적으로 생성되었습니다."),
NO_CONTENT(HttpStatus.NO_CONTENT, "COMMON_204", "성공적으로 삭제되었습니다."),

UPLOAD_IMAGE_SUCCESS(HttpStatus.CREATED, "IMAGE_201", "이미지가 성공적으로 저장되었습니다");
UPLOAD_IMAGE_SUCCESS(HttpStatus.CREATED, "IMAGE_201", "이미지가 성공적으로 저장되었습니다"),
GET_IMAGE_SUCCESS(HttpStatus.OK, "IMAGE_200", "이미지가 성공적으로 조회되었습니다"),
;

private final HttpStatus httpStatus;
private final String code;
Expand Down
37 changes: 32 additions & 5 deletions src/main/java/com/pictalk/message/controller/ImageController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@

import com.pictalk.global.payload.response.CommonResponse;
import com.pictalk.global.payload.status.SuccessStatus;
import com.pictalk.message.domain.MessageImage;
import com.pictalk.message.dto.ImageResponseDto;
import com.pictalk.message.service.MessageImageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
Expand All @@ -26,10 +30,33 @@ public class ImageController {
// 이미지 업로드
@Operation(summary = "이미지 업로드")
@PostMapping(value = "/messages/{message_id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<CommonResponse> uploadImage(@PathVariable("message_id") Long messageId,
@RequestPart(name = "image_file")
@Valid MultipartFile imageFile) {
public CommonResponse<Object> uploadImage(@PathVariable("message_id") Long messageId,
@RequestPart(name = "image_file")
@Valid MultipartFile imageFile) {
messageImageService.createImage(messageId, imageFile);
return ResponseEntity.ok(CommonResponse.of(SuccessStatus.UPLOAD_IMAGE_SUCCESS, null));
return CommonResponse.of(SuccessStatus.UPLOAD_IMAGE_SUCCESS, null);
}

@Operation(summary = "이미지 조회")
@GetMapping(value = "/messages/{message_id}")
public CommonResponse<ImageResponseDto.GetImagesResponse> getImage(@PathVariable("message_id") Long messageId) {
List<MessageImage> messageImages = messageImageService.getImage(messageId);
List<ImageResponseDto.ImageResponse> imageResponses = messageImages.stream()
.map(this::convertToImageResponse)
.collect(Collectors.toList());

ImageResponseDto.GetImagesResponse getImagesResponse = ImageResponseDto.GetImagesResponse.builder()
.images(imageResponses)
.build();

return CommonResponse.of(SuccessStatus.GET_IMAGE_SUCCESS, getImagesResponse);
}

private ImageResponseDto.ImageResponse convertToImageResponse(MessageImage messageImage) {
return ImageResponseDto.ImageResponse.builder()
.imageId(messageImage.getId())
.imageUrl(messageImage.getImage().getImageUrl())
.imageName(messageImage.getImage().getImageName())
.build();
}
}
54 changes: 44 additions & 10 deletions src/main/java/com/pictalk/message/controller/MessageController.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
package com.pictalk.message.controller;

import static com.pictalk.message.service.MessageService.getReceiversAsString;

import com.pictalk.global.payload.response.CommonResponse;
import com.pictalk.message.domain.Message;
import com.pictalk.message.domain.MessageImage;
import com.pictalk.message.dto.MessageRequestDto.SendMessageRequest;
import com.pictalk.message.dto.MessageResponseDto.*;
import com.pictalk.message.dto.MessageResponseDto.CancelMessageResponse;
import com.pictalk.message.dto.MessageResponseDto.MessageResponse;
import com.pictalk.message.dto.MessageResponseDto.SendMessageResponse;
import com.pictalk.message.service.MessageService;
import jakarta.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
Expand All @@ -20,7 +33,8 @@ public class MessageController {
private final MessageService messageService;

@PostMapping("/send")
public CommonResponse<SendMessageResponse> sendMessage(@AuthenticationPrincipal UserDetails authenticatedPrincipal, @Valid @RequestBody SendMessageRequest request) {
public CommonResponse<SendMessageResponse> sendMessage(@AuthenticationPrincipal UserDetails authenticatedPrincipal,
@Valid @RequestBody SendMessageRequest request) {
String userEmail = authenticatedPrincipal.getUsername();
SendMessageResponse response = messageService.sendMessage(request, userEmail);
return CommonResponse.onSuccess(response);
Expand All @@ -29,26 +43,46 @@ public CommonResponse<SendMessageResponse> sendMessage(@AuthenticationPrincipal
@GetMapping
public CommonResponse<List<MessageResponse>> getMessages(@AuthenticationPrincipal UserDetails authenticatedPrincipal) {
String userEmail = authenticatedPrincipal.getUsername();
List<MessageResponse> messages = messageService.getMessages(userEmail);
return CommonResponse.onSuccess(messages);
List<Message> messages = messageService.getMessages(userEmail);

List<MessageResponse> messageResponses = messages.stream().map(message -> MessageResponse.builder()
.messageId(message.getId())
.content(message.getContent())
.to(getReceiversAsString(message.getReceivers()))
.sendTime(message.getSentAt() != null ? message.getSentAt().toString() : null)
.messageImages(getImageUrls(message.getMessageImages()))
.status(message.getStatus().toString())
.build()
).collect(Collectors.toList());

return CommonResponse.onSuccess(messageResponses);
}

private List<String> getImageUrls(List<MessageImage> messageImages) {
return messageImages.stream()
.map(messageImage -> messageImage.getImage().getImageUrl())
.collect(Collectors.toList());
}

@GetMapping("/{message-id}")
public CommonResponse<MessageResponse> getMessage(@AuthenticationPrincipal UserDetails authenticatedPrincipal, @PathVariable("message-id") Long messageId) {
public CommonResponse<MessageResponse> getMessage(@AuthenticationPrincipal UserDetails authenticatedPrincipal,
@PathVariable("message-id") Long messageId) {
String userEmail = authenticatedPrincipal.getUsername();
MessageResponse response = messageService.getMessage(messageId, userEmail);
return CommonResponse.onSuccess(response);
}

@PatchMapping("/{message-id}")
public CommonResponse<CancelMessageResponse> cancelScheduledMessage(@AuthenticationPrincipal UserDetails authenticatedPrincipal, @PathVariable("message-id") Long messageId) {
public CommonResponse<CancelMessageResponse> cancelScheduledMessage(@AuthenticationPrincipal UserDetails authenticatedPrincipal,
@PathVariable("message-id") Long messageId) {
String userEmail = authenticatedPrincipal.getUsername();
CancelMessageResponse response = messageService.cancelScheduledMessage(messageId, userEmail);
return CommonResponse.onSuccess(response);
}

@DeleteMapping("/{message-id}")
public CommonResponse<Void> deleteMessage(@AuthenticationPrincipal UserDetails authenticatedPrincipal, @PathVariable("message-id") Long messageId) {
public CommonResponse<Void> deleteMessage(@AuthenticationPrincipal UserDetails authenticatedPrincipal,
@PathVariable("message-id") Long messageId) {
String userEmail = authenticatedPrincipal.getUsername();
messageService.deleteMessage(messageId, userEmail);
return CommonResponse.onSuccess(null);
Expand Down
22 changes: 22 additions & 0 deletions src/main/java/com/pictalk/message/dto/ImageResponseDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.pictalk.message.dto;

import java.util.List;
import lombok.Builder;
import lombok.Getter;

public class ImageResponseDto {

@Getter
@Builder
public static class GetImagesResponse {
private List<ImageResponse> images;
}

@Getter
@Builder
public static class ImageResponse {
private Long imageId;
private String imageUrl;
private String imageName;
}
}
2 changes: 2 additions & 0 deletions src/main/java/com/pictalk/message/dto/MessageResponseDto.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.pictalk.message.dto;

import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
Expand All @@ -26,6 +27,7 @@ public static class MessageResponse {
private String to;
private String sendTime;
private String status;
private List<String> messageImages;
}

@Getter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@

public interface MessageImageRepository extends JpaRepository<MessageImage, Long> {
List<MessageImage> findAllByMessage(Message message);


MessageImage findByMessage(Message message);
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import com.pictalk.message.domain.MessageImage;
import com.pictalk.message.repository.MessageImageRepository;
import com.pictalk.message.repository.MessageRepository;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand Down Expand Up @@ -35,4 +36,12 @@ public void deleteAllByMessage(Message message) {
messageImageRepository.findAllByMessage(message);
}

@Transactional(readOnly = true)
public List<MessageImage> getImage(Long messageId) {
final Message message = messageRepository.findById(messageId)
.orElseThrow(() -> new GeneralException(ErrorStatus.MESSAGE_NOT_FOUND));
message.getMessageImages();
List<MessageImage> messageImages = messageImageRepository.findAllByMessage(message);
return messageImages;
}
}
33 changes: 15 additions & 18 deletions src/main/java/com/pictalk/message/service/MessageService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,21 @@

import com.pictalk.global.exception.GeneralException;
import com.pictalk.global.payload.status.ErrorStatus;
import com.pictalk.message.domain.*;
import com.pictalk.message.dto.MessageRequestDto.*;
import com.pictalk.message.dto.MessageResponseDto.*;
import com.pictalk.message.domain.Message;
import com.pictalk.message.domain.Receiver;
import com.pictalk.message.dto.MessageRequestDto.SendMessageRequest;
import com.pictalk.message.dto.MessageResponseDto.CancelMessageResponse;
import com.pictalk.message.dto.MessageResponseDto.MessageResponse;
import com.pictalk.message.dto.MessageResponseDto.SendMessageResponse;
import com.pictalk.message.repository.MessageRepository;
import com.pictalk.user.domain.User;
import com.pictalk.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
Expand All @@ -40,23 +42,15 @@ public SendMessageResponse sendMessage(SendMessageRequest request, String userEm
}
}

public List<MessageResponse> getMessages(String userEmail) {
public List<Message> getMessages(String userEmail) {
User user = userRepository.findByEmail(userEmail)
.orElseThrow(() -> new GeneralException(ErrorStatus.USER_NOT_FOUND));

List<Message> messages = messageRepository.findAllByDeletedFalseAndSenderUser(user);

return messages.stream().map(message -> MessageResponse.builder()
.messageId(message.getId())
.content(message.getContent())
.to(getReceiversAsString(message.getReceivers()))
.sendTime(message.getSentAt() != null ? message.getSentAt().toString() : null)
.status(message.getStatus().toString())
.build()
).collect(Collectors.toList());
return messages;
}

private String getReceiversAsString(List<Receiver> receivers) {
public static String getReceiversAsString(List<Receiver> receivers) {
return receivers.stream()
.map(Receiver::getPhoneNumber)
.collect(Collectors.joining(", "));
Expand All @@ -75,6 +69,9 @@ public MessageResponse getMessage(Long messageId, String userEmail) {
.to(getReceiversAsString(message.getReceivers()))
.sendTime(message.getSentAt() != null ? message.getSentAt().toString() : null)
.status(message.getStatus().toString())
.messageImages(message.getMessageImages().stream()
.map(messageImage -> messageImage.getImage().getImageUrl())
.collect(Collectors.toList()))
.build();
}

Expand Down

0 comments on commit 02d3bb5

Please sign in to comment.