[Nest.JS] http 요청/응답 처리 단계

jm4293·2024년 2월 13일
0

http 요청 순서

  1. 클라이언트가 요청
  2. 가드
    • 인증/인가
  3. 인터셉터
  4. 파이프
    • 요청에 대한 유효성 검증
  5. 컨트롤러
    • 라우팅
  6. 서비스
    • 비즈니스
  7. 리포지토리
    • 데이터 저장
  8. 클라이언트로 응답

Entity

  • entity는 데이터베이스의 테이블과 일치하는 객체입니다. entity는 다음과 같은 속성을 가질 수 있습니다.
// user.entity.ts

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  username: string;

  @Column()
  password: string;
}

DTO

  • DTO는 데이터를 전송하는 데 사용되는 객체입니다. DTO는 다음과 같은 속성을 가질 수 있습니다.
// user.dto.ts
export class UserDTO {
  username: string;
  password: string;
}
  • NestJS는 entity와 DTO를 사용하여 데이터를 저장하고 처리합니다. entity는 데이터베이스의 테이블과 일치하는 객체입니다. DTO는 데이터를 전송하는 데 사용되는 객체입니다.

DTO validataion

  • 설치: npm i class-validator class-transformer
  • 프론트엔드에서 validation 처리를 하면 되지만 백엔드에서도 validation 처리를 해서 이상한 형식의 데이터가 데이터베이스에 저장되는 것을 막을 수 있다.
// *.dto.ts
import { IsInt, IsString } from 'class-validator';

export class CreateProductDto {
  @IsString()
  name: string;

  @IsString()
  description: string;

  @IsInt()
  price: number;
}
// *.contoroller.ts
import { Controller, Post, ValidationPipe, UsePipes } from '@nestjs/common';
@Post()
@UsePipes(ValidationPipe)
create(@Body() input: any): boolean {
  return true
}
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(8080);
}
bootstrap();
  • @UsePipes(ValidationPipe)를 컨트롤러에 매번 데코레이터할 필요없이 main.ts 에서 전역적으로 선언할 수 있다.
profile
무언가를 만드는 것을 좋아합니다

0개의 댓글

관련 채용 정보