-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Help] 메시지 전송 로직에서 문제가 있는 부분 수정 #52
Changes from all commits
e2a8fc9
a64047a
c1ef4e1
f6c0fa8
a3f1c6e
cd768f4
7e91e13
fc41214
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
package com.pictalk.global.config; | ||
|
||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.web.client.RestTemplate; | ||
|
||
@Configuration | ||
public class RestTemplateConfig { | ||
|
||
@Bean | ||
public RestTemplate restTemplate() { | ||
return new RestTemplate(); | ||
} | ||
} | ||
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -69,7 +69,7 @@ public String createRefreshToken() { | |
.compact(); | ||
} | ||
|
||
// saveAndFlush 사용으로 @Transactional은 없어도 될 듯 | ||
// saveAndFlush 사용으로 @Transactional은 없어도 될 듯 | ||
public String reIssueRefreshToken(User user) { | ||
String reIssuedRefreshToken = createRefreshToken(); | ||
user.updateRefreshToken(reIssuedRefreshToken); | ||
|
@@ -122,4 +122,4 @@ public Optional<Claims> decodeAccessToken(String accessToken) { | |
return Optional.empty(); // 유효하지 않은 경우 빈 값 반환 | ||
} | ||
} | ||
} | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 코드를 검토한 결과, 아래와 같은 부분에서 수정이나 개선이 필요합니다.
이러한 사항들을 개선하면 코드의 가독성, 유지보수성 및 명확성이 향상될 것입니다. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,12 @@ | ||
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.domain.Receiver; | ||
import com.pictalk.message.dto.MessageRequestDto; | ||
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; | ||
|
@@ -36,12 +37,13 @@ public class MessageController { | |
public CommonResponse<SendMessageResponse> sendMessage(@AuthenticationPrincipal UserDetails authenticatedPrincipal, | ||
@Valid @RequestBody SendMessageRequest request) { | ||
String userEmail = authenticatedPrincipal.getUsername(); | ||
SendMessageResponse response = messageService.sendMessage(request, userEmail); | ||
MessageResponseDto.SendMessageResponse response = messageService.sendMessage(request, userEmail); | ||
return CommonResponse.onSuccess(response); | ||
} | ||
|
||
@GetMapping | ||
public CommonResponse<List<MessageResponse>> getMessages(@AuthenticationPrincipal UserDetails authenticatedPrincipal) { | ||
public CommonResponse<List<MessageResponse>> getMessages( | ||
@AuthenticationPrincipal UserDetails authenticatedPrincipal) { | ||
String userEmail = authenticatedPrincipal.getUsername(); | ||
List<Message> messages = messageService.getMessages(userEmail); | ||
|
||
|
@@ -53,28 +55,40 @@ public CommonResponse<List<MessageResponse>> getMessages(@AuthenticationPrincipa | |
.messageImages(getImageUrls(message.getMessageImages())) | ||
.status(message.getStatus().toString()) | ||
.build() | ||
).collect(Collectors.toList()); | ||
).toList(); | ||
|
||
return CommonResponse.onSuccess(messageResponses); | ||
} | ||
|
||
private List<String> getImageUrls(List<MessageImage> messageImages) { | ||
return messageImages.stream() | ||
.map(messageImage -> messageImage.getImage().getImageUrl()) | ||
.collect(Collectors.toList()); | ||
.toList(); | ||
} | ||
|
||
@GetMapping("/{message-id}") | ||
public CommonResponse<MessageResponse> getMessage(@AuthenticationPrincipal UserDetails authenticatedPrincipal, | ||
@PathVariable("message-id") Long messageId) { | ||
String userEmail = authenticatedPrincipal.getUsername(); | ||
MessageResponse response = messageService.getMessage(messageId, userEmail); | ||
Message message = messageService.getMessage(messageId, userEmail); | ||
|
||
MessageResponse response = MessageResponse.builder() | ||
.messageId(message.getId()) | ||
.content(message.getContent()) | ||
.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(); | ||
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); | ||
|
@@ -87,4 +101,19 @@ public CommonResponse<Void> deleteMessage(@AuthenticationPrincipal UserDetails a | |
messageService.deleteMessage(messageId, userEmail); | ||
return CommonResponse.onSuccess(null); | ||
} | ||
|
||
@PostMapping("/temp") | ||
public CommonResponse<MessageResponseDto.TempMessageResponse> saveTempMessage( | ||
@AuthenticationPrincipal UserDetails authenticatedPrincipal, | ||
@Valid @RequestBody MessageRequestDto.TempMessageRequest request) { | ||
String userEmail = authenticatedPrincipal.getUsername(); | ||
MessageResponseDto.TempMessageResponse response = messageService.saveTempMessage(request, userEmail); | ||
return CommonResponse.onSuccess(response); | ||
} | ||
|
||
private String getReceiversAsString(List<Receiver> receivers) { | ||
return receivers.stream() | ||
.map(Receiver::getPhoneNumber) | ||
.collect(Collectors.joining(", ")); | ||
} | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 코드 리뷰 결과, 다음과 같은 수정 및 개선 사항을 제안합니다:
이러한 개선점을 적용하면 코드의 가독성과 유지보수성이 높아질 것입니다. 추가적으로, 모든 메소드에 대한 단위 테스트를 작성하면 코드의 신뢰성을 더욱 강화할 수 있습니다. |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -52,17 +52,19 @@ public class Message extends BaseEntity { | |
|
||
private String content; | ||
|
||
@Column(nullable = false) | ||
private LocalDateTime createdAt; | ||
|
||
private LocalDateTime updatedAt; | ||
private LocalDateTime sentAt; | ||
|
||
@Builder.Default | ||
private boolean deleted = false; | ||
@Column(name = "external_message_id") | ||
private String externalMessageId; | ||
|
||
public void addReceivers(List<Receiver> newReceivers) { | ||
this.receivers.addAll(newReceivers); | ||
newReceivers.forEach(receiver -> receiver.associateWithMessage(this)); | ||
} | ||
|
||
public void addReceivers(List<Receiver> receivers) { | ||
this.receivers.addAll(receivers); | ||
public void addReceiver(Receiver receiver) { | ||
this.receivers.add(receiver); | ||
receiver.associateWithMessage(this); | ||
} | ||
|
||
public void cancel() { | ||
|
@@ -71,7 +73,8 @@ public void cancel() { | |
} | ||
} | ||
|
||
public void softDelete() { | ||
this.deleted = true; | ||
public Message withExternalMessageId(String externalMessageId) { | ||
this.externalMessageId = externalMessageId; | ||
return this; | ||
} | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 코드를 살펴본 결과, 다음과 같은 부분에서 수정이나 개선이 필요합니다:
수정 후 코드는 다음과 같이 개선될 수 있습니다: public class Message extends BaseEntity {
private String content;
@Column(name = "external_message_id")
private String externalMessageId;
private LocalDateTime sentAt;
private List<Receiver> receivers = new ArrayList<>();
public void addMultipleReceivers(List<Receiver> newReceivers) {
this.receivers.addAll(newReceivers);
newReceivers.forEach(receiver -> receiver.associateWithMessage(this));
}
public void addSingleReceiver(Receiver receiver) {
this.receivers.add(receiver);
receiver.associateWithMessage(this);
}
public void cancel() {
// Cancellation logic
}
public Message withExternalMessageId(String externalMessageId) {
this.externalMessageId = externalMessageId;
return this;
}
} 위의 제안들을 통해 코드의 가독성과 유지 보수성을 높일 수 있습니다. |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,5 +3,6 @@ | |
public enum MessageStatus { | ||
SCHEDULED, // 예약됨 | ||
SENT, // 전송됨 | ||
CANCELLED // 예약 취소됨 | ||
CANCELLED, // 예약 취소됨 | ||
TEMP // 임시 저장됨 | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 코드에서 수정이 필요한 부분과 개선할 점은 다음과 같습니다.
개선된 코드는 다음과 같이 될 수 있습니다: public enum MessageStatus {
SCHEDULED, // 예약됨
SENT, // 전송됨
CANCELLED, // 예약 취소됨
TEMP; // 임시 저장됨
} 이와 같은 방식으로 Enum의 사용 및 정의를 개선할 수 있습니다. |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -52,4 +52,7 @@ public Receiver(String nickname, String phoneNumber) { | |
this.phoneNumber = phoneNumber; | ||
} | ||
|
||
public void associateWithMessage(Message message) { | ||
this.message = message; | ||
} | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 코드의 일부를 검토해보니 다음과 같은 몇 가지 개선점이 있습니다.
개선된 예시는 다음과 같습니다: public class Receiver {
private String nickname;
private String phoneNumber;
private Message message;
public Receiver(String nickname, String phoneNumber) {
this.nickname = nickname;
this.phoneNumber = phoneNumber;
}
/**
* 메시지를 설정합니다. 메시지가 null인 경우 예외를 던집니다.
* @param message 설정할 메시지
* @throws IllegalArgumentException 메시지가 null일 경우
*/
public void setMessage(Message message) {
if (message == null) {
throw new IllegalArgumentException("메시지는 null일 수 없습니다.");
}
this.message = message;
}
public Message getMessage() {
return message;
}
} 이렇게 변경하면 코드의 안정성을 높이고, 가독성을 개선할 수 있습니다. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
package com.pictalk.message.domain; | ||
|
||
public class Request { | ||
|
||
private String requestUri; | ||
private String authorization; | ||
|
||
public Request(String requestUri, String authorization) { | ||
this.requestUri = requestUri; | ||
this.authorization = authorization; | ||
} | ||
|
||
public String getRequestUri() { | ||
return requestUri; | ||
} | ||
|
||
public String getAuthorization() { | ||
return authorization; | ||
} | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 코드를 살펴본 결과, 일부 개선할 수 있는 부분이 있습니다.
이러한 개선사항을 반영하면 코드의 가독성과 안정성을 높일 수 있을 것입니다. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,25 @@ | ||
package com.pictalk.message.domain; | ||
|
||
import com.pictalk.user.domain.User; | ||
import jakarta.persistence.*; | ||
import lombok.*; | ||
|
||
import jakarta.persistence.Column; | ||
import jakarta.persistence.Entity; | ||
import jakarta.persistence.FetchType; | ||
import jakarta.persistence.GeneratedValue; | ||
import jakarta.persistence.GenerationType; | ||
import jakarta.persistence.Id; | ||
import jakarta.persistence.JoinColumn; | ||
import jakarta.persistence.ManyToOne; | ||
import jakarta.persistence.OneToMany; | ||
import jakarta.persistence.PrePersist; | ||
import jakarta.persistence.Table; | ||
import java.time.LocalDateTime; | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import lombok.AccessLevel; | ||
import lombok.AllArgsConstructor; | ||
import lombok.Builder; | ||
import lombok.Getter; | ||
import lombok.NoArgsConstructor; | ||
|
||
@Entity | ||
@Table(name = "sender") | ||
|
@@ -37,9 +50,6 @@ public class Sender { | |
@Column(updatable = false) | ||
private LocalDateTime createdAt; | ||
|
||
@Builder.Default | ||
private boolean deleted = false; | ||
|
||
@PrePersist | ||
protected void onCreate() { | ||
createdAt = LocalDateTime.now(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 코드를 리뷰하겠습니다. 다음과 같은 부분에서 수정이 필요하거나 개선할 수 있는 점이 있습니다.
위의 점들을 고려하여 코드 개선을 진행하면 좋겠습니다. |
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -22,10 +22,10 @@ public static class SendMessageRequest { | |
private int targetCount; | ||
private List<Target> targets; | ||
private String refKey; | ||
private String rejectType; | ||
private String sendTime; | ||
private String subject; | ||
private List<FileDto> files; | ||
// private String rejectType; | ||
// private String sendTime; | ||
// private String subject; | ||
// private List<FileDto> files; | ||
} | ||
|
||
@Getter | ||
|
@@ -62,6 +62,13 @@ public static class FileDto { | |
private String data; | ||
} | ||
|
||
@Getter | ||
public static class TempMessageRequest { | ||
private String content; | ||
private String to; | ||
private String sendTime; | ||
} | ||
|
||
@Getter | ||
public static class CreateAIMessageRequest { | ||
private String situation; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 코드에서 수정이 필요하거나 리팩토링할 수 있는 부분에 대해 다음과 같은 피드백을 드립니다:
이 점들을 고려하여 코드를 수정하고 개선해보세요. |
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -39,6 +39,13 @@ public static class CancelMessageResponse { | |
private String status; | ||
} | ||
|
||
@Getter | ||
@Builder | ||
public static class TempMessageResponse { | ||
private Long messageId; | ||
private String status; | ||
} | ||
|
||
@Getter | ||
@Builder | ||
public static class CreateAIMessageResponse { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 코드를 검토한 결과, 다음과 같은 부분들이 개선될 수 있습니다.
이러한 개선사항을 통해 코드의 가독성과 유지보수성을 높이고, 잠재적인 오류를 줄일 수 있습니다. |
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,18 +2,16 @@ | |
|
||
import com.pictalk.message.domain.Message; | ||
import com.pictalk.user.domain.User; | ||
|
||
import java.util.List; | ||
import java.util.Optional; | ||
|
||
import org.springframework.data.jpa.repository.JpaRepository; | ||
import org.springframework.stereotype.Repository; | ||
|
||
@Repository | ||
public interface MessageRepository extends JpaRepository<Message, Long> { | ||
// 삭제되지 않은 특정 사용자의 모든 메시지 조회 | ||
List<Message> findAllByDeletedFalseAndSenderUser(User user); | ||
List<Message> findAllBySenderUser(User user); | ||
|
||
// 삭제되지 않은 특정 사용자의 특정 메시지 조회 | ||
Optional<Message> findByIdAndSenderUserAndDeletedFalse(Long id, User user); | ||
Optional<Message> findByIdAndSenderUser(Long id, User user); | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 코드에서 수정이 필요하거나 리팩토링할 수 있는 부분에 대해 제안하겠습니다.
// Optional을 사용하여 안전하게 처리하도록 작업
Optional<Message> message = messageRepository.findByIdAndSenderUser(id, user);
message.ifPresentOrElse(
m -> {/* 메시지가 있을 경우 처리 */},
() -> {/* 메시지가 없을 경우 처리 */}
);
위의 고려 사항을 통해 코드의 가독성과 유지보수성을 높일 수 있습니다. |
This file was deleted.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
코드를 전반적으로 살펴보았을 때 몇 가지 개선 사항을 제안할 수 있습니다.
RestTemplate의 사용자 정의 설정:
RestTemplate
을 사용할 때 일반적으로 커스터마이징이 필요할 수 있습니다. 예를 들어, 타임아웃 설정이나 메시지 컨버터를 추가하는 방법을 고려할 수 있습니다.RestTemplate의 단일 빈 사용:
RestTemplate
은 스레드 세이프(Thread-safe)하므로 애플리케이션 내에서 단일 인스턴스를 공유하는 것이 좋습니다. 현재 코드에서는 이 부분이 적절하게 처리되고 있습니다.상수 사용: 타임아웃과 같은 상수 값을 사용할 때, 하드코딩 대신 상수로 선언하고 사용하는 것이 좋습니다. 이렇게 하면 유지보수성이 높아집니다.
Exception Handling: API 호출 시 예외 처리를 좀 더 구체화할 수 있습니다. 특정 예외 발생 시 어떻게 처리할지에 대한 로직을 추가하는 것도 좋습니다.
로깅:
RestTemplate
을 사용할 때 요청과 응답에 대한 로깅을 추가하면 디버깅에 유용합니다. 이를 위해ClientHttpRequestInterceptor
를 구현할 수 있습니다.이와 같이 수정하면
RestTemplate
의 기능성을 높이고 향후 확장성 및 유지보수성을 고려할 수 있습니다.