2017-09-29 86 views
0

我目前使用'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

回答

1

所以功能addGraphQLSubscriptions已過時,但他們沒有固定的,截至目前,您可以使用

npm i --save add-graphql-subscriptions

並將其導入到你的index.js應用

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

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

3

支持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

(聲明:我寫這些)

相關問題