context

Tags
 

Apollo Server Context

A request context is available for each request. When context is defined as a function, it will be called on each request and will receive an object containing a req property, which represents the request itself.
 
notion image
 

NestJS 연동

app.module.ts - 미들웨어 설정

notion image

미들웨어 코드

JwtMiddleware 라는 미들웨어를 만들었다.
요청이 오면 http headers에서 x-jwt라는 항목을 찾고, 토큰이 있다면 해당 유저를 db에서 찾아서 req에 넣어주도록 구현했다.
이로써 http 요청이 들어오면 미들웨어에서 잡혀서 req[’user’]에 유저 정보를 담게 된다.
notion image

app.module.ts - graphql context 설정

notion image
app.module.ts에서 graphql 설정을 할 때 context 설정을 했다.
이로써 req에 있는 req[’user’] 항목이 context에 공유된다.
graphql context에 있는 항목들은 모든 graphql resolvers 에서 참조할 수 있다.

graphql resolver 에서 context 값 확인

notion image
resolver에서 me라는 쿼리를 만들고, 콘텍스트를 가져와서 출력해본다.
그러면 다음과 같이 context에서 user가 담겨있음을 확인할 수 있다.
notion image