NestJS Midlleware

Outclass·2022년 7월 13일
0

NestJS+GraphQL+TypeORM 

목록 보기
5/16

express에도 많이 보았던 것인데, nest에도 자주 등장한다. 오늘은 미들웨어에 대해 한번 정리해보자

미들웨어 Middleware

Middleware is a function which is called before the route handler. Middleware functions have access to the request and response objects, and the next() middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next. - 공식문서

미들웨어는 route handler이전에 호출되는 함수이다. 미들웨어 함수는 request, response 객체에 접근할 수 있고 어플리케이션 응답-요청 싸이클의 next() 함수에 접근할 수 있다. (...) - 발번역

  • request, response, next는 express에서 호출한다
  • 미들웨어는 함수로 만들 수 있지만, class로도 만들 수 있다
  • next()로 다음단계로 넘어간다.
  • nest에서 미들웨어는 전역으로 적용하거나, 특정 모듈에만 지정할 수도 있다.
import { Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
import { UsersService } from 'src/users/users.service';
import { JwtService } from './jwt.service';

//미들웨어를 클래스로 만들 때(dependency injection을 사용하려면 class로)
//NestMiddleware는 extends가 아닌 implements로
//dependency injection을 사용하려면 @Injectable()이 필요하다
@Injectable()
export class AnyMiddleware implements NestMiddleware {
  constructor(
  	//dependency injection
    private readonly anyService: JwtService,
  ) {}

  //express에서 불러온 친구들
  async anyFunction(req: Request, res: Response, next: NextFunction) {
      try {
      	...
      } catch (error) {
      	...
      }
    }
    //다음단계로
    next();
  }
}

//미들웨어를 함수로 만들 때
export function anyMiddleware(req: Request, res: Response, next: NextFunction) {
	...
	next();
}
//app.module.ts에서 적용
//NestModule을 Implements해야한다
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AnyMiddleware).forRoutes({
      path: '/graphql', //경로지정이 가능하다
      method: RequestMethod.ALL, //허용할 메소드 지정이 가능하다
    });
  }
}

//main.ts에서 미들웨어 적용
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  //미들웨서 사용시 함수로만 사용 가능(class는 X)
  app.use(anyMiddleware);
  await app.listen(3000);
}
bootstrap();
  • class 미들웨어의 경우 main.ts에서는 적용할 수 없음. app.module.ts에서 적용시에는 function과 class모두 적용 가능
  • main.ts에서 적용시에는 미들웨어가 전역으로 적용됨
  • app.module.ts에서 적용시에는 특정 경로에 미들웨어를 지정할 수 있으며, 메소드 지정도 가능함(ALL, GET, POST...)
profile
When you stop having big dreams that’s when you’ve died, despite not being buried yet.

1개의 댓글

comment-user-thumbnail
2024년 2월 27일

제목 midlle -> middle 오타가 있습니다

답글 달기