【问题标题】:Apollo Subscription with Gatsby Setup带有 Gatsby 设置的 Apollo 订阅
【发布时间】:2020-06-20 23:58:10
【问题描述】:

下面是我使用 Apollo 设置的 Gatsby SSR,供那些正在寻找如何设置它们的解决方案的人使用。希望它可以帮助那些在网上寻找如何使用 Apollo 设置 Gatsby 的解决方案

致谢:[https://github.com/apollographql/subscriptions-transport-ws/issues/333]

目前我不确定我的 onError 变量是否放置正确。我去查一下

尽管如此,使用 gatsby 客户端路由的订阅在此设置下运行良好

【问题讨论】:

    标签: graphql gatsby apollo


    【解决方案1】:

    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 }
    

    【讨论】:

    • 谢谢伙计,这行得通!这场斗争是真实的!!!
    猜你喜欢
    • 2020-10-18
    • 2020-08-17
    • 2020-08-31
    • 2019-01-18
    • 2017-09-19
    • 2019-01-27
    • 2020-10-08
    • 2019-12-05
    • 2020-04-23
    相关资源
    最近更新 更多