Front End/React

class-transformer class에 정의되지 않은 properties 제외 plainToInstance ( excludeExtraneousValues 옵션 )

YJ_SW 2023. 3. 2. 19:27
728x90

수정기능을 개발하는데 등록/수정을 하는 class와 조회했을 때 class가 달라 class-transformer의 plainToInstance를 활용해 등록/수정을 하는 class로 변환하여 구현하려고 하였다.

예를 들어 회원을 등록할 때는 User class 를 사용하고 조회할 때는 Member class를 사용한다고 가정하자.

export class User {
    id!: string;
    password!: string;
    name!: string;
}
export class Member {
    id!: string;
    name!: string;
    memberTier!: string;
    postList!: Post[];
}

이와 같이 정의 되어있을 때 Member를 조회 후 이를 User class로 변환하여 수정하는 기능을 구현하고자 했다. Member 조회 결과에서 User에 정의되지 않은 속성들은 제외하고 사용하고자했다. 

 

그냥 plainToInstance를 사용하여 변환하면 자동으로 User에 있는 필드만 남겨줄거라 기대했다.

plainToInstance(User,memberData)

하지만 결과는 아래와 같이 데이터 그대로 다 남겨 변환해주었다.

plainToInstance(User,{   
    id: 'test',
    name: 1234,
    memberTier: 'gold',
    postList: [],
})

// 결과
{id: 'test', password: undefined, name: 1234, memberTier: 'gold', postList: Array(0)}

해결방법

class-transformer의 excludeExtraneousValues 옵션을 사용하면 된다. 

그전에 정의된 클래스에서 변환했을 때 남길 원하는 필드 앞에 @Expose() 데코레이터를 전부 붙여줘야 한다. 

export class User {
    @Expose() id!: string;
    @Expose() password!: string;
    @Expose() name!: string;
}

{ excludeExtraneousValues : true } 옵션을 주고 변환하면 아래와 같이 User에 정의되어 있지 않은 memberTier, postList는 사라지고 변환이 된다.

plainToInstance(User,{   
    id: 'test',
    name: 1234,
    memberTier: 'gold',
    postList: [],
},{excludeExtraneousValues:true})

// 결과
{id: 'test', password: undefined, name: 1234}

 

참고 : https://stackoverflow.com/questions/60542832/class-transformer-exclude-undefined-properties

728x90