Skip to content

Commit

Permalink
Merge pull request #130 from dd-jiyun/main
Browse files Browse the repository at this point in the history
쪽지 기능 (받은 쪽지, 보낸 쪽지 조회)
  • Loading branch information
dd-jiyun authored Mar 1, 2024
2 parents 05e5aca + e1a7497 commit bcbad95
Show file tree
Hide file tree
Showing 7 changed files with 88 additions and 60 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);

Optional<User> findByNickname(String nickname);

boolean existsByNickname(String nickname);

boolean existsByStudentNo(String studentNo);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,9 @@ public class MessageController {
@ApiResponse(responseCode = "400", description = "잘못된 요청"),
@ApiResponse(responseCode = "500", description = "관리자 문의")
})
public ResponseEntity<MessageDTO> writeMessage(@RequestBody MessageDTO messageDTO,
public ResponseEntity<String> writeMessage(@RequestBody MessageDTO.Request request,
@AuthenticationPrincipal UserDetails userDetails) {
messageService.writeMessage(messageDTO, userDetails.getUsername());
return new ResponseEntity<>(HttpStatus.CREATED);
return ResponseEntity.status(HttpStatus.CREATED).body(messageService.writeMessage(request, userDetails.getUsername()));
}

@GetMapping("/receiver")
Expand All @@ -50,7 +49,7 @@ public ResponseEntity<MessageDTO> writeMessage(@RequestBody MessageDTO messageDT
@ApiResponse(responseCode = "400", description = "잘못된 요청"),
@ApiResponse(responseCode = "500", description = "관리자 문의")
})
public ResponseEntity<List<MessageDTO>> getMessagesByReceiver(@AuthenticationPrincipal UserDetails userDetails) {
public ResponseEntity<List<MessageDTO.Response>> getMessagesByReceiver(@AuthenticationPrincipal UserDetails userDetails) {
return new ResponseEntity<>(messageService.getMessagesByReceiver(userDetails.getUsername()), HttpStatus.OK);
}

Expand All @@ -63,9 +62,13 @@ public ResponseEntity<List<MessageDTO>> getMessagesByReceiver(@AuthenticationPri
@ApiResponse(responseCode = "400", description = "잘못된 요청"),
@ApiResponse(responseCode = "500", description = "관리자 문의")
})
public ResponseEntity<List<MessageDTO>> getMessagesBySender(@AuthenticationPrincipal UserDetails userDetails) {
public ResponseEntity<List<MessageDTO.Response>> getMessagesBySender(@AuthenticationPrincipal UserDetails userDetails) {
return new ResponseEntity<>(messageService.getMessagesBySender(userDetails.getUsername()), HttpStatus.OK);
}

//메세지 삭제 (sender인 유저가 receiver유저와 한 대화내용을 삭제)
//쪽지함 전체 조회
//쪽지함 세부 조회 ( 주고 받은 사용자와의 대화 내용을 뿌려줄 수 있는 api)

}

Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import lombok.NoArgsConstructor;
import lombok.Setter;

//TODO: 메세지 삭제 기능 추가 할거임?
@Entity
@Table(name = "messages")
@Getter
Expand All @@ -33,30 +32,33 @@ public class Message extends BaseEntity {
@Column(name = "message_id")
private Long id;

// FetchType.LAZY로 바꿔야할지 고민중
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "sender_id")
private User sender;

@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "receiver_id")
private User receiver;

@Column(name = "title", nullable = false, length = 100)
private String title;

@Column(name = "content", columnDefinition = "TEXT", nullable = false)
private String content;

@Column(name = "sent_time")
private LocalDateTime sentAt;

@Column(name = "sender_nickname")
private String senderNickname;

@Column(name = "receiver_nickname")
private String receiverNickname;

@Builder
public Message(User sender, User receiver, String title, String content) {
public Message(User sender, User receiver, String content, String senderNickname, String receiverNickname) {
this.sender = sender;
this.receiver = receiver;
this.title = title;
this.content = content;
this.senderNickname = senderNickname;
this.receiverNickname = receiverNickname;
this.sentAt = LocalDateTime.now();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,64 @@
package com.example.titto_backend.message.dto;

import com.example.titto_backend.message.domain.Message;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
// response 임!
public class MessageDTO {
private String title;
private String content;
private Long receiverId;

public static MessageDTO toDto(Message message) {
return new MessageDTO(
message.getTitle(),
message.getContent(),
message.getReceiver().getId()
);

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Schema(description = "메시지 작성")
public static class Request {
@Schema(description = "내용")
private String content;
@Schema(description = "받는 사람 닉네임")
private String receiverNickname;
}

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@Schema(description = "메시지 조회")
public static class Response {
@Schema(description = "메시지 ID")
private Long id;

@Schema(description = "내용")
private String content;

@Schema(description = "보낸 사람 ID")
private Long senderId;

@Schema(description = "받는 사람 ID")
private Long receiverId;

@Schema(description = "보낸 시간")
private String sentAt;

@Schema(description = "받는 사람 닉네임")
private String receiverNickname;

@Schema(description = "보낸 사람 닉네임")
private String senderNickname;

public Response(Message message) {
this.id = message.getId();
this.content = message.getContent();
this.senderId = message.getSender().getId();
this.receiverId = message.getReceiver().getId();
this.sentAt = message.getSentAt().toString();
this.receiverNickname = message.getReceiverNickname();
this.senderNickname = message.getSenderNickname();
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.example.titto_backend.common.exception.ErrorCode;
import com.example.titto_backend.message.domain.Message;
import com.example.titto_backend.message.dto.MessageDTO;
import com.example.titto_backend.message.dto.MessageDTO.Response;
import com.example.titto_backend.message.repository.MessageRepository;
import java.util.List;
import lombok.RequiredArgsConstructor;
Expand All @@ -20,23 +21,26 @@ public class MessageService {
private final UserRepository userRepository;

@Transactional
public void writeMessage(MessageDTO messageDTO, String email) {
public String writeMessage(MessageDTO.Request request, String email) throws CustomException {
User sender = userRepository.findByEmail(email)
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));

User receiver = userRepository.findById(messageDTO.getReceiverId())
User receiver = userRepository.findByNickname(request.getReceiverNickname())
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));

messageRepository.save(Message.builder()
.sender(sender)
.receiver(receiver)
.title(messageDTO.getTitle())
.content(messageDTO.getContent())
.senderNickname(sender.getNickname())
.receiverNickname(receiver.getNickname())
.content(request.getContent())
.build());

return "메시지 전송 성공";
}

@Transactional
public List<MessageDTO> getMessagesByReceiver(String email) {
public List<Response> getMessagesByReceiver(String email) {
User receiver = userRepository.findByEmail(email)
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));

Expand All @@ -45,17 +49,17 @@ public List<MessageDTO> getMessagesByReceiver(String email) {
}

@Transactional
public List<MessageDTO> getMessagesBySender(String email) {
public List<Response> getMessagesBySender(String email) {
User sender = userRepository.findByEmail(email)
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));

List<Message> messages = messageRepository.findAllBySender(sender);
return convertMessagesToDTO(messages);
}

private List<MessageDTO> convertMessagesToDTO(List<Message> messages) {
private List<MessageDTO.Response> convertMessagesToDTO(List<Message> messages) {
return messages.stream()
.map(MessageDTO::toDto)
.map(MessageDTO.Response::new)
.toList();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,6 @@ public static class Request {
@NotBlank
private String content;

// 아직 미완성 상태
@Schema(description = "이미지")
private List<String> imageList;

@Schema(description = "카테고리", example = "HUMANITIES, MANAGEMENT, SOCIETY, MEDIA_CONTENT, FUTURE_FUSION, SOFTWARE")
@NotBlank
private String department;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,26 +88,6 @@ public Page<QuestionDTO.Response> findByCategory(int page, String category) {
.map(QuestionDTO.Response::new);
}

/*// Keyword Search
private Specification<Question> searchByKeyword(String keyword) {
return new Specification<>() {
@Serial
private static final long serialVersionUID = 1L;
@Override
public Predicate toPredicate(Root<Question> q, CriteriaQuery<?> query, CriteriaBuilder cb) {
query.distinct(true);
Join<Question, User> u1 = q.join("author", JoinType.LEFT);
Join<Question, Answer> a = q.join("answers", JoinType.LEFT);
Join<Answer, User> u2 = a.join("author", JoinType.LEFT);
return cb.or(
cb.like(q.get("title"), "%" + keyword + "%"),
cb.like(q.get("content"), "%" + keyword + "%"),
cb.like(u1.get("nickname"), "%" + keyword + "%"),
cb.like(u2.get("nickname"), "%" + keyword + "%")
);
}
};*/
@Transactional(readOnly = true)
public Page<QuestionDTO.Response> searchByKeyword(String keyWord, int page) {
Pageable pageable = Pageable.ofSize(10).withPage(page);
Expand Down

0 comments on commit bcbad95

Please sign in to comment.