Cat logomenu

Apollo getCacheKey() with TypeScript

I’m currently working on the front end of an app that uses React + Apollo (via apollo-boost) + TypeScript. I’m to the point where I’m retrieving items from the cache in my resolvers using fragments1, which means I need to use getCacheKey() to search for the item’s cache key using its ID field. (In this app, it would probably work to just assume the cache key is TypeName:UUID, but you never know, so we should probably do things properly.)

Unfortunately, I have not been able to find the correct typings for getCacheKey(). When passing in cache as an argument to a resolver, one can import NormalizedCacheObject for the typings, like so:

import { ApolloCache } from 'apollo-cache'
import { NormalizedCacheObject } from 'apollo-boost'

...

Mutation: {
  resolveSomeStuff: (
    _: undefined,
    { itemId, itemOptions }: { itemId: string; itemOptions: Array<string> },
    { cache }: { cache: ApolloCache<NormalizedCacheObject> }
  ) => {
  /* Now we resolve everything. Global warming, world
  hunger, over- and under-population.... */
  ...
  }
}

Inside my resolver, the Apollo docs tell me to get an item’s cacheKey like this:

const cacheKey = cache.getCacheKey({ __typename: "Item", id: itemId })

Unfortunately, if I use this formulation, tslint will yell at me:

“Property ‘getCacheKey’ does not exist on type ‘ApolloCache’.”

Well.

Half an hour of Googling was unhelpful. But eventually I found someone reporting a similar-sounding problem as an issue over at the apollo devtools repo. I adopted his workaround, and it was effective for me. So here is the code inside my resolver:

const cacheKey = cache["config"].dataIdFromObject({
  __typename: "Item",
  id: itemId,
})

This essentially does an end run around the problem by not calling getCacheKey() at all. I don’t know enough about the inner workings of the Apollo client to understand why this works, but I kind of don’t care.


  1. If you don’t know what some or all of that means, this post probably isn’t for you.

Give us a share!