Main.ts
import { ValidationPipe } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// whiteList : 엔티티 데코레이터에 없는 프로퍼티 값은 무조건 거름
// forbidNonWhitelisted : 엔티티 데코레이터에 없는 값 인입시 그 값에 대한 에러메세지 알려줌
// transform : 컨트롤러가 값을 받을때 컨트롤러에 정의한 타입으로 형변환
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true
})
);
await app.listen(3000);
}
bootstrap();
forbidNonWhitelisted
{
"statusCode": 400,
"message": ["property xxx should not exist"],
"error": "Bad Request"
}
- DTO 에 정의되지 않은 프로퍼티를 body에 넘길 시 설정한 에러 메시지를 띄워줌
- 즉, DTO 에 정의되지 않은 프로퍼티를 차단
transform
export class TestController {
@Delete("/:id")
// 원래 userId는 string이지만 `userId: number`로 지정함으로써 userId의 타입은 number로 변환
remove(@Param("id") userId: number) {
console.log(typeof userId); // number
}
}
- 원래 Param 으로 들어오는 값은 무조건 String
- 하지만 들어오는 Param 이 모두 숫자라는 것을 알고 있다면?
- 굳이 나중에 Number(paramId) 로 바꾸는 귀찮은 작업을 하지 않도록 해줌
DTO