apollo icon indicating copy to clipboard operation
apollo copied to clipboard

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

Open QiroNT opened this issue 3 years ago • 2 comments

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!

QiroNT avatar Oct 28 '22 13:10 QiroNT

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

PssbleTrngle avatar Nov 26 '22 10:11 PssbleTrngle

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()
}

soeren-krueger avatar Nov 29 '23 21:11 soeren-krueger