일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- 체인의정석
- SBT표준
- 머신러닝기초
- 오블완
- ethers
- 러스트 기초 학습
- 컨트렉트 배포 자동화
- 스마트컨트렉트 함수이름 중복 호출
- Vue
- 티스토리챌린지
- 러스트기초
- 계정추상화
- ambiguous function description
- erc4337 contract
- ethers type
- Vue.js
- rust 기초
- 스마트컨트렉트 예약어 함수이름 중복
- ethers v6
- ethers typescript
- 스마트 컨트렉트 함수이름 중복
- 스마트컨트렉트테스트
- multicall
- 러스트 기초
- git rebase
- 컨트렉트 동일한 함수이름 호출
- ethers websocket
- vue기초
- chainlink 설명
- erc4337
- Today
- Total
체인의정석
Nest.js) Validation 하기 , validation Pipe 사용하기 본문
Nest.js에서 여태까지 class validator를 사용하기 위하여
constructor를 사용하여 모든 클래스를 생성한 하여 valditaion을 진행하였다.
하지만 validation Pipe를 사용하면 이러한 과정을 모듈로 깔끔하게 할 수 있다는 사실을 알게 되어서 적용해 보려고 한다.
이걸 잘 사용하면 중복된 코드를 대량으로 줄일 수 있을것 같다.
우선 constructor 부분이 삭제가 되면서 1차적으로 코드가 깔끔해지며, 2차적으로 공통 모듈로서 validation하는 부분을 설정해 줌으로서 더 클린하고 유지보수가 쉬운 코드가 나오게 될 것으로 기대하고 리팩토링을 진행하도록 하겠다.
먼저, validation Pipe의 경우 nest.js 공식 document에 있기 때문에 이를 정독해보도록 하겠다.
https://docs.nestjs.com/techniques/validation
Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac
docs.nestjs.com
위와 같은 링크에서 공부가 가능하다.
The ValidationPipe makes use of the powerful class-validator package and its declarative validation decorators. The ValidationPipe provides a convenient approach to enforce validation rules for all incoming client payloads, where the specific rules are declared with simple annotations in local class/DTO declarations in each module.
상단의 문구를 보니 제대로 찾아온 것이 맞는것 같다.
Using the built-in ValidationPipe#
To begin using it, we first install the required dependency.
먼저 모듈을 설치부터 해주어야 한다.
$ npm i --save class-validator class-transformer
이 패키지는 nestjs/common 에서 export 된다고 한다. 기본적으로 제공하는 확장 기능인셈이다.
Because this pipe uses the class-validator and class-transformer libraries, there are many options available. You configure these settings via a configuration object passed to the pipe. Following are the built-in options:
옵션이 많다고 하는데 아래에 옵션을 한번 정리한걸 거져와 보았다.
export interface ValidationPipeOptions extends ValidatorOptions {
transform?: boolean;
disableErrorMessages?: boolean;
exceptionFactory?: (errors: ValidationError[]) => any;
}
이런식으로 하면 validation에 대한 설정을 통해서 실제 validate를 할 수 있는것 같다.
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
bootstrap();
먼저 위의 코드와 같이 모듈을 처음에 가져와서 설정해 주는 과정이 필요한것 같다. 이 부분은 원래 작성해두었던 main.ts 코드에 추가를 하였다. 이때 따로 Npm install을 안해도
import { ValidationPipe } from '@nestjs/common';
위에 이렇게 import를 해오면 사용이 가능하다.
사용할 기능은 아래와 같다.
transform: true,
whitelist: true,
forbidNonWhitelisted: true,
validationError: {
target: false,
},
먼저 transform의 경우
auto-transformation을 가능하게 해준다. DTO에서 정의된 부분을 자동으로 적용가능하게 하려면 해당 부분을 true로 만들어 주어야 한다.
특정 부분에만 제한을 걸기 위해서는 이런식으로 코드를 수정해주면 된다.
@Post()
@UsePipes(new ValidationPipe({ transform: true }))
async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}
이러한 작업을 글로벌하게 실행하려면 아래와 같은 설정값이 필요하다.
app.useGlobalPipes(
new ValidationPipe({
transform: true,
}),
);
'개발 > backend' 카테고리의 다른 글
Nest.js 수정사항 총 정리 02 ) 예외처리 패턴 - Invalid Input 리팩토링 (0) | 2021.12.07 |
---|---|
Nest.js 수정사항 총 정리 01 ) 예외처리 패턴 - Internal Server Error 리팩토링 (0) | 2021.12.07 |
코드리뷰 정리) 확장성있는 URL 만들기 (0) | 2021.12.03 |
typescript 모듈 설정 에러 1.default) is not a function (0) | 2021.11.23 |
Typescript 3 항 연산자로 조건문 바꾸기 (0) | 2021.11.22 |