与在 ApolloClient 中创建 NetworkInterface 相关的问题

Issue related to creating NetworkInterface in ApolloClient

我需要向 graphql 端点发出自己的请求。 (默认实现对我们指定的 url 进行 POST 调用)。我需要拨打 AJAX 电话。我读自: http://dev.apollodata.com/core/network.html#custom-network-interface

它明确指出我需要创建一个NetworkInterface并将其传递给ApolloClient。

我做了这样的事情:

const customInterface = {
    query(request) {
        return $.post(url_of_graphql_endpoint)
            .send({query : request.query.loc.source.body})
            .end()
            .then(result => result.text)    
    }
}

const client = new ApolloClient({networkInterface: customInterface});

ReactDOM.render((
  <ApolloProvider client={client}>
    <Router history={browserHistory}>
      <Route path='/' component={App} />
    </Router>
  </ApolloProvider>
  ),
  document.getElementById('root')
)

正在向 graphql 端点发出网络请求,服务器也响应 apt 响应(它应该发送)。

即使在这之后,我的浏览器仍然出现一些错误,因此我无法显示从我的服务器获取的数据。该组件始终处于 'loading' 状态。

Error in observer.error 
Error
    at new ApolloError (<URL>:12345/bundle.js:22220:23)
    at <URL>:12345/bundle.js:21680:39
    at <URL>:12345/bundle.js:22168:25
    at Array.forEach (native)
    at <URL>:12345/bundle.js:22165:27
    at <URL>:12345/bundle.js:81569:11
    at baseForOwn (<URL>:12345/bundle.js:47066:20)
    at forOwn (<URL>:12345/bundle.js:82561:20)
    at QueryManager.broadcastQueries (<URL>:12345/bundle.js:22163:9)
    at Array.<anonymous> (<URL>:12345/bundle.js:21595:23)
    at dispatch (<URL>:12345/bundle.js:56461:19)
    at <URL>:12345/bundle.js:64699:30
    at Object.dispatch (<URL>:12345/bundle.js:17264:16)
    at <URL>:12345/bundle.js:22130:33
    at tryCatcher (<URL>:12345/bundle.js:7247:23)
    at Promise._settlePromiseFromHandler (<URL>:12345/bundle.js:5269:31)
    at Promise._settlePromise (<URL>:12345/bundle.js:5326:18)
    at Promise._settlePromise0 (<URL>:12345/bundle.js:5371:10)
    at Promise._settlePromises (<URL>:12345/bundle.js:5446:18)
    at <URL>:12345/bundle.js:2169:25
    at MutationObserver.<anonymous> (<URL>:12345/bundle.js:6501:17)

我能够覆盖查询方法的功能,所以我只为可能面临相同问题的其他人发布答案。

我尝试覆盖查询方法的方式是错误的。我是这样做的。

class CustomNetworkInterface extends HttpNetworkInterface{
    query(request){
                return $.post(url_of_graphql_endpoint)
            .send({query : request.query.loc.source.body})
            .end()
            .then(result => result.text)    
    }
}

制作ApolloClient,传入CustomNetworkInterface对象即可。

const client = new ApolloClient({networkInterface: new CustomNetworkInterface(http://url)});

ReactDOM.render((
  <ApolloProvider client={client}>
    <Router history={browserHistory}>
      <Route path='/' component={App} />
    </Router>
  </ApolloProvider>
  ),
  document.getElementById('root')
)