CacheKeyResolver

Hi All, :wave:

According to the documentation, “CacheKeyResolvers enables you to generate custom cache IDs from a field’s arguments”
Based on my understanding, the CacheKeyResolver should be aware of the argument it needs to generate the custom CacheKey.
i.e

val cacheKeyResolver = object: CacheKeyResolver() {
  override fun cacheKeyForField(field: CompiledField, variables: Executable.Variables): CacheKey? {
...
// resolveArgument returns the runtime value of the "id" argument
    // from either the variables or as a literal value
    val id = field.resolveArgument("id", variables)
...
    }
}

As shown above, this excerpt of the CacheKeyResolver logic from the documentation would work fairly well if all the graphql operations use id as the name of the argument representing an id. But what if the names of id field argument varies from id to empid to employeeid?
In that case, CacheKeyResolver would have to keep track of every possible argument, in a set or map, that is used to represent an id and eventually use this set to determine if a field argument is an id. Note, the id in my schema is a String! which guarantees to generate a unique string for every object.

I also noticed that the CompiledArgument class, contains a field called isKey.
Just curious, when would its value be set to true :thinking: ?

There are a few ways to get past this but they seem a little verbose to me.
I just thought it would be good idea to check with the community.
Eager to know everybody’s thoughts. :slight_smile:

Thanks!

Hi :wave:

But what if the names of id field argument varies from id to empid to employeeid ?

You can decide based on __typename:

val cacheKeyGenerator = object : CacheKeyGenerator {
  override fun cacheKeyForObject(obj: Map<String, Any?>, context: CacheKeyGeneratorContext): CacheKey? {
    val typename = obj["__typename"] as String
    val id = when (typename) {
      "Employee" -> obj["employeeid"] as String
      // More cases here
      else -> obj["id"] as String
    }

    return CacheKey(typename, id)
  }
}

I also noticed that the CompiledArgument class, contains a field called isKey .
Just curious, when would its value be set to true :thinking: ?

This is used if you use the declarative cache feature

Hope this helps!

1 Like