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

Support defining `read` & `merge` functions in `InMemoryCache` #443

Open QiroNT opened 1 year ago

QiroNT commented 1 year ago

Apollo supports defining read & merge function for fields in InMemoryCache (https://www.apollographql.com/docs/react/caching/cache-field-behavior), which is critical for advanced caching and custom scalars.

But that involves defining functions inside inMemoryCacheOptions.

({
  inMemoryCacheOptions: {
    typePolicies: {
      Person: {
        fields: {
          name: {
            read(name) {
              // Return the cached name, transformed to upper case
              return name.toUpperCase()
            },
          },
        },
      },
    },
  },
})

As far as I can tell, the functions will be ignored because of the use of JSON.stringify in here: https://github.com/nuxt-modules/apollo/blob/1f52586ab7ae3944b0cbfccc01c893ca3c9c8df9/src/module.ts#L104-L114

My best thought around solving this would be to provide a hook to register inMemoryCacheOptions instead of defining it in nuxt.config, kinds of like how Nuxt does for titleTemplate.

However, nuxt.config does not allow the page title to be dynamic. Therefore, it is recommended to use titleTemplate in the app.vue file to add a dynamic title, which is then applied to all routes of your Nuxt app.

Hope it could be supported!

PssbleTrngle commented 1 year ago

Having the option to define typePolicies and other InMemory cache optional that require functions would be great

soeren-krueger commented 10 months ago

I couldn't get the official Apollo example from above to work, but this works fine now:

read: (name) => {
  // Return the cached name, transformed to upper case
  return name.toUpperCase()
}