Graphql 阿波罗订阅与盖茨比设置

Graphql 阿波罗订阅与盖茨比设置,graphql,gatsby,apollo,Graphql,Gatsby,Apollo,下面是我与阿波罗合作的盖茨比SSR的设置,供那些寻找如何设置它们的解决方案的人使用。希望它能帮助那些在网上寻找解决办法的人,让他们知道如何与阿波罗一起建立盖茨比 学分:[ 我现在不确定我的onError变量是否正确放置。我将查找它 尽管如此,使用gatsby客户端路由订阅可以很好地使用此设置client.js//导入到ApolloProvider中 import ApolloClient from 'apollo-client' // import * as ws from 'ws' // im

下面是我与阿波罗合作的盖茨比SSR的设置,供那些寻找如何设置它们的解决方案的人使用。希望它能帮助那些在网上寻找解决办法的人,让他们知道如何与阿波罗一起建立盖茨比

学分:[

我现在不确定我的onError变量是否正确放置。我将查找它


尽管如此,使用gatsby客户端路由订阅可以很好地使用此设置

client.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(),
})
graphql/subscriptions.js

import gql from 'graphql-tag'

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

谢谢你,伙计,这很有效!这一次的斗争是真实的!!!