728x90

- 설치

class validator (검증) / class-transformer (변환) 설치, 둘다 설치해줘야함

yarn add class-validator class-transformer

- dto 생성

export class CretePostDto {
  @IsString()
  title: string;

  @IsString()
  content: string;
}

 

- dto 적용

  @Post()
  @UseGuards(AccessTokenGuard)
  postPosts(
    @User('id') usersId: number,
    @Body() body: CretePostDto,
    // @Body('title') title: string,
    // @Body('content') content: string,
  ) {
    return this.postsService.createPost(usersId, body);
  }

 

- main.ts에 글로벌 파이프 설정

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3000);
}
bootstrap();

 

- Validation decorators

- fastcampus 강의 내용

https://springdream0406.tistory.com/181

 

 

- 공식 문서

https://github.com/typestack/class-validator?tab=readme-ov-file#validation-decorators

 

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


- 에러 메시지 변경하기

export class CretePostDto {
  @IsString({
    message: 'title은 string 타입을 입력 해줘야합니다.',
  })
  title: string;

  @IsString({
    message: 'content는 string 타입을 입력 해줘야합니다.',
  })
  content: string;
}

option으로 원하는 반환 메시지 설정


- extends 하기

  @IsString({
    message: 'title은 string 타입을 입력 해줘야합니다.',
  })
  @Column()
  title: string;

  @IsString({
    message: 'content는 string 타입을 입력 해줘야합니다.',
  })
  @Column()
  content: string;

validator를 extends 할 class (entity)에 적용하기

 

// Pick, Omit, Partial -> Type 반환
// PickType, OmitType, PartialType -> 값을 반환
export class CretePostDto extends PickType(PostsModel, ['title', 'content']) {}

DTO를 PickType으로 extends 하기


- optional 설정

export class UpdatePostDto extends PartialType(PostsModel) {
  @IsString()
  @IsOptional()
  title?: string;

  @IsString()
  @IsOptional()
  content?: string;
}

예제는 이렇게 작성해줬지만 사실 @IsOptional()을 보여주기 위한 중복정의라

export class UpdatePostDto extends PartialType(PostsModel) {}

이렇게 작성해도 상관없음.

  @Patch(':id')
  patchPost(
    @Param('id', ParseIntPipe) id: number,
    @Body() body: UpdatePostDto,
    // @Body('title') title?: string,
    // @Body('content') content?: string,
  ) {
    return this.postsService.updatePost(id, body);
  }

- Length / Email Annotation

  @Column({
    length: 20,
    unique: true,
  })
  @IsString()
  @Length(1, 20, {
    message: '닉네임은 1~20자 사이로 입력해주세요.',
  })
  nickname: string;

  @Column({
    unique: true,
  })
  @IsString()
  @IsEmail()
  email: string;

  @Column()
  @IsString()
  @Length(3, 8)
  password: string;

 

export declare function Length(min: number, max?: number, validationOptions?: ValidationOptions): PropertyDecorator;

- Validation Message 일반화

- length-validation.message.ts

export const lengthValidationMessage = (args: ValidationArguments) => {
  /**
   * ValidationArguments의 프로퍼티들
   *
   * 1) value > 검증 되고 있는 값 (입력된 값)
   * 2) constraints -> 파라미터에 입력된 제한 사항들
   *    args.constraints[0] -> 1 (이 경우 @Length()의 1)
   *    args.constraints[1] -> 20 (이 경우 @Length()의 20)
   * 3) targetName -> 검증하고 있는 클래스의 이름
   * 4) object -> 검증하고 있는 객체
   * 5) property -> 검증 되고 있는 객체의 프로퍼티 이름 (이 경우는 nickname)
   */
  // contraints가 2개 일때 ex) length()
  if (args.constraints.length === 2) {
    return `${args.property}은 ${args.constraints[0]}~${args.constraints[1]}글자를 입력 해주세요!`;
  }
  //  contraints가 없거나 한개 뭐 그런 때 ex) IsString(), MinLenth()
  else {
    return `${args.property}는 최소 ${args.constraints[0]}글자를 입력 해주세요!`;
  }
};

주석은 UsersModel entity의 nickname을 기준으로 작성됨.

 

- string-validation.message.ts

export const stringValidationMessage = (args: ValidationArguments) => {
  return `${args.property}에 String을 입력해주세요!`;
};

 

- entity

  @Column({
    // 1) 길이가 20을 넘지 않을 것
    length: 20,
    // 2) 유일무이한 값이 될 것
    unique: true,
  })
  @IsString({ message: stringValidationMessage })
  @Length(1, 20, {
    message: lengthValidationMessage,
  })
  nickname: string;

  @Column({
    unique: true,
  })
  // 1) 유일무이한 값이 될것
  @IsString({ message: stringValidationMessage })
  @IsEmail(
    {},
    {
      message: emailValidationMessage,
    },
  )
  email: string;

  @Column()
  @IsString({ message: stringValidationMessage })
  @Length(3, 8, {
    message: lengthValidationMessage,
  })
  password: string;

message에 함수를 넣을 수 있고, 공통 반환 될 함수를 따로 만들어서 집어넣음.

 

 

 

https://www.inflearn.com/course/lecture?courseSlug=nestjs-%EB%B0%B1%EC%97%94%EB%93%9C-%EC%99%84%EC%A0%84%EC%A0%95%EB%B3%B5-%EB%A7%88%EC%8A%A4%ED%84%B0-%ED%81%B4%EB%9E%98%EC%8A%A4-1&unitId=184243&subtitleLanguage=ko&tab=curriculum

 

학습 페이지

 

www.inflearn.com

 

728x90

'코딩 > Nest.js' 카테고리의 다른 글

환경변수 ConfigModule (+ TypeORM DB 설정)  (0) 2024.10.21
Class Transformer  (0) 2024.10.21
커스텀 데코레이터  (1) 2024.10.20
Guard 기본적 느낌  (0) 2024.10.20
Header에 id:password  (0) 2024.10.18

+ Recent posts