plainToInstance() 사용 시 중첩된 객체 변환 문제

윤학·2023년 8월 14일
0

Nestjs

목록 보기
8/12
post-thumbnail

문제 상황

MongoDB를 이용하고 있는데 결과로 반환되는 Document들을 인스턴스로 변경하기 위하여 class-transformer의 plainToInstance()를 사용하고 있었다.

변환 후 아래와 같이 내부 객체에 접근해야 할 일이 있었는데

export class License {
    private name: string;
    private isCertified: boolean; // 증명됐는지 여부

    constructor(name: string, isCertified: boolean) {
        this.name = name;
        this.isCertified = isCertified;
    };

    getName(): string { return this.name; };
    getIsCertified(): boolean { return this.isCertified; };
}

license.getName is not a function이라는 오류가 떴다.

확인해봤더니 중첩된 객체까지는 인스턴스로 생성해 주지 않았다.

describe('plainToInstance() 중첩된 객체 Test', () => {
        it('plainToInstance()를 수행하고 나서 내부 객체에 접근할 수 있는지 확인', async() => {
            const testLicenseName = '테스트자격증';
            const testLicenseList = [ new License(testLicenseName, false) ];
            
            const testProfile = TestCaregiverProfile.default().licenseList(testLicenseList).build();

            const toLiteral = instanceToPlain(testProfile);
            const toInstace = plainToInstance(CaregiverProfile, toLiteral);

            expect(toInstace).toBeInstanceOf(CaregiverProfile);
            toInstace.getLicenseList().map( license => expect(license).toBeInstanceOf(License) );
        })
    })

해결법

당연히 plainToInstance()가 중첩된 객체까지 전부 변환해주는 줄 알고 있었다.

하지만 찾아보니 아니라는 것이 문서에 떡하니 나와있었다.

유형을 알 수 없기에 중첩된 객체까지 변환하려면 어떤 유형인지 @Type()으로 알려줘야 한다고 한다.

그럼 얼른 변환이 안됐던 필드에 적용하고 다시 테스트를 해보자.

	describe('plainToInstance() 중첩된 객체 Test', () => {
        it('plainToInstance()를 수행하고 나서 내부 객체에 접근할 수 있는지 확인', async() => {
            const testLicenseName = '테스트자격증';
            const testLicenseList = [ new License(testLicenseName, false) ];
            
            const testProfile = TestCaregiverProfile.default().licenseList(testLicenseList).build();

            const toLiteral = instanceToPlain(testProfile);
            const toInstace = plainToInstance(CaregiverProfile, toLiteral);

            expect(toInstace).toBeInstanceOf(CaregiverProfile);
            toInstace.getLicenseList().map( license => {
                expect(license).toBeInstanceOf(License) 
                expect(license.getName()).toBe(testLicenseName)
            });
        })
    })

중첩된 객체까지 잘 변환되는 것을 확인할 수 있다.

참고

npm class-transformer

profile
해결한 문제는 그때 기록하자

0개의 댓글