NestJS || Guide

Alpha, Orderly·2023년 9월 18일
0

nestJS

목록 보기
2/8

파일 생성하기

모듈

  • nest generate module 이름
  • 자동으로 src폴더에 Module을 이름 끝에 붙혀 생성해줌

컨트롤러

  • nest generate controller 모듈이름/컨트롤러이름 --flat
  • flat을 붙혀 추가 폴더가 생기지 않게 함.
  • 자동으로 모듈에 controller가 추가됨.

URI WILDCARD

  • 특정 uri를 지정하고 싶지 않을때 사용한다.
@Get('/:id')
example(@Param('id') id: string)
  • :를 사용해 지정할수 있다.
  • @Param 데코레이터를 이용해 가져온다.

Post 에서 Body 및 기타 가져오기

  • @Body를 사용한다.
@Post()
example(@Body() body: any)
  • 이 외 헤더, 쿼리스트링또한 @Header, @Query를 사용
    헤더와 쿼리스트링을 가져올수 있다.

에러 핸들링

  • NotFoundException 을 @nestjs/core에서 import
  • 에러 상황에 대해 throw 한다.
if(!message) 
{
    throw new NotFoundException('message not found');
}

Injectable

  • nestJS의 특징
  • spring에서 쓰이는 제어 역전 개념

DI Container

  1. 클래스를 찾아 각각의 dependency를 찾는다.
  2. dependency에 해당하는 클래스의 객체를 생성하고 제공한다.

사용법

  1. dependency로 사용되던 문법을 constructor 로 옮긴다.
    messagesRepo: MessagesRepository;

    constructor() {
        this.messagesRepo = new MessagesRepository();
    }
// Service는 Repository가 있어야 ( Dependency ) 사용가능

에서

    messagesRepo: MessagesRepository;

    constructor(messagesRepo: MessagesRepository) {
        this.messagesRepo = messagesRepo;
    }

와 같이

  1. Repository 가 DI Container에서 생성될수 있도록 Decorator를 추가한다.
@Injectable()
export class MessagesRepository
  1. 모듈에 provider 형식으로 Repository를 추가해 DI Container에 생성되도록 지정한다.
@Module({
  controllers: [MessagesController],
  providers: [MessagesService, MessagesRepository]
})

constructor(private powerService: PowerService)
와 같이 사용 가능.

  1. 결과적으로 DI Container에서 Repository를 생성하고 Service단에 자동으로 Injection 해 사용할수 있게 된다.

여러 모듈 사용하기

  • main.ts 에서는 한개의 모듈만을 가져온다.
async function bootstrap() {
  const app = await NestFactory.create(ComputerModule);
  await app.listen(3000);
}
bootstrap();
  • 여러개의 모듈을 사용하려면 어떻게 해야 할까?

Computer 모듈과 Power모듈이 있다고 가정, 둘다 사용가능해야 한다.

  1. Power 모듈에 대해 다른 모듈에서 사용 가능할 클래스를 export로 지정한다.
@Module({
  providers: [PowerService],
  exports: [PowerService]
})
export class PowerModule {}
  1. Computer 모듈에서 Power모듈을 import로 지정한다.
@Module({
  providers: [ComputerService],
  imports: [PowerModule]
})
export class ComputerModule {}
  1. Computer 모듈의 클래스들에서 Power 모듈의 클래스를 Injection 받아 사용할수 있게 된다.
@Injectable()
export class ComputerService {
    constructor(private powerService: PowerService) {}
}

Exception Handling

  • Service에서 비즈니스 로직을 처리하다 문제가 생기면 Exception 을 throw 할수 있다.
    • Ex. NotFoundException
  • 단, 위와 같이 http에서만 사용되는 Exception 을 사용시 웹소켓, GRPC 등을 사용하는 컨트롤러는 제대로 이를 사용하지 못할수 있다.

Transform 데코레이터

  • plainToInstance를 통해 클래스로 변환시 특정 값을 변환해서 받아올수 있다.
    @Transform(({obj}) => obj.user.id)
    @Expose()
    userId: number;
  • user의 id에서 id만 가져와 저장하도록 한다.

미들웨어 만들기

export class CurrentUserMiddleware implements NestMiddleware {
    async use(req: Request, res: Response, next: NextFunction) {

    }
}
  • 안에서 작동 후 next() 를 호출한다.
profile
만능 컴덕후 겸 번지 팬

0개의 댓글