스팀펑크의 완판의 기쁨을 뒤로하고, 또 개발에 매진을 해봅니다.!!
만들어야 할 것들이 산더미라서요...!! ㅎㅎ
가봅니다!
Nestjs에서 Middleward란 Express의 Middleware와 동일하게 작동하는데요,
httprequest가 서버로 전송되면, Middleware에서 한번쯤 보안 및 이런 저런 일들을 처리하고 원래 목적지로 넘겨주는 용도로 주로 사용됩니다.
보안이 보통 제일 큰 부분일텐데요, JWT를 사용하는 경우에도 Middleware에서 확인하면 아주 간단히 처리가 가능하게 됩니다.
Middleware Class 만들기
- Middleware를 Class나 function 둘다 만드는 것이 가능하지만, nestjs에서는 다른 서비스를 inject 하여 사용하는 것이 쉽다보니, inject를 위해서 class로 만들어 주는 것이 조금더 활용성 측면에서 좋은 것 같다는 생각이 듭니다.
- Middleware를 만들기 위해서는 NestMiddleware를 implements 하시면 됩니다.
- 그리고 use(request, response, NextFunction) 를 정의 해주면 됩니다.
- 마지막으로 다시 원래 목적지로 next() 처리를 해주는 방식으로 사용하면 됩니다.
export class JwtMiddleware implements NestMiddleware {
constructor(private readonly service: Service들...) {}
async use(req: Request, res: Response, next: NextFunction) {
console.log(req.headers);
// 이러쿵 저러쿵 보안도 체크하고 admin 여부 체크도 해보고 마구마구 처리 후
req['result'] = 내용내용;
next();
}
}
app.module 에 적용
- 위와 같이 middleware를 만들고 나면 이를 적용해주기 위해서 app.module에 코드를 작성합니다.
- 아래와 같이 NestModule를 implements 합니다.
- 그리고 configure를 정의해주면 됩니다.
- consumer에서 middleware가 작동하는 route를 따로 설정이 가능한데요, 아래의 주석과 샘플처럼 하면 원하는 대로 middleware 작동범위를 설정 할 수 있습니다.
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(JwtMiddleware)
.forRoutes({ path: '/graphql', method: RequestMethod.POST });
// 모든 요청에 적용하려면 아래와 같이 적용
// consumer
// .apply(JwtMiddleware)
// .forRoutes({ path: '*', method: RequestMethod.ALL });
// 특정 route만 예외로 하고 싶은 경우 exclude를 사용하면 된다.
// consumer
// .apply(JwtMiddleware)
// .exclude({ path: '/graphql', method: RequestMethod.ALL });
}
}
그리고 테스트를 해보면 설정된 route로 httprequest가 들어 올 때 마다!! middleware 강제호출!!! 잘되네요!!
오... 완벽히 이해했어!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
오호~!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
@happyberrysboy transfered 50 KRWP to @krwp.burn. voting percent : 100.00%, voting power : 18.56%, steem power : 1940831.44, STU KRW : 1200.
@happyberrysboy staking status : 13840 KRWP
@happyberrysboy limit for KRWP voting service : 13.84 KRWP (rate : 0.001)
What you sent : 50 KRWP (Voting Percent over 100 %)
Refund balance : 46.782 KRWP [62564838 - af534832b32f8bb7b1c7ce962769841977668d5c]
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit