Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
hinogi opened this issue Sep 19, 2022 · 2 comments
Open

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

hinogi opened this issue Sep 19, 2022 · 2 comments

Comments

@hinogi
Copy link

hinogi commented Sep 19, 2022

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
Copy link

dougg0k commented Jan 6, 2023

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
Copy link

carsondarling commented Sep 20, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants