How can I specify maximum cache-time for any data matching a regex in apollo-client with InMemoryCache?

Some fields coming from the graphql server will have the shape short-lived-token-XYZ123 . Ideally we wouldn’t even have to know the field names ahead of time, as any code we write will live in a library. How can I hook into the InMemoryCache or the ApolloClient object to set the cache time of fields with values matching a regex? Causing them to poll at a set interval would be really ideal, but because polling is query-centric, I dont think that is possible at the field level. Giving them a specific cache time would be enough. Is there a way to hook into the InMemoryCache with a function that gets called on every read?

Another option would be to make these token strings a graphql type Token like

type Token {
    id: String
}

and then in the client it might be possible to define a custom cache behavior for this type when initializing the cache like

new InMemoryCache({
  typePolicies: {
    Token: {
      fields: {
        id: {
          read(cachedVal) {
            if (cacheTimeElapsed){
                return null
            } else {
                return cachedVal
            }
           
          }
        }
      },
    },
  },

But Im also unclear HOW to bust the cache using the read function. What do I return from the function to tell the cache that it is busted and needs to refetch? These docs are…challenging. If I could just call a function on every single read and do what I need to do, that would be ideal.

These fields will also be annotated in the apollo-server with @token (for other reasons), and we could potentially hook in here to somehow tell the client to cache-bust these fields. Not sure how, but it’s another option.

@Forrest_Allison time based cache expiration capabilities aren’t currently provided by Apollo Client out of the box (it’s on our roadmap), but there are 3rd party community solutions that might help, like @nerdwallet/apollo-cache-policies.

That’s surprising but I’m happy to use the third party lib. In your inMemoryCache, isn’t there even a way to bust the cache manually in that read function? It’s not mentioned in the docs, just alluded to. What happens if the cache returns null from read? Is there no way for the read function to tell the query that requested the field to skip the cache and fire a web request? Or can it only overwrite the value of the field?

Ah, nevermind. I can see in the “Why does this exist?” of the library you linked that they explain all these shortcomings. Thank you very much for turning me onto it!

1 Like