nuxt-modules / apollo

Nuxt.js module to use Vue-Apollo. The Apollo integration for GraphQL.
https://apollo.nuxtjs.org
MIT License
945 stars 199 forks source link

How do I define `InMemoryCache` options? #542

Open munjalpatel opened 1 year ago

munjalpatel commented 1 year ago

Your use case

I want to define caching behavior by specifying custom merge function in InMemoryCache because I am getting the following errors in console.

Cache data may be lost when replacing the reviews_reviews field of a Subscription object.

This could cause additional (usually avoidable) network requests to fetch data that were otherwise cached.

To address this problem (which is not a bug in Apollo Client), define a custom merge function for the Subscription.reviews_reviews field, so InMemoryCache can safely merge these objects:

  existing: [object Object],[object Object],[object Object]
  incoming: [object Object],[object Object]

For more information about these options, please refer to the documentation:

  * Ensuring entity objects have IDs: https://go.apollo.dev/c/generating-unique-identifiers
  * Defining custom merge functions: https://go.apollo.dev/c/merging-non-normalized-objects

But I couldn't find a way to do this in Nuxt Apollo.

The solution you'd like

Allow customizing InMemoryCache

Possible alternatives

No response

Additional information

No response

itpropro commented 1 year ago

For advanced cases, I normally use @vue/apollo-composable directly with something similar to this custom plugin setup:

apolloPlugin.ts:

import {
  DefaultApolloClient,
  provideApolloClient,
} from '@vue/apollo-composable';
import {
  ApolloClient,
  createHttpLink,
  InMemoryCache,
} from '@apollo/client/core';

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.hook('vue:setup', () => {
    const {
      $config: { baseUrl },
    } = useNuxtApp();
    const httpLink = createHttpLink({
      uri: `${baseUrl}/graphql`,
    });
    const cache = new InMemoryCache({
      typePolicies: {
        Users: {
          fields: {
            details: {
              merge(_, incoming) {
                return incoming;
              },
            },
          },
        },
      },
    });
    const apolloClient = new ApolloClient({
      link: httpLink,
      cache,
    });
    provideApolloClient(apolloClient);
    nuxtApp.provide('apollo', { DefaultApolloClient, apolloClient });
  });
});

And always remember to have a proper id field on all objects and subfields you want to work with, the apollo cache will not work otherwise.