1. ValidationPipe = @Type, 2. 하위 연관 dto 검증 = @ValidateNested
아래 코드의 문제점
export class UserInfo {
@ApiProperty({ type: Date })
@IsDateString()
@IsOptional()
@prop()
playTime?: Date;
@prop({ type: () => userStrongInfo })
@ApiProperty({ type: () => userStrongInfo })
@IsDefined()
@Type(() => userStrongInfo)
public userPower: userStrongInfo;
@prop({ type: () => userBaseInfo })
@ApiProperty({ description: '사용자 기본정보' })
@IsDefined()
@Type(() => userBaseInfo)
public userInfo: userBaseInfo;
}
userStrongInfo 클래스로 선언된 userPower와 userBaseInfo 클래스로 선언된 userinfo가 dto에서 사용될 때 validation이 되지 않는 단점이 있다.
- 하위 연관 클래스의 필드에 존재하지 않는 속성을 넣어도 값이 검증되지 않고 들어가진다.
- 하위 연관 클래스의 필수 속성을 넣지 않아도 검증되지 않고 들어가진다.
다음과 같이 존재하지 않는 'ㅋㅋ' 를 속성으로 넣는다.
{
"playTime": "2023-03-03T01:41:09.873Z",
"userPower": {
"level": 0,
"skills": [
"string"
],
"sheildPower": 0,
"magicPower": 0,
"swordPower": 0
},
"userBase": {
"name": "string",
"role": "Warrior",
"age": 0,
"major": 0,
"ㅋㅋ": 5
},
"createdAt": "2023-03-03T01:41:09.874Z",
"ㅋㅋ": 5
}
위 코드는 Request body로 dto를 넘긴다.
해당 입력값이 NestJS 콘솔에서 찍힌 dto
1. 가장 마지막에 있는 "ㅋㅋ"는 dto검증에서 삭제 되는 것을 볼 수 있다.
2. 하지만 userBase안에는 검증이 되지 않아 삭제되지 않았다.
3. db에 저장할 때는 entity와 한 번더 비교하여 없는 속성을 제거하므로 결국 db에는 모든 'ㅋㅋ'가 제거되고 저장된다.
* userBase에 major는 필수속성(required)으로 설정되어 있다.
이를 제외한 아래와 같은
{
"playTime": "2023-03-03T01:49:50.167Z",
"userPower": {
"level": 0,
"skills": [
"string"
],
"sheildPower": 0,
"magicPower": 0,
"swordPower": 0
},
"userBase": {
"name": "string",
"role": "Warrior",
"age": 0
},
"createdAt": "2023-03-03T01:49:50.167Z"
}
Request body로 dto를 넘긴다.
@ValidateNested()가 없을 때
1. 성공적으로 검증이 이루어지지 않아 위와 같이 성공한다
2. db에도 major속성 없이 값이 저장된다.
@ValidateNested()가 있을 때 출력 값
1. 성공적으로 검증이되어 위와 같이 400 Error가 나오면서 실패한다.
2. 해당 dto는 NestJS에 값이 들어오지도 않는다. (잘못된 값이기 때문에)
'개발 프레임워크 > NestJS' 카테고리의 다른 글
[NestJS] vscode Delete eslint (prettier/prettier)오류 (0) | 2023.08.24 |
---|---|
[MongoDB, NestJS] DB 트랜잭션을 이용한 자원소비 코드 (0) | 2023.03.26 |
[Mongoose] Model.events, Model관련 Error 처리 (0) | 2023.03.01 |
[NestJS] 배열 구문 분석 및 유효성 검사, DTO 검증 (0) | 2023.02.23 |
[NestJS] 매핑유형(Partial, Pick, Omit, Intersection) Type() (0) | 2023.02.23 |
댓글