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

时间:2017-06-06 13:42:47

标签: graphql react-apollo apollo-client

我需要向graphql端点发出自己的请求。 (默认实现使POST调用我们指定的url)。我需要进行一次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响应(它应该发送)。

即使在此之后,我的浏览器出现了一些错误,因为我无法显示从我的服务器获取的数据。组件始终处于“加载”状态。

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)

1 个答案:

答案 0 :(得分:0)

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

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

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')
)