Search code examples
cachingapollo-clientapollo-cache-inmemorytypepolicies

Apollo Client: Is there a way to define Apollo Client type policy after the client object is created?


So it all started when I found that two queries were using the same cache ID, causing the queries be overwritten in the cache.

export const ArtworkMastersQuery = gql`
  query ARTWORK_MASTERS_QUERY($page: Int!, $perPage: Int) {
    sessionStatus {
      artworkMasters(page: $page, perPage: $perPage) {
        ...
      }
    }
  }
`

Response: https://share.getcloudapp.com/4guXQ6gB

export const SessionStatusQuery = gql`
  query SESSION_STATUS_QUERY {
    sessionStatus {
      adminUserId
      cart {
        ...
      }
      user {
        ...
      }
    }
  }
`

Response: https://share.getcloudapp.com/rRuzy4eb

Setting merge: true when instantiating apollo client fixed the issue.

  return new ApolloClient({
    connectToDevTools: !isServer,
    // disable forceFetch when SSR, run query only once
    ssrMode: isServer,
    link: headersLink.concat(httpLink),
    cache: new InMemoryCache({
      typePolicies: {
        SessionStatus: {
          merge: true
        }
      }
    }).restore(initialState || {}),

But the problem is that the file where we instantiate apollo is shared among several services. I would like to change the type policy only for my service.

I believe it could be overkill to duplicate the entire file (and several others) just to add one policy.

Is there a way I can do this without having to duplicate the files? I tried to find a method to update the type policy during runtime, but no luck.


Solution

  • You can add/modify type policies at a later point in time by using cache.policies.addTypePolicies

    cache.policies.addTypePolicies({
      SessionStatus: {
        merge: true,
      },
    });