오늘은 DTO 객체의 키 이름을 @Transform 데코레이터를 사용하여 바꾸는 방법에 대해 포스팅을 할 것이다.
음,, 이렇게만 얘기해서는 무슨소린지 헷갈리니 바로 예제 코드로 보자.
findBookmark=[
{
target_uuid: 123,
name: Blanc,
...
},
{
target_uuid: 234,
name: Jack,
...
},
{
target_uuid: 345,
name: Scott,
...
}
]
/////////////////////////////
BookmarkReadDto={
@Expose()
@ApiProperty()
uuid: string;
@Expose()
@ApiProperty(
name: string;
...
}
변수 findBookmark : [] 와 BookmarkReadDto가 해당 코드처럼 각각 존재한다.
나는 Response값으로 BookmarkReadDto 형태가 필요하므로 plainToInstance로 매핑을 해줘야 한다.
객체를 원하는 형태의 DTO로 매핑 시켜줄 수 있는 plainToInstance에 대한 설명이 있으니
한번 읽어보면 도움이 될 것이다...!
https://ilikezzi.tistory.com/9
다시 본론으로 돌아와서, 우선 매핑을 시켜보자.
이런식으로 plainToInstance를 사용하여 매핑을 시켜주었으나, 여기서 고민이 생겼다.
기존 findBookmark에 있는 객체의 target_uuid 라는 key값을
매핑한 BookmarkReadDto의 객체의 uuid 라는 key값으로 변경해서 사용해야했다.
그래서 강제로 for문을 돌면서 map함수를 사용해서 findBookmark의 target_uuid값을 추출해서
새로운 BookmarkReadDto의 uuid key값을 가진 객체에 넣을까 했는데
너무 비효율적인것 같아서 다른방법을 찾게 되었다.
이때 찾게 된게 DTO에서 @Transform 데코레이터 사용이다.
이렇게 해당 DTO파일에서
@Transform(({ obj }) => obj.target_uuid)
한줄만 추가해주면 끝이다.
@Transform 데코레이터가 uuid 속성에 적용된다.
데코레이터는 원래 개체를 나타내는 obj 속성을 포함하는 개체를 사용한다.
그런 다음 원래 개체의 target_uuid 속성을 반환하고,
이렇게 하면 DTO를 사용할 때 uuid 속성이 target_uuid 값으로 설정된다.
굉장히 간단하면서 편리하다..!
이제 매핑한 bookmarkReadDto를 콘솔을 찍어보자.
bookmarkReadDto=[
{
uuid: 123,
name: Blanc,
...
},
{
uuid: 234,
name: Jack,
...
},
{
uuid: 345,
name: Scott,
...
}
]
내가 원했던대로 key값이 target_uuid --> uuid 로 잘 바뀐걸 확인할 수 있을것이다.
'Web > NestJS' 카테고리의 다른 글
[Nest.JS] DTO vs Interface (0) | 2023.04.23 |
---|---|
[Nest.JS] Axios, Http 비동기 통신 라이브러리 (0) | 2023.04.15 |
[NestJS] DB커넥션을 최소화하고 Service부에 부하를 줘야하는 이유. (0) | 2023.03.27 |
[Nest.JS] @Param() 사용 시 왜 경로를 지정해 주는걸까? (0) | 2023.03.03 |
[Nest.JS] @Query() 파라미터 값 Boolean으로 사용하는 방법 (2) | 2023.03.01 |