subscription setup(grahpql-ws, webSoket)

김종민·2022년 10월 6일
0

Nuber-Client

목록 보기
16/21

들어가기
주문이 했을때, Owner가 주문을 실시간으로 바로
받을 수 있고,
Owner가 Order상태를 pending에서 cooking, cooked등으로
editOrder할 수 있게
subscription을 setup한다.


1.src/apollo.ts

npm i graphql-ws

import {
  ApolloClient,
  InMemoryCache,
  ApolloProvider,
  gql,
  makeVar,
  createHttpLink,
  split,
} from '@apollo/client'
import { LOCALSTORAGE_TOKEN } from './constant'
import { setContext } from '@apollo/client/link/context'
import { createClient } from 'graphql-ws'
import { GraphQLWsLink } from '@apollo/client/link/subscriptions'
import { getMainDefinition } from '@apollo/client/utilities'

///createClient, setContext, GraphQLWsLink등이
///어디서 import되는지 확인한다.

const token = localStorage.getItem(LOCALSTORAGE_TOKEN)
export const isLoggedInVar = makeVar(Boolean(token))
export const authTokenVar = makeVar(token)

export const wsLink = new GraphQLWsLink(
  createClient({
    url: 'ws://localhost:4000/graphql',
    connectionParams: {
      'x-jwt': authTokenVar() || '',
    },
  })
)
///wsLink를 만드는데, connectionParams에
///'x-jwt'에 token을 넣어준다.
///url을 uri와 햇갈리면 안됨.
///url을 잘 확인한다.
///connectionParams는 ws연결시, server에 req를 할때마다,
///connectionParams에 token을 넣어서 req를 보낸다.

const httpLink = createHttpLink({
  uri: 'http://localhost:4000/graphql',
})
///ws통신이 아닌 http통신일 경우 사용될 httpLink를 만든다.

const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      ...headers,
      'x-jwt': authTokenVar() || '',
    },
  }
})
///http통신일 경우, setContext를 이용해서,
///headers에 authTokenVar를 이용해 token을 같이 보내준다.

const splitLink = split(
  ({ query }) => {
    const definition = getMainDefinition(query)
    return (
      definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
    )
  },
  wsLink,
  authLink.concat(httpLink)
)
///apollo공식문서에 있는 그대로임.
///wsLink과 httpLink를 사용해야 되는 경우를
///자동적으로 나눠지게 설정해놓음.

export const client = new ApolloClient({
  link: splitLink,  
  ///link에 위에서 만든 splitLink를 넣어줌.
  
  cache: new InMemoryCache({
    typePolicies: {
      Query: {
        fields: {
          isLoggedIn: {
            read() {
              return isLoggedInVar()
            },
          },
          token: {
            read() {
              return authTokenVar
            },
          },
        },
      },
    },
  }),
})

apollo subscription에서
graphql-ws만 이제 사용되게 할 예정이라고 하니,
이 설정을 유심히 집중해서 볼것!!!
Client부분에서 subscription을 사용하기 위해서는
반드시 wsLink로 설정해 주어야 함..!!!

profile
코딩하는초딩쌤

0개의 댓글