유효성 검사
- class-validator, class-transformer 패키지 설치
npm i class-validator class-transformer
- main.ts에 pipe 작성
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe()); // 유효성 검사 파이프
await app.listen(3000);
}
bootstrap();
* pipe
- 코드가 지나가는 길
- 미들웨어와 비슷한 역할
ValidationPipe
app.useGlobalPipes(
new ValidationPipe({ // 유효성 검사 파이프 생성
whitelist: true, // 아무 decorator도 없는 property는 object에서 제외
forbidNonWhitelisted: true, // DTO에 정의되지 않은 값이 존재하면 리퀘스트 거절
transform: true, // 리퀘스트의 파라미터를 실제 타입으로 변환
}),
);
DTO
- Data Transfer Object: 데이터 전송 객체
- 코드를 간결하게 하고 쿼리에 대한 유효성 검사 가능
- /movies/dto/create-movie.dto.ts
import { IsNumber, IsString } from 'class-validator';
export class CreateMovieDto {
@IsString()
readonly title: string;
@IsNumber()
readonly year: number;
@IsString({ each: true }) //모든 요소 검사
readonly genres: string[];
}

PartialType
- extends한 DTO의 속성을 옵션 타입으로 변환하고 사용할 수 있게 하는 패키지
- mapped-types
npm i @nestjs/mapped-types
- /movies/dto/update-movie-dto.ts
import { PartialType } from '@nestjs/mapped-types';
import { CreateMovieDto } from './create-movie.dto';
export class UpdateMovieDto extends PartialType(CreateMovieDto) {}
'개발 > JavaScript' 카테고리의 다른 글
| [NestJS] Unit Testing, End-to-End(E2E) (0) | 2022.08.10 |
|---|---|
| [NestJS] Modules, DI (0) | 2022.08.10 |
| [NestJS] Controller, Service (0) | 2022.08.10 |
| [NestJS] Project setup, 구조 (0) | 2022.08.10 |
| [JS] Promise, async, await (0) | 2022.08.09 |