不能在React中使用addGraphQLSubscriptions,状态"对象(...)未定义)"

时间:2017-09-29 02:09:45

标签: javascript reactjs graphql graphql-js react-apollo

我目前在我的graphql和reactJS应用上使用.then(() => { return truncateTable(models.User, trx); }) .then(() => { console.log('TRUNCATE FINISHED'); return knex.raw('SET foreign_key_checks = 1;').transacting(trx); }) .catch((err) => { throw err; }); 作为订阅客户端。但是,这行代码返回'subscriptions-transport-ws'

代码是:

Object(...) is not a function

代码断开的地方:

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();

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

2 个答案:

答案 0 :(得分: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

(免责声明:我写过这些)

答案 1 :(得分:1)

所以函数const networkInterfaceWithSubscriptions = addGraphQLSubscriptions( networkInterface, wsClient ) 已被弃用,虽然它们目前尚未修复,但您可以使用

addGraphQLSubscriptions

并将其导入index.js应用

npm i --save add-graphql-subscriptions

此外,我还必须使用import { addGraphQLSubscriptions } from 'add-graphql-subscriptions';版本0.7才能使其正常运行。