๋ฌธ์ ์ํฉ
๋ณดํต ์ ๋ฌด ์ฝ๋์์ Entity๋ ํ ์ด๋ธ ์ ๋ณด์ ๋์ผํ๊ฒ ์ ์ํ๊ณ , DTO๋ API๋ฅผ ์ํด ๋ณ๋๋ก ์ ์ํ๊ฒ ๋ฉ๋๋ค. ๋ฌธ์ ๋ Entity์์ DTO๋ก ๋ณํํ๊ฑฐ๋ ๊ทธ ๋ฐ๋์ ๊ณผ์ ์ด ํ์ํ๋ฐ, ๊ฒน์น๋ ์์ฑ์ด ๋ง์์๋ ๊ฐ์ฒด๋ฅผ ์๋ก ์์ฑํ๊ฒ ๋๋ฉด ์ฝ๋๊ฐ ๊น๋ํด์ง์ง ์๋๋ค๋ ์ ์ ๋๋ค.
const foos = await this.getFooList();
return foos.map((foo) => ({
name: foo.name,
description: foo.description,
bar: someProcess(foo.bar),
// ..
}));ํด๊ฒฐ ๋ฐฉ์
class-transformer ํจํค์ง์ plainToInstance ํจ์๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค.
import { plainToInstance } from "class-transformer";
const foos = await this.getFooList();
return foos.map((foo) =>
plainToInstance(FooDto, {
...foo,
bar: someProcess(foo.bar),
})
);๋ณ๋์ ์ฒ๋ฆฌ๊ฐ ํ์ํ ๊ฒฝ์ฐ ํ์ํ ๊ฐ๋ง ๊ต์ฒดํ๋ฉด ๋๊ธฐ ๋๋ฌธ์ ์ ์ฐํ๊ฒ ๋์ฒํ ์ ์์ต๋๋ค.
@Expose ๋ฐ์ฝ๋ ์ดํฐ ํ์ฉ
ํน์ ํ๋๋ง ๋
ธ์ถํ๊ณ ์ถ์ ๊ฒฝ์ฐ @Expose() ๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ํ์ฉํ ์ ์์ต๋๋ค.
import { Expose, Exclude } from "class-transformer";
@Exclude()
export class FooDto {
@Expose()
name: string;
@Expose()
description: string;
// bar๋ ๋
ธ์ถ๋์ง ์์
bar: string;
}excludeExtraneousValues ์ต์
๊ณผ ํจ๊ป ์ฌ์ฉํ๋ฉด @Expose()๊ฐ ๋ถ์ ํ๋๋ง ๋ณํ๋ฉ๋๋ค.
plainToInstance(FooDto, data, { excludeExtraneousValues: true });๋์
DTO๊ฐ ๋ง๊ณ ๋งคํ์ด ๋ณต์กํด์ง๋ฉด @automapper/nestjs๋ฅผ ๊ณ ๋ คํด๋ณผ ์ ์์ต๋๋ค.