Skip to content

Commit

Permalink
feat(connect): POST:/api/connects 커넥트 요청 구현 (#62)
Browse files Browse the repository at this point in the history
* refactor: MemberNotFoundException의 Default String을 적자

개요

- 현재 여러 곳에서 MemberNotFoundException에 다양한 스트링을 사용 중인데
Default값을 정해서 통일성을 최대한 맞춘다. 다른 코드 refactoring은 이후
예정

* feat(connect): Connect 엔티티 생성 및 다대다 매핑 구현

개요

- 커넥트의 용도로 커넥트 엔티티와, ENUM 그리고 관련하여 매핑을 진행한다.

수정 사항

- Connect 엔티티
  - UniqueConstraints를 둬서 member1, 과 member2의 조합을 Unique하게
취급한다
  - `sortMember()`는 `@PreUpdate`, `@PrePersist` 어노테이션과 함께
사용하여, member1과 member2가 반대로 INSERT 쿼리 실행될 때, member1은
반드시 더 작은 member가 배정받도록한다.

  - `@ManyToOne` 매핑을 사용하여, Member와 매핑

- `ConnectStatus.java`
  - 현재 커넥트 요청 상태를 나타낸다

- `Member.java`
  - Member API 상에서 요청/응답할때, `id`값도 보이도록 `@JsonIgnore`를 없앤다
  - 다대다 매핑을 위해 sent, received 부분을 추가한다.(request 시에
 Member 값에 보이지 않음 참고로 매핑만을 위한 변수)

* feat(connect): Connect 리포지토리, 서비스 구현

개요

- Connect 리포지토리, 서비스를 구현하자

수정 사항

- `ConnectService.java`
  - ConnectDto를 넘겨받아
  - findById의 Optional을 처리하는 방법 중 기존 .get, isEmpty() 방식도
있지만, 최소한 간결한 표현을 찾던 중, orElseThrow를 찾음.
  - 이전 커밋에 정의했던 MemberNotFoundException Default 메시지 사용
(혹시 더 좋은 방법이 있으면 추천바랍니다)
  - 커넥트 요청을 Pending으로 저장함

- `ConnectDto.java`
  - @NotNull validation 추가
  - 요청 대상의 id를 받아옴
  - JsonProperty 추가해서 API 요청응답시 snakecase로 매칭되게끔함

* feat(connect): POST:/api/connects 구현

개요 사항

- POST:/api/connects 에 요청을 하면 상대방에서 친구추가를 보낸다.
- STATUS로는 CREATED를 리턴한다.
- Auth로 현재 유저 정보 가져옴
  • Loading branch information
seungholee-dev authored Apr 10, 2024
1 parent 5de68e6 commit a5b5557
Show file tree
Hide file tree
Showing 8 changed files with 170 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.dife.api.controller;

import com.dife.api.model.Member;
import com.dife.api.model.dto.ConnectDto;
import com.dife.api.service.ConnectService;
import com.dife.api.service.MemberService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
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
@RequestMapping("/api/connects")
public class ConnectController {

private final ConnectService connectService;
private final MemberService memberService;

@PostMapping("/")
public ResponseEntity<String> connect(@Valid @RequestBody ConnectDto requestDto, Authentication auth) {
Member currentMember = memberService.getMember(auth.getName());
connectService.connectMembers(requestDto, currentMember);

return ResponseEntity.status(HttpStatus.CREATED).body("커넥트 추가 성공");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.dife.api.exception;

public class MemberNotFoundException extends MemberException {

public MemberNotFoundException() {
super("해당 멤버는 존재하지 않습니다.");
}

public MemberNotFoundException(String message)
{
super(message);
}

public MemberNotFoundException(Throwable cause)
{
super(cause);
}

public MemberNotFoundException(String message, Throwable cause)
{
super(message, cause);
}
}
46 changes: 46 additions & 0 deletions rest-api/src/main/java/com/dife/api/model/Connect.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.dife.api.model;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;

import java.time.LocalDateTime;

@Getter
@Setter
@Entity
@Table(name = "connect", uniqueConstraints = @UniqueConstraint(columnNames = {"member1_id", "member2_id"}))
public class Connect {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@ManyToOne
@JoinColumn(name = "member1_id", referencedColumnName = "id")
private Member member1;

@NotNull
@ManyToOne
@JoinColumn(name = "member2_id", referencedColumnName = "id")
private Member member2;

@NotNull
@Enumerated(EnumType.STRING)
private ConnectStatus status;

@CreationTimestamp
private LocalDateTime createdAt;

@PreUpdate
@PrePersist
private void sortMember() {
if (this.member1.getId() > this.member2.getId()) {
Member temp = this.member1;
this.member1 = this.member2;
this.member2 = temp;
}
}
}
5 changes: 5 additions & 0 deletions rest-api/src/main/java/com/dife/api/model/ConnectStatus.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.dife.api.model;

public enum ConnectStatus {
PENDING, ACCEPTED
}
8 changes: 7 additions & 1 deletion rest-api/src/main/java/com/dife/api/model/Member.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
import lombok.Setter;

import java.time.LocalDateTime;
import java.util.Set;

@Getter
@Setter
@Entity
@Table(name = "member")
public class Member {

@JsonIgnore
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Expand Down Expand Up @@ -57,4 +57,10 @@ public class Member {

private String tokenId;

@OneToMany(mappedBy = "member1")
private Set<Connect> sent;

@OneToMany(mappedBy = "member2")
private Set<Connect> received;

}
17 changes: 17 additions & 0 deletions rest-api/src/main/java/com/dife/api/model/dto/ConnectDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.dife.api.model.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;
import lombok.*;

@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class ConnectDto {

@NotNull
@JsonProperty("member_id")
private Long memberId;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.dife.api.repository;

import com.dife.api.model.Connect;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ConnectRepository extends JpaRepository<Connect, Long> {
}
33 changes: 33 additions & 0 deletions rest-api/src/main/java/com/dife/api/service/ConnectService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.dife.api.service;

import com.dife.api.exception.MemberNotFoundException;
import com.dife.api.model.Connect;
import com.dife.api.model.ConnectStatus;
import com.dife.api.model.Member;
import com.dife.api.model.dto.ConnectDto;
import com.dife.api.repository.ConnectRepository;
import com.dife.api.repository.MemberRepository;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Transactional
public class ConnectService {
private final ConnectRepository connectRepository;
private final MemberRepository memberRepository;

public void connectMembers(ConnectDto dto, Member currentMember) {
Member connectMember = memberRepository.findById(dto.getMemberId())
.orElseThrow(MemberNotFoundException::new);

Connect connect = new Connect();
connect.setMember1(currentMember);
connect.setMember2(connectMember);
connect.setStatus(ConnectStatus.PENDING);

connectRepository.save(connect);
}
}

0 comments on commit a5b5557

Please sign in to comment.