Tekies Community 백엔드 만들기 -4

노문택·2022년 1월 23일
0

저번 파트때.. 연결은 했지만.. 사실 여유가 나지 않아서 더 작성하는것을 관두었지만 이어서 하기로한다..

구현해야될부분 컨트롤러 / 서비스 / DTO / Entity (저번에함)

엥 ? Dto 파트랑 Entity랑 또이또이일꺼같은데 왜 나눠염?

Entity 클래스를 Request/Response 클래스로 쓰면 안된다라는 내용을 따르기로했습니다..

2021.0225 추가내용 Request를 Entity로 받으면 보안상의 문제가 될수 있기때문에 Request/Response용 DTO를 만들거나 혹슨 lIST 로 Mapping해 사용하는게 좋다고 정보를 찾았습니다. 그래서 필자는 DTO를 만들어 직접적으로 Entity에 대해 알지못하게 진행하였습니다.

로그인 및 회원가입 파트를 예시로 진행하기로 했습니다.

이부분을 하면 나머지는 응용파트..

먼저 Entity파트를 보면..
회원정보 수정기능을 넣기위해 User.class에 update 메소드를 추가해준다.

 public void update(String tc_id, String tc_password, String tc_email) {
        this.tc_id = tc_id;
        this.tc_password = tc_password;
        this.tc_email = tc_email;
    }

를추가해준다. 또한 생성자가없다면 @NoArgsConstructor 어노테이션을 넣어주도록한다.

Dto 파트
Dto 파트는 크게 Request/Response로 구성할수있다.

Response 파트는 롬복을이용한 처리를 하였다.

@Getter
@NoArgsConstructor
public class UserResponseDto {
    private int tc_num;
    private String tc_id;
    private String tc_password;
    private String tc_email;

    public UserResponseDto(User entity) {
        this.tc_num = entity.getTc_num();
        this.tc_id = entity.getTc_id();
        this.tc_password = entity.getTc_password();
        this.tc_email = entity.getTc_email();
    }
}

Request파트는 한 4시간정도 고민했던것같다..
updateRequest,, saveRequest사실..
하나로 뭉쳐서 만들고 그안에 메소드들을 호출해서 한번에 처리하면안될까?

그러나 기본적으로 값을 받아오는 갯수가 다르기때문에 목적에 따라 분류하는게 나을꺼같다고 느꼇다.
save의 경우 모든정보지만 update의 경우 사실 바꿀수있는정보가 password와 email뿐 합쳐서만들다보면
update를 할때도 id를 가져오기때문에 분리하는게맞다고 생각한다.

결론 : 사람들이 분리해놓은대는 이유가다 있다..

해당 지문에서는 save 버전만 구현하도록한다 update 도 같은방식으로 만들면됨

public class UserSaveRequestDto {
    private String tc_id;
    private String tc_password;
    private String tc_email;

    @Builder
    public UserSaveRequestDto(User entity) {
        this.tc_id = entity.getTc_id();
        this.tc_password = entity.getTc_password();
        this.tc_email = entity.getTc_email();
    }

    public User toEntity(){
        return User.builder()
                .tc_id(tc_id).tc_password(tc_password).tc_email(tc_email).build();
    }
}

Dto가 끝낫으니 Dto를 부를 service 작성

@RequiredArgsConstructor
@Service
public class UserService {
    private final UserRepository userRepository;

    @Transactional
    public int save (UserSaveRequestDto requestDto){
        return userRepository.save(requestDto.toEntity()).getTc_num();
    }
}

서비스를 작성했으면? 컨트롤러 작성을 하면 이제 save 기능이 완성된다.

@RequiredArgsConstructor
@RestController
public class UserController {
    private final UserService userService;

    @PostMapping("/v1/user/join")
    public int save(@RequestBody UserSaveRequestDto requestDto){
        return userService.save(requestDto);
    }
}

localhost/v1/user에 이제 담아서 보내면 자동으로 저장을 해준다. 이파트를 시험하기위해 jUnit등을 사용하지만 필자는 프론트도 만들꺼기에 프론트를 만들어 테스트 하기로 하였다.

post man 이있따.. 그걸로 테스트하기로결정.,..프론트느 ㄴ굳이 안해도될꺼같다.

해당 기능을 이용해 나머지 백엔드도 작성하여 완성

profile
노력하는 뚠뚠이

0개의 댓글