본문 바로가기

node.js

Nest.js - validation

클래스 유효성 검사기

(TypeScript가 필요하며 앱이 바닐라 JavaScript를 사용하여 작성된 경우에는 사용할 수 없습니다.)

Nest는 클래스 유효성 검사기 라이브러리와 잘 작동합니다. 이 강력한 라이브러리를 사용하면 데코레이터 기반 유효성 검사를 사용할 수 있습니다. 데코레이터 기반 유효성 검사는 처리된 속성에 액세스할 수 있으므로 특히 Nest의 Pipe 기능 과 결합할 때 매우 강력 합니다. metatype시작하기 전에 필요한 패키지를 설치해야 합니다.

 

$ npm i --save class-validator class-transformer

이것들이 설치되면 CreateCatDto클래스에 몇 가지 데코레이터를 추가할 수 있습니다. 여기에서 이 기술의 중요한 이점을 볼 수 있습니다. CreateCatDto클래스는 Post 본문 개체에 대한 단일 소스로 유지됩니다(별도의 유효성 검사 클래스를 만들 필요가 없음).  https://github.com/typestack/class-validator#usage -> 사용법에 대한 자세한 설명 

 

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
import { Document, SchemaOptions } from 'mongoose';

const options: SchemaOptions = {
  timestamps: true,
};

@Schema(options)
export class Cat extends Document {
  @Prop({
    required: true,
    unique: true,
  })
  @IsEmail()
  @IsNotEmpty()
  email: string;

  @Prop({
    required: true,
  })
  @IsString()
  @IsNotEmpty()
  name: string;

  @Prop({
    required: true,
  })
  @IsString()
  @IsNotEmpty()
  password: string;

  @Prop()
  @IsString()
  imgUrl: string;
}

export const CatSchema = SchemaFactory.createForClass(Cat);

validation을 이용해   Schema Cat(JPA의 entity) 설계 

 

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './common/exceptions/http-exception.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalFilters(new HttpExceptionFilter());
  const PORT = process.env.PORT;
  await app.listen(PORT);
}

bootstrap();

  app.useGlobalPipes(new ValidationPipe()); 를 통해 validation 등록

'node.js' 카테고리의 다른 글

node.js - 이벤트 루프  (0) 2023.02.18
Nest.Js - mongoDB 연결  (0) 2022.08.29
Nest.js - 인터셉터  (0) 2022.08.20
Nest.js - pipes  (0) 2022.08.20
Nest.js - 예외 필터  (0) 2022.08.20