Derive `maxAge` from function return value?
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.
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.
@gregory-j-baker - I know this issue is kind of ancient 😅 but I've circled back around to it have a working prototype. I've published a new beta version, so if you are willing to check it out and make sure it matches your expectations I'd appreciate it. You can install it via:
npm install moize@next
// or
yarn add moize@next
I have actually decided to deprecate this package in favor of micro-memoize, a much smaller memoization library that this library was built on. I was able to build almost all the functionality this library has into that one, in a smaller package that was also faster!
In addition to porting over that functionality, I have included this requested feature via the expires option in micro-memoize. As such, I'm closing.