1. 프로젝트 생성과 구성
1) 프로젝트 생성
$ yarn add @nestjs/cli
$ nest new 프로젝트명 (yarn선택)
2) Nest 기본구성
- 모듈
$ nest g mo module-name
-
@Module({ controllers: [CatsController], providers: [CatsService], exports: [CatsService], }) export class CatsModule {}
- 컨트롤러
$ nest g co controller-name
- 서비스
$ nest g service service-name
3) Nest 응용구성 - 미들웨어
$ nest g middleware middleware-name
-
export class AppModule {} => export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer.apply(MiddlewareNameMiddleware).forRoutes('*'); } }
- 필터
$ nest g filter filter-name
-
const app = await NestFactory.create(AppModule); app.useGlobalFilters(new HttpExceptionFilter()); await app.listen(3000);
-
@Get() @UseFilters(HttpExceptionFilter) getAllCat() { throw new HttpException({ koko: 'fail' }, HttpStatus.FORBIDDEN); return 'all cat'; }
- 파이프
$ nest g pipe pipe-name
-
@Injectable() export class PostiveIntPipe implements PipeTransform { transform(value: any, metadata: ArgumentMetadata) { if (value < 0) { throw new HttpException(); } return value; } }
-
@Get(':id') getOneCat(@Param('id', ParseIntPipe) id: number) { return 'one cat'; }
- 인터셉터(AOP)
$ nest g interceptor interceptor-name
-
@Injectable() export class InterceptorNameInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { return next.handle().pipe(map((data) => ({ success: true, data }))); } }
-
@Get('test2') @UseInterceptors(InterceptorNameInterceptor) getHello2(@Param() param: { id: string }): string { return this.catsService.getHello(); }
- 라이프사이클
- 글로벌 -> 개별
- request -> middleware -> guard -> interceptor -> pipe -> controller
4) 실행
$ yarn start
$ yarn start:dev