graphql / dataloader

DataLoader is a generic utility to be used as part of your application's data fetching layer to provide a consistent API over various backends and reduce requests to those backends via batching and caching.
MIT License
12.89k stars 515 forks source link

✨ [REQUEST]: Add examples for cacheKeyFn and cacheMap #315

Open hinogi opened 2 years ago

hinogi commented 2 years ago

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.

dougg0k commented 1 year ago

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

carsondarling commented 1 year ago

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}`;
    },
  },
);