Skip to content

Derive maxAge from function return value? #213

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

Open
gregory-j-baker opened this issue Mar 10, 2024 · 1 comment
Open

Derive maxAge from function return value? #213

gregory-j-baker opened this issue Mar 10, 2024 · 1 comment

Comments

@gregory-j-baker
Copy link

Is it possible to set a cache's maxAge according to the value that is returned by the memoized function?

I am fetching an OAuth access token which has an expires_in value, and I would like to cache the token for approximately as long as it is valid. The problem is that the value of expires_in is set by the remote auth server and is unknown until I actually fetch the token.

@planttheidea
Copy link
Owner

planttheidea commented Jan 4, 2025

Is it possible to set a cache's maxAge according to the value that is returned by the memoized function?

Unfortunately not; it is a configuration option for the cache, and is therefore static for the life of that function. However, you may be able to manually implement a manual cache removal by using some of the lifecycle methods.

If you leverage the onCacheAdd method to manually trigger a deletion with a setTimeout whenever a new value is added to the cache. A pseudo-code example:

const dynamicMaxAge = moize(fn, {
  async onCacheAdd(cache) {
    const addedKey = cache.keys[0];
    const addedValue = await cache.values[0];

    setTimeout(() => {
      cache.remove(addedKey);
    }, addedValue.expires_in);
  },
  isPromise: true,
});

If you wanted the value to reset when the cache was hit you'll likely need to get more creative (managing your own key => timeoutId cache to clear and restart the timeout), but something like this may give you what you seek. The maxAge option is basically just an automated version of this with some performance tweaks.

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

No branches or pull requests

2 participants