Подписка на Apollo с настройкой Gatsby - PullRequest
0 голосов
/ 09 марта 2020

ниже - мои настройки Gatsby SSR с Apollo для тех, кто ищет решение о том, как их настроить. Надеюсь, это поможет тем, кто ищет в Интернете решение о том, как настроить Gatsby с помощью Apollo

Кредиты: [https://github.com/apollographql/subscriptions-transport-ws/issues/333]

В настоящий момент я не уверен, Моя переменная onError размещена правильно. Я посмотрю это

Тем не менее, подписка с клиентскими маршрутами gatsby работает нормально с этой настройкой

1 Ответ

0 голосов
/ 09 марта 2020

клиент. js // для импорта в ApolloProvider

import ApolloClient from 'apollo-client'
// import * as ws from 'ws'
// import { createHttpLink } from 'apollo-link-http'
import { split } from 'apollo-link'
// import { setContext } from 'apollo-link-context'
import { onError } from 'apollo-link-error'
import { HttpLink } from 'apollo-link-http'
import { WebSocketLink } from 'apollo-link-ws'
// import fetch from 'isomorphic-fetch' // Comment out this line results in an error ...
import 'isomorphic-fetch'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { getMainDefinition } from 'apollo-utilities'

const HTTP_URI = `http://localhost:4000/graphql`
const WS_URI = `ws://localhost:4000/graphql`

const httplink = new HttpLink({
  uri: HTTP_URI,
  // credentials: 'same-origin',
  // fetch,
})

const wsLink = process.browser
  ? new WebSocketLink({
      // if you instantiate in the server, the error will be thrown
      uri: WS_URI,
      options: {
        reconnect: true,
      },
    })
  : null

const errorLink = onError(({ networkError, graphQLErrors }) => {
  if (graphQLErrors) {
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
      )
    )
  }
  if (networkError) console.log(`[Network error]: ${networkError}`)
})

const link = process.browser
  ? split(
      //only create the split in the browser
      // split based on operation type
      ({ query }) => {
        const { kind, operation } = getMainDefinition(query)
        return kind === 'OperationDefinition' && operation === 'subscription'
      },
      wsLink,
      httplink,
      errorLink
    )
  : httplink

export const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
})

график / подписки. js

import gql from 'graphql-tag'

const BOOK_ADDED_SUBSCRIPTION = gql`
  subscription {
    bookAdded {
      _id
      title
      author
    }
  }
`
export { BOOK_ADDED_SUBSCRIPTION }
...