light24bulbs
light24bulbs

Reputation: 3161

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.

Upvotes: 2

Views: 1446

Answers (1)

light24bulbs
light24bulbs

Reputation: 3161

I posted the same question on the Apollo forums and received the answer that, remarkably, they don't support setting specific cache times or invalidating the cache from the read function of the typePolicies. It is apparently on the roadmap.

A third party caching library was suggested instead: https://github.com/NerdWalletOSS/apollo-cache-policies

Looking in the "Why does this exist?" in the NerdWallet README, you can see they mention that this is a common pain point with the InMemoryCache

Upvotes: 0

Related Questions