export class MessageCreateDto {
message: string
}
npm i --save class-validator class-transformer
...
async function bootstrap() {
const app = await NestFactory.create(AppModule)
app.useGlobalPipes(new ValidationPipe()) // New!
await app.listen(4000)
}
...
...
@Post()
@UsePipes(new ValidationPipe({transform: true})) // New!
create(@Body() messageCreateDto: MessageCreateDto) {
return this.messagesService.createMessage(messageCreateDto)
}
...
export class MessageCreateDto {
@IsString() // New!
@Transform((params: TransformFnParams<string>) => {
return textToCode(params.value)
}) // New!
message: string
}
...
export interface TransformFnParams<T> {
value: T;
key: string;
obj: any;
type: TransformationType;
options: ClassTransformOptions;
}
textToCode 함수의 return '.-.-.- .---.-. ..-...- -.-.' 그대로 변환해준다.
이제 IsString()을 걷어내고 Custom validator를 붙여보자
GitHub - typestack/class-validator: Decorator-based property validation for classes.
Decorator-based property validation for classes. Contribute to typestack/class-validator development by creating an account on GitHub.
github.com
...
// New!
@ValidatorConstraint()
export class CheckValidText implements ValidatorConstraintInterface {
validate(text: string) {
return this.isValid(text)
}
private isValid(text: string): boolean {
return ...
}
}
...
export class MessageCreateDto {
@IsString()
@Validate(CheckValidText, {
message: 'This message cannot be converted to code.',
}) // New!
@Transform((params: TransformFnParams<string>) => {
return textToCode(params.value)
})
message: string
}
문제가 발생했다.
ValidationPipe transforms before validating · Issue #2856 · nestjs/nest
Bug Report Current behavior If a property from a DTO has transformation and validation decorators the transformation decorator will be applied before the validation ones. Since the validators work ...
github.com
nestjs 개발자의 답변: 의도된 동작이다.
동일한 ValidationPipe 안에서는 @Transform 데코레이터가 반드시 먼저 실행된다고 한다.
Transform을 성공적으로 마친 뒤 Validation하는 것이 자연스러운 흐름이긴 할 것 같다.
그럼 input text의 유효성을 먼저 검사한 뒤 암호화해야하는 내 경우는 어떡하지...?..?
...
export class CodeTransformPipe // New!
implements PipeTransform<MessageCreateDto, MessageCreateDto>
{
transform(value: MessageCreateDto) {
return ...
}
...
}
...
...
@Post()
@UsePipes(new CodeTransformPipe()) // New!
create(@Body() messageCreateDto: MessageCreateDto) {
return this.messagesService.createMessage(messageCreateDto)
}
...
...
export class MessageCreateDto {
@IsString()
@Validate(CheckValidText, {
message: 'This message cannot be converted to code.',
})
// @Transform() 데코레이터 제거
message: string
}
...
문제 2개가 동시에 해결되었다.
아싸
[Question] How control global and non-global Pipe order? · Issue #3108 · nestjs/nest
Question How control global and non-global Pipeline order? At my application I have global ValidationPipe added with useGlobalPipes and custom ParseDatePipe added with Query decorator. I want run P...
github.com
[Docker] Docker 자주 쓰는 명령어 정리 (0) | 2024.07.14 |
---|---|
[Docker] Docker 설치, 개념 정리 (1) | 2024.07.14 |
[MySQL] SQL Query 문법과 실제 실행 순서 (0) | 2024.02.26 |
[MySQL] SQL 커맨드 분류: DDL, DML, DQL, DCL, TCL (0) | 2023.12.25 |
비밀번호 없이 SSH 접속? pem 키로 간편화해보자 (1) | 2023.11.13 |