0
votes

I am creating an app using React and the Apollo Graphql client. This app must have a local resolver to retrieve data from a legacy REST API and write it to the cache.

What I expect from this resolver is that it will first try to get the data from the local cache and then if it is not there, it will fetch it from the legacy API. However sometimes this data is also updated by other parts of my application, so in this case I would like the resolver to ignore the cache and go directly to the legacy API.

I know that what I described above is similar to the fetchPolicies that the Apollo Client provides: the first scenario would be cache-first and the second would be network-only and I would like to use them to determine my resolver's behavior.

However I wasn't able to find the fetchPolicy in my resolver's arguments. The resolver's function signature that I am using now is this:

export async function customerData(
  root: any,
  variables: any,
  context: { client: ApolloClient<any>; cache: InMemoryCache; getCacheKey: any },
  info: any
): Promise<CustomerData | null> {
  console.log('root', root);
  console.log('variables', variables);
  console.log('context', context);
  console.log('info', info);

  return null;
}

And the fetch policy is not avaible.

Is there a way to know the chosen fetchPolicy when a local resolver is executed? Or is there another way to solve this problem?

Note 1: I know that I could just send the fetchPolicy along with the resolver's variables, but I was looking for a more elegant solution that would leverage what we already have in Apollo.

Note 2: I could also use the Apollo Link Rest for this, instead of writing my own resolver and have it call fetch or axios to retrieve the data. But I would not like to use it, because it does not support any timeout configuration and since my app is meant to be executed in environments with bad internet connection, I don't want it to try to fetch data indefinetly.

1

1 Answers

1
votes

I just saw this part of the Apollo client documentation that I think I missed before: https://www.apollographql.com/docs/react/data/local-state/#working-with-fetch-policies.

Basically it says that the fetch-policies are evaluated before the resolver is called and that they work just like when calling a remote resolver.

So, I ran some tests and by using the default policy (cache-first), my resolver is called only once and the rest of the times the result is returned directly from the cache.

If I change the fetch-policy to network-only than my resolver function is always called.