无法在React中使用addGraphQLSubscriptions,状态“对象(...)未定义)”

问题描述:

我目前使用'subscriptions-transport-ws'作为我的graphql和reactJS应用程序上的订阅客户端。然而这行代码返回Object(...) is not a function无法在React中使用addGraphQLSubscriptions,状态“对象(...)未定义)”

的代码:

import App from './components/App'; 
import registerServiceWorker from './registerServiceWorker'; 
import { ApolloProvider, createNetworkInterface, ApolloClient } from 'react-apollo' 
import { SubscriptionClient, addGraphQLSubscriptions } from 'subscriptions-transport-ws' 

const networkInterface = createNetworkInterface({ 
    uri: '_GRAPHQL_END_POINT_' 
}) 
const wsClient = new SubscriptionClient('_SUBSCRIPTION_END_POINT', { 
    reconnect: true, 
}) 
const networkInterfaceWithSubscriptions = addGraphQLSubscriptions(
    networkInterface, 
    wsClient 
) 
const client = new ApolloClient({ 
    networkInterface: networkInterfaceWithSubscriptions 
}) 
ReactDOM.render(
    <BrowserRouter> 
     <ApolloProvider client={client}> 
      <App /> 
     </ApolloProvider> 
    </BrowserRouter> 
    , document.getElementById('root') 
) 
registerServiceWorker(); 

凡在代码中断:

const networkInterfaceWithSubscriptions = addGraphQLSubscriptions(
     networkInterface, 
     wsClient 
    ) 

我该如何解决这个问题? 相关文章:https://github.com/apollographql/subscriptions-transport-ws/issues/169 https://github.com/apollographql/subscriptions-transport-ws/pull/272

所以功能addGraphQLSubscriptions已过时,但他们没有固定的,截至目前,您可以使用

npm i --save add-graphql-subscriptions

并将其导入到你的index.js应用

import { addGraphQLSubscriptions } from 'add-graphql-subscriptions';

此外,我不得不使用subscriptions-transport-ws版本0.7以及让它工作。

支持networkInterfaceaddGraphQLSubscriptions已被放弃,以支持Apollo的新apollo-link

新的客户端代码将是这个样子:

import { ApolloClient } from 'apollo-client'; 
import { ApolloLink } from 'apollo-link'; 
import { HttpLink } from 'apollo-link-http'; 
import WebSocketLink from 'apollo-link-ws'; 
import Cache from 'apollo-cache-inmemory'; 
import { getOperationAST } from 'graphql'; 

const httpUri = '_GRAPHQL_END_POINT_'; 
const wsUri = '_SUBSCRIPTION_END_POINT'; 

const link = ApolloLink.split(
    operation => { 
    const operationAST = getOperationAST(operation.query, operation.operationName); 
    return !!operationAST && operationAST.operation === 'subscription'; 
    }, 
    new WebSocketLink({ 
    uri: wsUri, 
    options: { 
     reconnect: true, //auto-reconnect 
     // // carry login state (should use secure websockets (wss) when using this) 
     // connectionParams: { 
     // authToken: localStorage.getItem("authToken") 
     // } 
    } 
    }), 
    new HttpLink({ uri: httpUri }) 
); 

const cache = new Cache(window.__APOLLO_STATE); 

const client = new ApolloClient({ 
    link, 
    cache 
}); 

来源:

How to get Apollo 2.0 working with GraphQL + subscriptions

Apollo 2.0 w/subscriptions example app

(声明:我写这些)