首页 > 解决方案 > 未处理的 GraphQL 订阅错误 [错误:无法解构“未定义”的属性“数据”,因为它未定义。]

问题描述

我尝试subscribeToMore在 react-native 中使用我的 graphql 查询,但出现以下问题:

ERROR: Unhandled GraphQL subscription error [Error: Cannot destructure property 'data' of 'undefined' as it is undefined.]

我的订阅看起来像

// MESSAGE_SUBSCRIPTION
import { gql } from '@apollo/client'

export const TOPIC_MESSAGE_SUBSCRIPTION = gql`
  subscription MessageSubscription($data: SubscriptionInput!) {
    messageSubscription(data: $data) {
      _id
      text
    }
  }
`

我的组件

...
subscribeToMore({
  document: MESSAGE_SUBSCRIPTION,
  variables: {
    data: {
      _id: params._id,
    },
  },
  updateQuery: (prev, { subscriptionData }) => {
    if (!subscriptionData.data) return prev
    console.log(prev, subscriptionData)

    return prev
  },
})
...

当我在操场上尝试订阅时,一切正常。

标签: javascriptreact-nativegraphql

解决方案


我的 apolloClient 的配置缺少 websocket 连接。

我还需要将授权添加为参数,以将其作为上下文

const wsLink = new WebSocketLink({
  uri: Platform.select({
    ios: 'ws://localhost:4000/',
    android: 'ws://10.0.2.2:4000/',
  }),
  options: {
    reconnect: true,
    connectionParams: async () => {
      const result = await getToken()

      return {
        authorization: result ? `Bearer ${result.password}` : '',
      }
    },
  },
})

....


export const client = new ApolloClient({
  link: split(
    ({ query }) => {
      const definition = getMainDefinition(query)
      return (
        definition.kind === 'OperationDefinition' &&
        definition.operation === 'subscription'
      )
    },
    authLink.concat(wsLink as any),
    authLink.concat(httpLink as any)
  ),
  cache: new InMemoryCache(),
})

推荐阅读