일친 (IlChin) - User API 만들기

no.oneho·2025년 6월 1일
0

일친 개발기

목록 보기
14/17

이제 유저쪽 api를 만들시간이다.

유저 api는

1. 회원관리 (회원 등록, 조회, 수정, 삭제)

엔드포인트메서드요청 데이터응답 예시설명비고
/api/loginPOST{ "username": ..., "password": ... }{ "token": ... }로그인 후 JWT 토큰 발급
/api/usersPOST{ "username": ..., "password": ... }성공 메시지 또는 유저 상세회원 등록
/api/users/meGET-내 정보 상세내 정보 조회
/api/users/{id}PATCH{ "fullName": ..., "phone": ... }수정 완료 메시지회원 정보 수정이름, 핸드폰, 이메일 수정가능, 관리자, 부서 팀장일 경우 타인의 회원 정보 수정 가능
/api/users/{id}GET-회원 상세 정보특정 회원 정보 조회관리자나 해당 부서 팀장만 타인의 상세 정보 조회 가능
api/users/passwordPATCH{"password": ..., "confirmPassword": ...}패스워드 변경 완료
/api/users/{id}DELETE-삭제 성공회원 삭제소프트딜리트, 관리자 권한, 부서 팀장만 사용 가능
/api/usersGET{"pageSize": ..., "pageNumber": ..., "departmet": ..., "sortType": ..., "searchType": ..., "searchType": ...}회원 리스트회원 리스트 조회관리자 권한 일 경우 모든 회원 정보및 부서별 조회 가능, 그 외 본인의 부서 소속 회원만 조회 가능
/api/users/{id}/rolePATCH{"role": ...}변경 성공회원 권한 변경{ADMIN, MEMBER, GUEST}, 관리자 권한만 사용 가능

일단 이정도가 있고 현 시점에서 user <-> userProfile 테이블만 조인하면 된다.
조인같은경우 jpa의 entity끼리만 묶고 물리db에선 제외할것이다.

userProfile.class

@Column(name = "user_id", nullable = false)
    private Long userId;

기존에 작성된 이 컬럼을

@JoinColumn(name = "user_id", nullable = false)
    @ManyToOne(fetch = FetchType.LAZY)
    private User user;

이렇게 변경해준다.

변경 후 컴파일을 돌려 QClass에 반영해주고

제일 간단한 내 정보 조회 api를 만들어보자

//UserController
	@Auth
    @GetMapping
    public Response<UserProfileResp> getCurrentUserProfile() {
        return Api.success(200, "내 정보 조회 완료", userService.getCurrentUserProfile());
    }
    
//UserProfileResp
@Builder
public record UserProfileResp(
        String username,
        String email,
        String role,
        String fullName,
        String phoneNumber
) {}

//UserService
    public UserProfileResp getCurrentUserProfile() {
        User user = getCurrentUser();
        return userRepository.findUserProfileByUser(user);
    }
    
//findUserProfileByUser Method
@Override
    public UserProfileResp findUserProfileByUser(User currentUser) {
        return jpaQueryFactory
                .select(Projections.constructor(UserProfileResp.class,
                        user.username,
                        user.email,
                        user.role,
                        userProfile.fullName,
                        userProfile.phone))
                .from(user)
                .join(userProfile).on(user.eq(userProfile.user))
                .where(
                        user.eq(currentUser)
                )
                .fetchFirst();
    }

여기서 주의해야할점은 queryDSL에 생성자 주입 방식이다.
Projections.constructor는 매개변수로
(x.class, a, b, c, d, e) 를 받는데 dto 클래스 내부에 필드 순서와 쿼리에 적는 컬럼의 순서가 일치해야하고 불일치할 시 에러가 발생하므로 꼼꼼하게 체크해야한다.

결과를 보면

원하는대로 잘 나오는것을 알 수 있다.

이런 느낌으로 나머지 api도 작성해나가면 된다.

profile
이렇게 짜면 요구사항이나 기획이 변경됐을 때 불편하지 않을까? 라는 생각부터 시작해 설계를 해나가는 개발자

0개의 댓글