dataloader icon indicating copy to clipboard operation
dataloader copied to clipboard

✨ [REQUEST]: Add examples for cacheKeyFn and cacheMap

Open hinogi opened this issue 3 years ago • 2 comments

What problem are you trying to solve?

The api documentation does not show how a different cacheMap or a custom cacheKeyFn should look like, for example if you have a composite keys.

Describe the solution you'd like

Add more examples to the documentation.

hinogi avatar Sep 19 '22 22:09 hinogi

A cacheKeyFn always returns a key. So whatever you receive through the key param, you can choose a value to turn into a key (string), if not yet a string.

cacheMap seems to use ES6 Map by default and you can also see the example from lru_map. Follow the type https://github.com/graphql/dataloader/blob/main/src/index.js#L27

dougg0k avatar Jan 06 '23 19:01 dougg0k

I'd love to second this request, with a specific callout for Typescript examples.

It took me longer than I want to admit to realize that there was a third type available on the DataLoader generic to specify the type for the cache key. The current documentation implies that the return type of the cacheKeyFn is the same type as the key:

image

If I end up with spare time at the end of this cycle I'll try to pull together a documentation PR, but for the sake of anyone else searching for an answer to this problem, my basic example looks like this:

type KeyType = { type: string; id: string };
type CacheKeyType = string;
type ValueType = any;

const loader = new DataLoader<KeyType, ValueType, CacheKeyType>(
  async (keys: readonly KeyType[]) => {
    const values = await loadValues(keys);
    return values;
  },
  {
    cacheKeyFn(key: KeyType): string {
      return `${key.type}:${key.id}`;
    },
  },
);

carsondarling avatar Sep 20 '23 17:09 carsondarling