最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set a timeout on a request with Apollo-Client - Stack Overflow

programmeradmin1浏览0评论

I have a React-Native app where I make requests to a GraphQL server. Everything works fine except I need a way to set the timeout on the request/client to 5 or 10 seconds. Currently the request takes a very long time before it times out (around 1 minute).

Here's a quick example of how I use the client.

const client = new ApolloClient({
  networkInterface: createNetworkInterface({
    uri: `${config.server_hostname}/graphql`
  })
});

client.query({ query: gqlString });

I have been unable to find any solution through StackOverflow, google search or Apollo's documentation.

I have a React-Native app where I make requests to a GraphQL server. Everything works fine except I need a way to set the timeout on the request/client to 5 or 10 seconds. Currently the request takes a very long time before it times out (around 1 minute).

Here's a quick example of how I use the client.

const client = new ApolloClient({
  networkInterface: createNetworkInterface({
    uri: `${config.server_hostname}/graphql`
  })
});

client.query({ query: gqlString });

I have been unable to find any solution through StackOverflow, google search or Apollo's documentation.

Share Improve this question asked Nov 9, 2017 at 9:38 menderleitmenderleit 1711 gold badge1 silver badge4 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 7

The Apollo client uses (v1.9 and apollo-link-http) the fetch API to send the requests. Therefore there is no cross-browser way to abort a fetch. You could create you own Networkinterface or Link and use something like this:

const oldfetch = fetch;
fetch = function(input, opts) {
  return new Promise((resolve, reject) => {
      setTimeout(reject, opts.timeout);
      oldfetch(input, opts).then(resolve, reject);
  });
}

But be careful as this doesn't actually abort the request. You can end up with a lot running requests and hit a browser limit.

BTW it looks like apollo-link-http is prepared for the AbortController ;-)

I had the same issue and used the following from npm documentation. You can now control how long a request can wait before being aborted:

import ApolloLinkTimeout from 'apollo-link-timeout';
import { createHttpLink } from 'apollo-link-http';
import { ApolloClient } from 'apollo-client';

...

const timeoutLink = new ApolloLinkTimeout(10000); // 10 second timeout

const httpLink = createHttpLink({ uri: "/graphql" });

const timeoutHttpLink = timeoutLink.concat(httpLink);

const apolloClient = new ApolloClient({ link: timeoutHttpLink });

// use timeout-enabled Apollo client...

// Override timeout from any query 
<Query
 query={SOME_QUERY}
 variables={{
    someVar1: "foo",
    someVar2: "bar",
   }}
  context={{ timeout: 3000 }}
>
// ...
发布评论

评论列表(0)

  1. 暂无评论